diff --git a/Examples/ExampleAssistantV1.cs b/Examples/ExampleAssistantV1.cs index 17b0ec31b..34a705321 100644 --- a/Examples/ExampleAssistantV1.cs +++ b/Examples/ExampleAssistantV1.cs @@ -20,6 +20,8 @@ using UnityEngine; using IBM.Watson.Assistant.V1; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Assistant.V1.Model; using System; @@ -104,12 +106,15 @@ private void Start() private IEnumerator CreateService() { - service = new AssistantService("2019-02-18"); - // Wait for authorization token - while (!service.Credentials.HasIamTokenData()) + IamAuthenticator authenticator = new IamAuthenticator(apikey: "{iamApikey}"); + + // Wait for tokendata + while (!authenticator.CanAuthenticate()) yield return null; + service = new AssistantService("2019-02-18", authenticator); + workspaceId = Environment.GetEnvironmentVariable("CONVERSATION_WORKSPACE_ID"); Runnable.Run(Examples()); } @@ -118,7 +123,7 @@ private IEnumerator Examples() { // List Workspaces Log.Debug("ExampleAssistantV1", "Attempting to ListWorkspaces..."); - service.ListWorkspaces(callback: OnListWorkspaces, pageLimit: 1, includeCount: true, sort: "-name", includeAudit: true); + service.ListWorkspaces(callback: OnListWorkspaces, pageLimit: 1, sort: "-name", includeAudit: true); while (!listWorkspacesTested) yield return null; diff --git a/Examples/ExampleAssistantV2.cs b/Examples/ExampleAssistantV2.cs index 277a62d22..e92c0984c 100644 --- a/Examples/ExampleAssistantV2.cs +++ b/Examples/ExampleAssistantV2.cs @@ -18,6 +18,8 @@ using System.Collections; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Assistant.V2; using IBM.Watson.Assistant.V2.Model; @@ -68,21 +70,13 @@ private IEnumerator CreateService() } // Create credential and instantiate service - Credentials credentials = null; - - // Authenticate using iamApikey - TokenOptions tokenOptions = new TokenOptions() - { - IamApiKey = iamApikey - }; - - credentials = new Credentials(tokenOptions, serviceUrl); + IamAuthenticator authenticator = new IamAuthenticator(apikey: iamApikey); // Wait for tokendata - while (!credentials.HasIamTokenData()) + while (!authenticator.CanAuthenticate()) yield return null; - service = new AssistantService(versionDate, credentials); + service = new AssistantService(versionDate, authenticator); Runnable.Run(Examples()); } diff --git a/Examples/ExampleDiscoveryV1.cs b/Examples/ExampleDiscoveryV1.cs new file mode 100644 index 000000000..cb79ef48a --- /dev/null +++ b/Examples/ExampleDiscoveryV1.cs @@ -0,0 +1,89 @@ +using IBM.Watson.Discovery.V1; +using IBM.Watson.Discovery.V1.Model; +using IBM.Cloud.SDK.Utilities; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using IBM.Cloud.SDK; + +public class ExampleDiscoveryV1 : MonoBehaviour +{ + #region PLEASE SET THESE VARIABLES IN THE INSPECTOR + [Space(10)] + [Tooltip("The IAM apikey.")] + [SerializeField] + private string iamApikey; + [Tooltip("The service URL (optional). This defaults to \"https://gateway.watsonplatform.net/discovery/api\"")] + [SerializeField] + private string serviceUrl; + [Tooltip("The version date with which you would like to use the service in the form YYYY-MM-DD.")] + [SerializeField] + private string versionDate; + #endregion + + private DiscoveryService service; + // Start is called before the first frame update + void Start() + { + LogSystem.InstallDefaultReactors(); + Runnable.Run(CreateService()); + } + + // Update is called once per frame + public IEnumerator CreateService() + { + if (string.IsNullOrEmpty(iamApikey)) + { + throw new IBMException("Plesae provide IAM ApiKey for the service."); + } + + // Create credential and instantiate service + IamAuthenticator authenticator = new IamAuthenticator(apikey: iamApikey); + + // Wait for tokendata + while (!authenticator.CanAuthenticate()) + yield return null; + + service = new DiscoveryService(versionDate, authenticator); + + + Runnable.Run(ExampleCreateEnvironment()); + Runnable.Run(ExampleListEnvironments()); + } + + private IEnumerator ExampleCreateEnvironment() + { + ModelEnvironment createEnvironmentResponse = null; + service.CreateEnvironment( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("DiscoveryServiceV1", "CreateEnvironment result: {0}", response.Response); + createEnvironmentResponse = response.Result; + // environmentId = createEnvironmentResponse.EnvironmentId; + }, + name: "my_environment", + description: "My environment" + ); + + while (createEnvironmentResponse == null) + yield return null; + } + + private IEnumerator ExampleListEnvironments() + { + Log.Debug("DiscoveryServiceV1", "ListEnvironments"); + ListEnvironmentsResponse listEnvironmentsResponse = null; + service.ListEnvironments( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("DiscoveryServiceV1", "ListEnvironments result: {0}", response.Response); + listEnvironmentsResponse = response.Result; + } + ); + + while (listEnvironmentsResponse == null) + yield return null; + } +} \ No newline at end of file diff --git a/Examples/ExampleDiscoveryV1.cs.meta b/Examples/ExampleDiscoveryV1.cs.meta new file mode 100644 index 000000000..b72cb2956 --- /dev/null +++ b/Examples/ExampleDiscoveryV1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c8cc5579d4a384f8ca87dccdf800981f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ExampleDiscoveryV1.unity b/Examples/ExampleDiscoveryV1.unity new file mode 100644 index 000000000..32f8fdb64 --- /dev/null +++ b/Examples/ExampleDiscoveryV1.unity @@ -0,0 +1,168 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &444819960 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 444819963} + - component: {fileID: 444819961} + m_Layer: 0 + m_Name: ExampleDiscoveryV1 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &444819961 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 444819960} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c8cc5579d4a384f8ca87dccdf800981f, type: 3} + m_Name: + m_EditorClassIdentifier: + iamApikey: S + serviceUrl: S + versionDate: 2019-09-16 +--- !u!4 &444819963 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 444819960} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/Examples/ExampleDiscoveryV1.unity.meta b/Examples/ExampleDiscoveryV1.unity.meta new file mode 100644 index 000000000..13ccdc994 --- /dev/null +++ b/Examples/ExampleDiscoveryV1.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 9dd94e07480dd434883ee65b9c8e50bb +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ExampleLanguageTranslatorV3.cs b/Examples/ExampleLanguageTranslatorV3.cs new file mode 100644 index 000000000..4e1af12f6 --- /dev/null +++ b/Examples/ExampleLanguageTranslatorV3.cs @@ -0,0 +1,72 @@ +using IBM.Watson.LanguageTranslator.V3; +using IBM.Watson.LanguageTranslator.V3.Model; +using IBM.Cloud.SDK.Utilities; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using IBM.Cloud.SDK; + +public class ExampleLanguageTranslatorV3 : MonoBehaviour +{ + #region PLEASE SET THESE VARIABLES IN THE INSPECTOR + [Space(10)] + [Tooltip("The IAM apikey.")] + [SerializeField] + private string iamApikey; + [Tooltip("The service URL (optional). This defaults to \"https://gateway.watsonplatform.net/discovery/api\"")] + [SerializeField] + private string serviceUrl; + [Tooltip("The version date with which you would like to use the service in the form YYYY-MM-DD.")] + [SerializeField] + private string versionDate; + #endregion + + private LanguageTranslatorService service; + // Start is called before the first frame update + void Start() + { + LogSystem.InstallDefaultReactors(); + Runnable.Run(CreateService()); + } + + // Update is called once per frame + public IEnumerator CreateService() + { + if (string.IsNullOrEmpty(iamApikey)) + { + throw new IBMException("Plesae provide IAM ApiKey for the service."); + } + + // Create credential and instantiate service + IamAuthenticator authenticator = new IamAuthenticator(apikey: iamApikey); + + // Wait for tokendata + while (!authenticator.CanAuthenticate()) + yield return null; + + service = new LanguageTranslatorService(versionDate, authenticator); + service.SetServiceUrl("https://api.us-south.language-translator.test.watson.cloud.ibm.com"); + + + Log.Debug("LanguageTranslatorServiceV3", "ListModels result"); + } + + private IEnumerator ExampleListModels() + { + TranslationModels listModelsResponse = null; + service.ListModels( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("LanguageTranslatorServiceV3", "ListModels result: {0}", response.Response); + listModelsResponse = response.Result; + }, + source: "en", + target: "fr" + ); + + while (listModelsResponse == null) + yield return null; + } +} \ No newline at end of file diff --git a/Examples/ExampleLanguageTranslatorV3.cs.meta b/Examples/ExampleLanguageTranslatorV3.cs.meta new file mode 100644 index 000000000..e5e41d24f --- /dev/null +++ b/Examples/ExampleLanguageTranslatorV3.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9a1e352a986b5428ea65dbad0d72f77e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ExampleLanguageTranslatorV3.unity b/Examples/ExampleLanguageTranslatorV3.unity new file mode 100644 index 000000000..3f15c052e --- /dev/null +++ b/Examples/ExampleLanguageTranslatorV3.unity @@ -0,0 +1,168 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &250075178 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 250075181} + - component: {fileID: 250075179} + m_Layer: 0 + m_Name: ExampleLanguageTranslatorV3 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &250075179 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 250075178} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 9a1e352a986b5428ea65dbad0d72f77e, type: 3} + m_Name: + m_EditorClassIdentifier: + iamApikey: s + serviceUrl: s + versionDate: 2019-09-16 +--- !u!4 &250075181 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 250075178} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/Examples/ExampleLanguageTranslatorV3.unity.meta b/Examples/ExampleLanguageTranslatorV3.unity.meta new file mode 100644 index 000000000..0e262e7fc --- /dev/null +++ b/Examples/ExampleLanguageTranslatorV3.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1db2a18e871684a5590b5d13afaa8096 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ExampleNaturalLanguageClassifierV1.cs b/Examples/ExampleNaturalLanguageClassifierV1.cs new file mode 100644 index 000000000..bda5ad4f4 --- /dev/null +++ b/Examples/ExampleNaturalLanguageClassifierV1.cs @@ -0,0 +1,85 @@ +/** +* Copyright 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using IBM.Watson.NaturalLanguageClassifier.V1; +using IBM.Watson.NaturalLanguageClassifier.V1.Model; +using IBM.Cloud.SDK.Utilities; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using IBM.Cloud.SDK; + + +namespace IBM.Watson.Examples +{ + public class ExampleNaturalLanguageClassifierV1 : MonoBehaviour + { + #region PLEASE SET THESE VARIABLES IN THE INSPECTOR + [Space(10)] + [Tooltip("The IAM apikey.")] + [SerializeField] + private string iamApikey; + [Tooltip("The service URL (optional). This defaults to \"https://gateway.watsonplatform.net/natural-language-understanding/api\"")] + [SerializeField] + private string serviceUrl; + #endregion + + private NaturalLanguageClassifierService service; + private string nluText = "IBM is an American multinational technology company headquartered in Armonk, New York, United States with operations in over 170 countries."; + private void Start() + { + LogSystem.InstallDefaultReactors(); + Runnable.Run(CreateService()); + } + + private IEnumerator CreateService() + { + if (string.IsNullOrEmpty(iamApikey)) + { + throw new IBMException("Please add IAM ApiKey to the Iam Apikey field in the inspector."); + } + + IamAuthenticator authenticator = new IamAuthenticator(apikey: iamApikey); + + while (!authenticator.CanAuthenticate()) + { + yield return null; + } + + service = new NaturalLanguageClassifierService(authenticator); + + Runnable.Run(ExampleListClassifiers()); + } + + private IEnumerator ExampleListClassifiers() + { + ClassifierList listClassifiersResponse = null; + service.ListClassifiers( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("NaturalLanguageClassifierServiceV1", "ListClassifiers result: {0}", response.Response); + listClassifiersResponse = response.Result; + } + ); + + while (listClassifiersResponse == null) + yield return null; + } + } +} diff --git a/Examples/ExampleNaturalLanguageClassifierV1.cs.meta b/Examples/ExampleNaturalLanguageClassifierV1.cs.meta new file mode 100644 index 000000000..003fde73d --- /dev/null +++ b/Examples/ExampleNaturalLanguageClassifierV1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b3646f01bb184a2185f421538734ff3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ExampleNaturalLanguageClassifierV1.unity b/Examples/ExampleNaturalLanguageClassifierV1.unity new file mode 100644 index 000000000..731d478da --- /dev/null +++ b/Examples/ExampleNaturalLanguageClassifierV1.unity @@ -0,0 +1,165 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 1 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 1 + m_PVRDenoiserTypeIndirect: 1 + m_PVRDenoiserTypeAO: 1 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &534719662 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 534719665} + - component: {fileID: 534719663} + m_Layer: 0 + m_Name: ExampleNaturalLanguageClassiffierV1 + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &534719663 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 534719662} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6b3646f01bb184a2185f421538734ff3, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &534719665 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 534719662} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} diff --git a/Examples/ExampleNaturalLanguageClassifierV1.unity.meta b/Examples/ExampleNaturalLanguageClassifierV1.unity.meta new file mode 100644 index 000000000..8a8d630fe --- /dev/null +++ b/Examples/ExampleNaturalLanguageClassifierV1.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a25f3447ffa82495985ba0e0516f0343 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ExampleNaturalLanguageUnderstandingV1.cs b/Examples/ExampleNaturalLanguageUnderstandingV1.cs index 53d49dfb1..614839b90 100644 --- a/Examples/ExampleNaturalLanguageUnderstandingV1.cs +++ b/Examples/ExampleNaturalLanguageUnderstandingV1.cs @@ -19,6 +19,7 @@ using IBM.Watson.NaturalLanguageUnderstanding.V1.Model; using IBM.Cloud.SDK.Utilities; using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; using System.Collections; using System.Collections.Generic; using UnityEngine; @@ -57,18 +58,14 @@ private IEnumerator CreateService() throw new IBMException("Please add IAM ApiKey to the Iam Apikey field in the inspector."); } - IamTokenOptions tokenOptions = new IamTokenOptions() - { - IamApiKey = iamApikey - }; - Credentials credentials = new Credentials(tokenOptions, serviceUrl); + IamAuthenticator authenticator = new IamAuthenticator(apikey: iamApikey); - while (!credentials.HasTokenData()) + while (!authenticator.CanAuthenticate()) { yield return null; } - service = new NaturalLanguageUnderstandingService(versionDate, credentials); + service = new NaturalLanguageUnderstandingService(versionDate, authenticator); Runnable.Run(ExampleAnalyze()); Runnable.Run(ExampleListModels()); diff --git a/Examples/ExampleNaturalLanguageUnderstandingV1.unity b/Examples/ExampleNaturalLanguageUnderstandingV1.unity index 6307b28e9..a2fb6bc21 100644 --- a/Examples/ExampleNaturalLanguageUnderstandingV1.unity +++ b/Examples/ExampleNaturalLanguageUnderstandingV1.unity @@ -54,7 +54,7 @@ LightmapSettings: m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 m_LightmapEditorSettings: - serializedVersion: 10 + serializedVersion: 12 m_Resolution: 2 m_BakeResolution: 40 m_AtlasSize: 1024 @@ -62,6 +62,7 @@ LightmapSettings: m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 @@ -76,10 +77,16 @@ LightmapSettings: m_PVRDirectSampleCount: 32 m_PVRSampleCount: 500 m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 500 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 2 + m_PVRDenoiserTypeDirect: 0 + m_PVRDenoiserTypeIndirect: 0 + m_PVRDenoiserTypeAO: 0 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 - m_PVRFilteringMode: 1 + m_PVREnvironmentMIS: 0 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 @@ -87,7 +94,8 @@ LightmapSettings: m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 - m_ShowResolutionOverlay: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 1 --- !u!196 &4 @@ -141,9 +149,9 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: dfdc93e9c48b5475fbceaff19b33d951, type: 3} m_Name: m_EditorClassIdentifier: - iamApikey: - serviceUrl: - versionDate: + iamApikey: 7cIHQv_i4rwRqDd_q3T92pBZ7QFCEewk7rpQU0DyR_ZW + serviceUrl: https://api.us-south.natural-language-understanding.test.watson.cloud.ibm.com + versionDate: 2019-09-16 --- !u!4 &800506887 Transform: m_ObjectHideFlags: 0 diff --git a/Examples/ExamplePersonalityInsightsV3.cs b/Examples/ExamplePersonalityInsightsV3.cs index 31fd8fda4..339c894a4 100644 --- a/Examples/ExamplePersonalityInsightsV3.cs +++ b/Examples/ExamplePersonalityInsightsV3.cs @@ -16,6 +16,8 @@ */ using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; using IBM.Cloud.SDK.Utilities; using IBM.Watson.PersonalityInsights.V3; using IBM.Watson.PersonalityInsights.V3.Model; @@ -35,7 +37,7 @@ public class ExamplePersonalityInsightsV3 : MonoBehaviour private bool profileTested = false; private bool profileAsCsvTested = false; - + private void Start() { LogSystem.InstallDefaultReactors(); @@ -45,12 +47,15 @@ private void Start() private IEnumerator CreateService() { - service = new PersonalityInsightsService("2019-02-18"); - // Wait for authorization token - while (!service.Credentials.HasIamTokenData()) + IamAuthenticator authenticator = new IamAuthenticator(apikey: "{iamApikey}"); + + // Wait for tokendata + while (!authenticator.CanAuthenticate()) yield return null; + service = new PersonalityInsightsService("2019-02-18", authenticator); + Runnable.Run(Examples()); } diff --git a/Examples/ExampleStreaming.cs b/Examples/ExampleStreaming.cs index 2c4d1a97e..cb6ed6fb5 100644 --- a/Examples/ExampleStreaming.cs +++ b/Examples/ExampleStreaming.cs @@ -22,6 +22,8 @@ using UnityEngine.UI; using IBM.Watson.SpeechToText.V1; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; using IBM.Cloud.SDK.Utilities; using IBM.Cloud.SDK.DataTypes; @@ -70,22 +72,13 @@ private IEnumerator CreateService() throw new IBMException("Plesae provide IAM ApiKey for the service."); } - // Create credential and instantiate service - Credentials credentials = null; - - // Authenticate using iamApikey - TokenOptions tokenOptions = new TokenOptions() - { - IamApiKey = _iamApikey - }; - - credentials = new Credentials(tokenOptions, _serviceUrl); + IamAuthenticator authenticator = new IamAuthenticator(apikey: _iamApikey); // Wait for tokendata - while (!credentials.HasIamTokenData()) + while (!authenticator.CanAuthenticate()) yield return null; - _service = new SpeechToTextService(credentials); + _service = new SpeechToTextService(authenticator); _service.StreamMultipart = true; Active = true; diff --git a/Examples/ExampleStreaming.unity b/Examples/ExampleStreaming.unity index 57ebaceb5..b4d5befb3 100644 --- a/Examples/ExampleStreaming.unity +++ b/Examples/ExampleStreaming.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0.44657868, g: 0.49641263, b: 0.57481706, a: 1} + m_IndirectSpecularColor: {r: 0.44657898, g: 0.49641287, b: 0.5748173, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -54,7 +54,7 @@ LightmapSettings: m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 m_LightmapEditorSettings: - serializedVersion: 10 + serializedVersion: 12 m_Resolution: 2 m_BakeResolution: 40 m_AtlasSize: 1024 @@ -62,6 +62,7 @@ LightmapSettings: m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 @@ -76,10 +77,16 @@ LightmapSettings: m_PVRDirectSampleCount: 32 m_PVRSampleCount: 500 m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 500 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 2 + m_PVRDenoiserTypeDirect: 0 + m_PVRDenoiserTypeIndirect: 0 + m_PVRDenoiserTypeAO: 0 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 - m_PVRFilteringMode: 1 + m_PVREnvironmentMIS: 0 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 @@ -87,7 +94,8 @@ LightmapSettings: m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 - m_ShowResolutionOverlay: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 0 --- !u!196 &4 @@ -140,7 +148,7 @@ MonoBehaviour: m_GameObject: {fileID: 278297820} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1301386320, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreReversedGraphics: 1 @@ -157,7 +165,7 @@ MonoBehaviour: m_GameObject: {fileID: 278297820} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1980459831, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 0cd44c1031e13a943bb63640046fad76, type: 3} m_Name: m_EditorClassIdentifier: m_UiScaleMode: 0 @@ -236,12 +244,13 @@ Light: m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 1159842907} m_Enabled: 1 - serializedVersion: 8 + serializedVersion: 9 m_Type: 1 m_Color: {r: 1, g: 0.95686275, b: 0.8392157, a: 1} m_Intensity: 1 m_Range: 10 m_SpotAngle: 30 + m_InnerSpotAngle: 21.802082 m_CookieSize: 10 m_Shadows: m_Type: 2 @@ -251,6 +260,24 @@ Light: m_Bias: 0.05 m_NormalBias: 0.4 m_NearPlane: 0.2 + m_CullingMatrixOverride: + e00: 1 + e01: 0 + e02: 0 + e03: 0 + e10: 0 + e11: 1 + e12: 0 + e13: 0 + e20: 0 + e21: 0 + e22: 1 + e23: 0 + e30: 0 + e31: 0 + e32: 0 + e33: 1 + m_UseCullingMatrixOverride: 0 m_Cookie: {fileID: 0} m_DrawHalo: 0 m_Flare: {fileID: 0} @@ -258,12 +285,15 @@ Light: m_CullingMask: serializedVersion: 2 m_Bits: 4294967295 + m_RenderingLayerMask: 1 m_Lightmapping: 4 m_LightShadowCasterMode: 0 m_AreaSize: {x: 1, y: 1} m_BounceIntensity: 1 m_ColorTemperature: 6570 m_UseColorTemperature: 0 + m_BoundingSphereOverride: {x: 0, y: 0, z: 0, w: 0} + m_UseBoundingSphereOverride: 0 m_ShadowRadius: 0 m_ShadowAngle: 0 --- !u!4 &1159842909 @@ -336,9 +366,10 @@ Camera: m_ClearFlags: 2 m_BackGroundColor: {r: 0.125, g: 0.125, b: 0.125, a: 0} m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 m_SensorSize: {x: 36, y: 24} m_LensShift: {x: 0, y: 0} - m_GateFitMode: 2 m_FocalLength: 50 m_NormalizedViewPortRect: serializedVersion: 2 @@ -407,7 +438,7 @@ MonoBehaviour: m_GameObject: {fileID: 1428860024} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1077351063, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalAxis: Horizontal @@ -426,7 +457,7 @@ MonoBehaviour: m_GameObject: {fileID: 1428860024} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -619905303, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3} m_Name: m_EditorClassIdentifier: m_FirstSelected: {fileID: 0} @@ -540,7 +571,7 @@ MonoBehaviour: m_GameObject: {fileID: 1863902089} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 2 @@ -554,7 +585,7 @@ MonoBehaviour: m_GameObject: {fileID: 1863902089} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} diff --git a/Examples/ExampleToneAnalyzerV3.cs b/Examples/ExampleToneAnalyzerV3.cs index 54d7e487f..7a266669c 100644 --- a/Examples/ExampleToneAnalyzerV3.cs +++ b/Examples/ExampleToneAnalyzerV3.cs @@ -22,6 +22,8 @@ using System.Collections.Generic; using UnityEngine; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; namespace IBM.Watson.Examples { @@ -60,21 +62,13 @@ private IEnumerator CreateService() } // Create credential and instantiate service - Credentials credentials = null; - - // Authenticate using iamApikey - TokenOptions tokenOptions = new TokenOptions() - { - IamApiKey = iamApikey - }; - - credentials = new Credentials(tokenOptions, serviceUrl); + IamAuthenticator authenticator = new IamAuthenticator(apikey: iamApikey); // Wait for tokendata - while (!credentials.HasIamTokenData()) + while (!authenticator.CanAuthenticate()) yield return null; - service = new ToneAnalyzerService(versionDate, credentials); + service = new ToneAnalyzerService(versionDate, authenticator); Runnable.Run(Examples()); } diff --git a/Examples/ExampleToneAnalyzerV3.unity b/Examples/ExampleToneAnalyzerV3.unity index ae87fb11c..225c62e27 100644 --- a/Examples/ExampleToneAnalyzerV3.unity +++ b/Examples/ExampleToneAnalyzerV3.unity @@ -38,7 +38,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0.37311953, g: 0.38074014, b: 0.3587274, a: 1} + m_IndirectSpecularColor: {r: 0.37311953, g: 0.38074, b: 0.35872698, a: 1} m_UseRadianceAmbientProbe: 0 --- !u!157 &3 LightmapSettings: @@ -54,7 +54,7 @@ LightmapSettings: m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 m_LightmapEditorSettings: - serializedVersion: 10 + serializedVersion: 12 m_Resolution: 2 m_BakeResolution: 40 m_AtlasSize: 1024 @@ -62,6 +62,7 @@ LightmapSettings: m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 @@ -76,10 +77,16 @@ LightmapSettings: m_PVRDirectSampleCount: 32 m_PVRSampleCount: 500 m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 500 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 2 + m_PVRDenoiserTypeDirect: 0 + m_PVRDenoiserTypeIndirect: 0 + m_PVRDenoiserTypeAO: 0 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 - m_PVRFilteringMode: 1 + m_PVREnvironmentMIS: 0 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 @@ -87,7 +94,8 @@ LightmapSettings: m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 - m_ShowResolutionOverlay: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 1 --- !u!196 &4 @@ -141,9 +149,9 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: 0565ac87492626f4f8ae7c0b00ca16bd, type: 3} m_Name: m_EditorClassIdentifier: - iamApikey: - serviceUrl: - versionDate: + iamApikey: sad + serviceUrl: dsad + versionDate: 2019-09-16 --- !u!4 &1170910667 Transform: m_ObjectHideFlags: 0 diff --git a/Examples/GenericSerialization.cs b/Examples/GenericSerialization.cs index aa832e3c9..d415236a8 100644 --- a/Examples/GenericSerialization.cs +++ b/Examples/GenericSerialization.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using UnityEngine; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using Newtonsoft.Json; using IBM.Watson.Assistant.V2.Model; @@ -32,21 +33,8 @@ void Start() LogSystem.InstallDefaultReactors(); MessageResponse messageResponse = JsonConvert.DeserializeObject(responseJson); - //Dictionary e = Json.Deserialize(responseJson) as Dictionary; - //Dictionary context = e["context"] as Dictionary; - //Dictionary skills = context["skills"] as Dictionary; - //Dictionary main_skill = skills["main skill"] as Dictionary; - //Dictionary user_defined = main_skill["user_defined"] as Dictionary; - //string name = user_defined["name"] as string; - - //var user_defined = messageResponse.Context.Skills["main skill"]["user_defined"].ToString(); - //var uDefinedObject = JsonConvert.DeserializeObject>(user_defined); - - //Log.Debug("GenericSerialization", "main skill: {0}", uDefinedObject["name"]); - //Log.Debug("GenericSerialization", "test: {0}", messageResponse); - - var name = messageResponse.Context.Skills["main skill"]["user_defined"]["name"].ToString(); + var name = messageResponse.Context.Skills.Get("main skill").UserDefined["name"].ToString(); Log.Debug("GenericSerialization", "name: {0}", name); } diff --git a/MIGRATION-v4.md b/MIGRATION-v4.md new file mode 100644 index 000000000..709ba9528 --- /dev/null +++ b/MIGRATION-v4.md @@ -0,0 +1,230 @@ +### Unity SDK V4 Migration guide + +#### Authentication + +##### v3.x.x + +Previously different `Config` objects were used for authentication. + +```cs +void Example() +{ + TokenOptions iamTokenOptions = new TokenOptions( + Apikey: "{iam-apikey}" + ); + service = new AssistantService("{versionDate}", iamTokenOptions); + service.SetEndpoint("{service-endpoint}"); +} +``` + +Or constructors accepted `TokenOptions` or `username` and `password`. + +```cs +void Example() +{ + service = new AssistantService("{tokenOptions}", "{versionDate}"); + service2 = new DiscoveryService("{username}", "{password}", "{versionDate}"); +} +``` + +##### v4.x.x + +Now we use an `Authenticator` to authenticate the service. Available authentication schemes include `IamAuthenticator`, `BasicAuthenticator`, `CloudPakForDataAuthenticator` and `BearerTokenAuthenticator` + +###### IamAuthenticator + +```cs +void Example() +{ + IamAuthenticator authenticator = new IamAuthenticator( + apikey: "{apikey}" + ); + var service = new AssistantService("{versionDate}", authenticator); + service.SetServiceUrl("{serviceUrl}"); +} +``` + +##### BasicAuthenticator + +```cs +void Example() +{ + BasicAuthenticator authenticator = new BasicAuthenticator( + username: "{username}", + password: "{password}" + ); + var service = new AssistantService("{versionDate}", authenticator); + service.SetServiceUrl("{serviceUrl}"); +} +``` + +###### BearerTokenAuthenticator + +```cs +void Example() +{ + BearerTokenAuthenticator authenticator = new BearerTokenAuthenticator( + bearerToken: "{bearerToken}" + ); + var service = new AssistantService("{versionDate}", authenticator); + service.SetServiceUrl("{serviceUrl}"); +} +``` + +###### CloudPakForDataAuthenticator + +```cs +void Example() +{ + CloudPakForDataAuthenticator authenticator = new CloudPakForDataAuthenticator( + url: "https://{cp4d_cluster_host}{:port}", + username: "{username}", + password: "{password}" + ); + var service = new AssistantService("{version-date}", authenticator); + service.SetServiceUrl("{serviceUrl}"); + var results = service.Message("{workspace-id}", "{message-request}"); +} +``` + +Constructors that did not take an `Authenticator` were removed. + +#### Supplying credentials + +You can supply credentials to your service using external `ibm-credentials.env` files. + +```cs +AssistantService service = new AssistantService("{version-date}"); +var listWorkspacesResult = service.ListWorkspaces(); +``` + +##### v3.x.x + +Previously we would look for these files first in the system `home` directory, followed by the current project directory. + +##### v4.x.x +Now in order to allow developers to have different configurations for each project we look first in the current project directory, followed by the home directory. + +#### Setting the service url + +##### v3.x.x + +Previously we set the service url via SetEndpoint() method. + +```cs +void Example() +{ + TokenOptions iamTokenOptions = new TokenOptions( + apikey: "{iam-apikey}" + ); + service = new AssistantService("{versionDate}", iamTokenOptions); + service.SetEndpoint("{service-endpoint}"); +} +``` + +##### v4.x.x + +Now we set the service url via the SetServiceUrl() method. + +```cs +void Example() +{ + IamAuthenticator authenticator = new IamAuthenticator( + apikey: "{apikey}" + ); + var service = new AssistantService("{versionDate}", authenticator); + service.SetServiceUrl("{serviceUrl}"); +} +``` + +#### Service changes + +##### Assistant v1 + +* `includeCount` is no longer a parameter of the `ListWorkspaces()` method +* `includeCount` is no longer a parameter of the `ListIntents()` method +* `includeCount` is no longer a parameter of the `ListExamples()` method +* `includeCount` is no longer a parameter of the `ListCounterexamples()` method +* `includeCount` is no longer a parameter of the `ListEntities()` method +* `includeCount` is no longer a parameter of the `ListValues()` method +* `includeCount` is no longer a parameter of the `ListSynonyms()` method +* `includeCount` is no longer a parameter of the `ListDialogNodes()` method +* `valueType` was renamed to `type` in the `CreateValue()` method +* `newValueType` was renamed to `newType` in the `UpdateValue()` method +* `nodeType` was renamed to `type` in the `CreateDialogNode()` method +* `nodeType` was renamed to `type` in the `CreateDialogNode()` method +* `newNodeType` was renamed to `newType` in the `UpdateDialogNode()` method +* `ValueTypeEnumValue` was renamed to `TypeEnumValue` in the `CreateValue` model +* `ValueType` was renamed to `Type` in the `CreateValue` model +* `NodeTypeEnumValue` was renamed to `TypeEnumValue` in the `DialogNode` model +* `NodeType` was renamed to `Type` in the `DialogNode` model +* `ActionTypeEnumValue` was renamed to `TypeEnumValue` in the `DialogNodeAction` model +* `ActionType` was renamed to `Type` in the `DialogNodeAction` model +* `SEARCH_SKILL` constant was added to the `DialogNodeOutputGeneric` model +* `QueryTypeEnumValue` constants were added to the `DialogNodeOutputGeneric` model +* `QueryType` property was added to the `DialogNodeOutputGeneric` model +* `Query` property was added to the `DialogNodeOutputGeneric` model +* `Filter` property was added to the `DialogNodeOutputGeneric` model +* `DiscoveryVersion` property was added to the `DialogNodeOutputGeneric` model +* `Output` property type was converted from `Dictionary` to `DialogSuggestionOutput` in the `DialogSuggestion` model +* `LogMessage` model no longer has `additionalProperties` +* `DialogRuntimeResponseGeneric` was renamed to `RuntimeResponseGeneric` +* `RuntimeEntity` model no longer has `additionalProperties` +* `RuntimeIntent` model no longer has `additionalProperties` +* `ValueTypeEnumValue` was renamed to `TypeEnumValue` in the `Value` model +* `ValueType` was renamed to `Type` in the `Value` model + +##### Assistant v2 + +* `ActionTypeEnumValue` was renamed to `TypeEnumValue` in the `DialogNodeAction` model +* `ActionType` was renamed to `Type` in the `DialogNodeAction` model +* `DialogRuntimeResponseGeneric` was renamed to `RuntimeResponseGeneric` + +##### Compare Comply v1 + +* `ConvertToHtml()` method does not require a `filename` parameter + +##### Discovery v1 + +* `returnFields` was renamed to `_return` in the `Query()` method +* `loggingOptOut` was renamed to `xWatsonLoggingOptOut` in the `Query()` method +* `spellingSuggestions` was added to the `Query()` method +* `collectionIds` is no longer a parameter of the `Query()` method +* `returnFields` was renamed to `_return` in the `QueryNotices()` method +* `loggingOptOut` was renamed to `xWatsonLoggingOptOut` in the `FederatedQuery()` method +* `collectionIds` is now required in the `FederatedQuery()` method +* `collectionIds` changed position in the `FederatedQuery()` method +* `returnFields` was renamed to `_return` in the `FederatedQuery()` method +* `returnFields` was renamed to `_return` in the `FederatedQueryNotices()` method +* `EnrichmentName` was renamed to `_Enrichment` in the `Enrichment` model +* `FieldTypeEnumValue` was renamed to `TypeEnumValue` in the `Field` model +* `FieldType` was renamed to `Type` in the `Field` model +* `FieldName` was renamed to `_Field` in the `Field` model +* `TestConfigurationInEnvironment()` method was removed +* `QueryEntities()` method was removed +* `QueryRelations()` method was removed + +##### Language Translator v3 + +* `defaultModels` was renamed to `_default` in the `ListModels()` method +* `TranslationOutput` was renamed to `_Translation` in the `Translation` model + +##### Natural Language Classifier v1 + +* `metadata` was renamed to `trainingMetadata` in the `CreateClassifier()` method + +##### Speech to Text v1 + +* `strict` is no longer a parameter of the `TrainAcousticModel()` method +* `FinalResults` was renamed to `Final` in the `SpeakerLabelsResult` model +* `FinalResults` was renamed to `Final` in the `SpeechRecognitionResult` model + +##### Visual Recognition v3 + +* `DetectFaces()` method was removed +* `ClassName` was renamed to `_Class` in the `ClassResult` model +* `ClassName` was renamed to `_Class` in the `ModelClass` model + +##### Visual Recognition v4 + +* New service! \ No newline at end of file diff --git a/README.md b/README.md index f73bacaf2..5beedddd6 100755 --- a/README.md +++ b/README.md @@ -111,29 +111,19 @@ You supply either an IAM service **API key** or an **access token**: #### Supplying the IAM API key ```cs -Credentials credentials; +Authenticator authenticator; AssistantService assistant; string versionDate = ""; IEnumerator TokenExample() { - // Create IAM token options and supply the apikey. IamUrl is the URL used to get the - // authorization token using the IamApiKey. It defaults to https://iam.cloud.ibm.com/identity/token - TokenOptions iamTokenOptions = new TokenOptions() - { - IamApiKey = "", - IamUrl = "" - }; - - // Create credentials using the IAM token options - credentials = new Credentials(iamTokenOptions, ""); - while (!credentials.HasIamTokenData()) + // Create authenticator using the IAM token options + authenticator = new IamAuthenticator(apikey: ""); + while (!authenticator.CanAuthenticate()) yield return null; - assistant = new AssistantService( - versionDate: versionDate, - credentials: credentials - ); + assistant = new AssistantService(versionDate, authenticator); + assistant.SetServiceUrl(""); assistant.ListWorkspaces(callback: OnListWorkspaces); } @@ -145,25 +135,17 @@ private void OnListWorkspaces(DetailedResponse response, IB #### Supplying the access token ```cs -Credentials credentials; +Authenticator authenticator; AssistantService assistant; string versionDate = ""; void TokenExample() { - // Create IAM token options and supply the access token. - TokenOptions iamTokenOptions = new TokenOptions() - { - IamAccessToken = "" - }; - - // Create credentials using the IAM token options - credentials = new Credentials(iamTokenOptions, ""); + // Create authenticator using the Bearer Token + authenticator = new BearerTokenAuthenticator(""); - assistant = new AssistantService( - versionDate: versionDate, - credentials: credentials - ); + assistant = new AssistantService(versionDate, authenticator); + assistant.SetServiceUrl(""); assistant.ListWorkspaces(callback: OnListWorkspaces); } @@ -175,23 +157,21 @@ private void OnListWorkspaces(DetailedResponse response, IB ### Username and password ```cs -Credentials credentials; +Authenticator authenticator; AssistantService assistant; string versionDate = ""; void UsernamePasswordExample() { - Credentials credentials = new Credentials("", "", ""); - assistant = new AssistantService( - versionDate: versionDate, - credentials: credentials - ); + Authenticator authenticator = new BasicAuthenticator("", "", ""); + assistant = new AssistantService(versionDate, authenticator); + assistant.SetServiceUrl(""); } ``` -### Supplying credentials +### Supplying authenticator -There are two ways to supply the credentials you found above to the SDK for authentication. +There are two ways to supply the authenticator you found above to the SDK for authentication. #### Credential file (easier!) @@ -210,16 +190,16 @@ public IEnumerator ExampleAutoService() Assistant assistantService = new Assistant("2019-04-03"); // Wait for authorization token - while (!assistantService.Credentials.HasIamTokenData()) + while (!assistantService.Authenticator.CanAuthenticate()) yield return null; - + var listWorkspacesResult = assistantService.ListWorkspaces(); } ``` And that's it! -If you're using more than one service at a time in your code and get two different `ibm-credentials.env` files, just put the contents together in one `ibm-credentials.env` file and the SDK will handle assigning credentials to their appropriate services. +If you're using more than one service at a time in your code and get two different `ibm-credentials.env` files, just put the contents together in one `ibm-credentials.env` file and the SDK will handle assigning authenticator to their appropriate services. If you would like to configure the location/name of your credential file, you can set an environment variable called `IBM_CREDENTIALS_FILE`. **This will take precedence over the locations specified above.** Here's how you can do that: @@ -231,35 +211,31 @@ where `` is something like `/home/user/Downloads/.env`. #### Manually -If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you. +If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of authenticator your service instance gives you. ## Callbacks -A success callback is required. You can specify the return type in the callback. +A success callback is required. You can specify the return type in the callback. ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; DiscoveryService discovery; string discoveryVersionDate = ""; -Credentials discoveryCredentials; +Authenticator discoveryAuthenticator; private void Example() { - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + assistant = new AssistantService(assistantVersionDate, assistantAuthenticator); + assistant.SetServiceUrl(""); - discovery = new DiscoveryService( - versionDate: discoveryVersionDate, - credentials: discoveryCredentials - ); + discovery = new DiscoveryService(discoveryVersionDate, discoveryAuthenticator); + discovery.SetServiceUrl(""); // Call with sepcific callbacks assistant.Message( - callback: OnMessage, + callback: OnMessage, workspaceId: workspaceId ); @@ -283,29 +259,30 @@ Since the success callback signature is generic and the failure callback always ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; DiscoveryService discovery; string discoveryVersionDate = ""; -Credentials discoveryCredentials; +Authenticator discoveryAuthenticator; private void Example() { - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + assistant = new AssistantService(assistantVersionDate, assistantAuthenticator); + assistant.SetServiceUrl(""); // Call with generic callbacks JObject input = new JObject(); input.Add("text", ""); assistant.Message( - callback: OnSuccess, + callback: OnSuccess, workspaceId: workspaceId, input: input ); + discovery = new DiscoveryService(discoveryVersionDate, discoveryAuthenticator); + discovery.SetServiceUrl(""); + discovery.ListEnvironments( callback: OnSuccess ); @@ -322,15 +299,12 @@ You can also use an anonymous callback ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; private void Example() { - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + assistant = new AssistantService(assistantVersionDate, assistantAuthenticator); assistant.ListWorkspaces( callback: (DetailedResponse response, IBMError error) => @@ -342,6 +316,7 @@ private void Example() sort: "-name", includeAudit: true ); + assistant.SetServiceUrl(""); } ``` @@ -349,15 +324,12 @@ You can check the `error` response to see if there was an error in the call. ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; private void Example() { - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + assistant = new AssistantService(versionDate, authenticator); assistant.Message(OnMessage, workspaceId); } @@ -381,15 +353,12 @@ You can send custom request headers by adding them to the service. ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; void Example() { - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + assistant = new AssistantService(assistantVersionDate, assistantAuthenticator); // Add custom header to the REST call assistant.WithHeader("X-Watson-Metadata", "customer_id=some-assistant-customer-id"); @@ -408,15 +377,12 @@ You can get response headers in the `headers` object in the DetailedResponse. ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; void Example() { - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + assistant = new AssistantService(assistantVersionDate, assistantAuthenticator); assistant.Message(OnMessage, ""); } @@ -439,16 +405,13 @@ You can disable SSL verifciation when making a service call. ```cs AssistantService assistant; string assistantVersionDate = ""; -Credentials assistantCredentials; +Authenticator assistantAuthenticator; string workspaceId = ""; void Example() { - credentials.DisableSslVerification = true; - assistant = new AssistantService( - versionDate: assistantVersionDate, - credentials: assistantCredentials - ); + authenticator.DisableSslVerification = true; + assistant = new AssistantService(assistantVersionDate, assistantAuthenticator); // disable ssl verification assistant.DisableSslVerification = true; @@ -463,38 +426,23 @@ If your service instance is of ICP4D, below are two ways of initializing the ass The SDK will manage the token for the user ```cs - Icp4dTokenOptions tokenOptions = new Icp4dTokenOptions() - { - Username = "", - Password = "", - Url = "", - DisableSslVerification = true - }; - credentials = new Credentials(tokenOptions, ""); - while(!credentials.HasTokenData()) + CloudPakForDataAuthenticator authenticator = new CloudPakForDataAuthenticator("", "", ""); + while(!authenticator.CanAuthenticate()) { yield return null; } - service = new AssistantService(versionDate, credentials); + service = new AssistantService(versionDate, authenticator); ``` #### 2) Supplying the access token ```cs - Icp4dTokenOptions tokenOptions = new Icp4dTokenOptions() - { - Username = "", - Password = "", - Url = "", - AccessToken = "", - DisableSslVerification = true - }; - credentials = new Credentials(tokenOptions, ""); - while(!credentials.HasTokenData()) + BearerTokenAuthenticator = new BearerTokenAuthenticator(""); + while(!authenticator.CanAuthenticate()) { yield return null; } - service = new AssistantService(versionDate, credentials); + service = new AssistantService(versionDate, authenticator); ``` ## IBM Cloud Private diff --git a/Scripts/Services/Assistant/V1/AssistantService.cs b/Scripts/Services/Assistant/V1/AssistantService.cs index 95c961813..15a2b238e 100644 --- a/Scripts/Services/Assistant/V1/AssistantService.cs +++ b/Scripts/Services/Assistant/V1/AssistantService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Assistant.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.Assistant.V1 public partial class AssistantService : BaseService { private const string serviceId = "assistant"; - private const string defaultUrl = "https://gateway.watsonplatform.net/assistant/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/assistant/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// AssistantService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public AssistantService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public AssistantService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// AssistantService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public AssistantService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public AssistantService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of AssistantService"); @@ -111,18 +81,10 @@ public AssistantService(string versionDate, Credentials credentials) : base(vers VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the Assistant service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -131,6 +93,11 @@ public AssistantService(string versionDate, Credentials credentials) : base(vers /// /// Send user input to a workspace and receive a response. /// + /// **Important:** This method has been superseded by the new v2 runtime API. The v2 API offers significant + /// advantages, including ease of deployment, automatic state management, versioning, and search capabilities. + /// For more information, see the + /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-api-overview). + /// /// There is no rate limit for this operation. /// /// The callback function that is invoked when the operation completes. @@ -151,7 +118,7 @@ public AssistantService(string versionDate, Credentials credentials) : base(vers /// Whether to include additional diagnostic information about the dialog /// nodes that were visited during processing of the message. (optional, default to false) /// MessageResponse - public bool Message(Callback callback, string workspaceId, JObject input = null, List intents = null, List entities = null, bool? alternateIntents = null, JObject context = null, JObject output = null, bool? nodesVisitedDetails = null) + public bool Message(Callback callback, string workspaceId, MessageInput input = null, List intents = null, List entities = null, bool? alternateIntents = null, Context context = null, OutputData output = null, bool? nodesVisitedDetails = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Message`"); @@ -202,7 +169,7 @@ public bool Message(Callback callback, string workspaceId, JObj req.OnResponse = OnMessageResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/message", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/message", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -244,15 +211,13 @@ private void OnMessageResponse(RESTConnector.Request req, RESTConnector.Response /// /// The callback function that is invoked when the operation completes. /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned workspaces will be sorted. To reverse the sort order, /// prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// WorkspaceCollection - public bool ListWorkspaces(Callback callback, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListWorkspaces(Callback callback, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListWorkspaces`"); @@ -281,10 +246,6 @@ public bool ListWorkspaces(Callback callback, long? pageLim { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -300,7 +261,7 @@ public bool ListWorkspaces(Callback callback, long? pageLim req.OnResponse = OnListWorkspacesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/workspaces"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/workspaces", GetServiceUrl()); if (connector == null) { return false; @@ -412,7 +373,7 @@ public bool CreateWorkspace(Callback callback, string name = null, st req.OnResponse = OnCreateWorkspaceResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/workspaces"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/workspaces", GetServiceUrl()); if (connector == null) { return false; @@ -506,7 +467,7 @@ public bool GetWorkspace(Callback callback, string workspaceId, bool? req.OnResponse = OnGetWorkspaceResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -632,7 +593,7 @@ public bool UpdateWorkspace(Callback callback, string workspaceId, st req.OnResponse = OnUpdateWorkspaceResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -705,7 +666,7 @@ public bool DeleteWorkspace(Callback callback, string workspaceId) req.OnResponse = OnDeleteWorkspaceResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -752,15 +713,13 @@ private void OnDeleteWorkspaceResponse(RESTConnector.Request req, RESTConnector. /// returned data includes only information about the element itself. If **export**=`true`, all content, /// including subelements, is included. (optional, default to false) /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned intents will be sorted. To reverse the sort order, prefix /// the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// IntentCollection - public bool ListIntents(Callback callback, string workspaceId, bool? export = null, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListIntents(Callback callback, string workspaceId, bool? export = null, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListIntents`"); @@ -795,10 +754,6 @@ public bool ListIntents(Callback callback, string workspaceId, { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -814,7 +769,7 @@ public bool ListIntents(Callback callback, string workspaceId, req.OnResponse = OnListIntentsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -909,7 +864,7 @@ public bool CreateIntent(Callback callback, string workspaceId, string i req.OnResponse = OnCreateIntentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -999,7 +954,7 @@ public bool GetIntent(Callback callback, string workspaceId, string inte req.OnResponse = OnGetIntentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}", workspaceId, intent)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}", workspaceId, intent), GetServiceUrl()); if (connector == null) { return false; @@ -1096,7 +1051,7 @@ public bool UpdateIntent(Callback callback, string workspaceId, string i req.OnResponse = OnUpdateIntentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}", workspaceId, intent)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}", workspaceId, intent), GetServiceUrl()); if (connector == null) { return false; @@ -1172,7 +1127,7 @@ public bool DeleteIntent(Callback callback, string workspaceId, string i req.OnResponse = OnDeleteIntentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}", workspaceId, intent)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}", workspaceId, intent), GetServiceUrl()); if (connector == null) { return false; @@ -1216,15 +1171,13 @@ private void OnDeleteIntentResponse(RESTConnector.Request req, RESTConnector.Res /// Unique identifier of the workspace. /// The intent name. /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned examples will be sorted. To reverse the sort order, /// prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// ExampleCollection - public bool ListExamples(Callback callback, string workspaceId, string intent, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListExamples(Callback callback, string workspaceId, string intent, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListExamples`"); @@ -1257,10 +1210,6 @@ public bool ListExamples(Callback callback, string workspaceI { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -1276,7 +1225,7 @@ public bool ListExamples(Callback callback, string workspaceI req.OnResponse = OnListExamplesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}/examples", workspaceId, intent)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}/examples", workspaceId, intent), GetServiceUrl()); if (connector == null) { return false; @@ -1370,7 +1319,7 @@ public bool CreateExample(Callback callback, string workspaceId, string req.OnResponse = OnCreateExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}/examples", workspaceId, intent)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}/examples", workspaceId, intent), GetServiceUrl()); if (connector == null) { return false; @@ -1455,7 +1404,7 @@ public bool GetExample(Callback callback, string workspaceId, string in req.OnResponse = OnGetExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}/examples/{2}", workspaceId, intent, text)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}/examples/{2}", workspaceId, intent, text), GetServiceUrl()); if (connector == null) { return false; @@ -1551,7 +1500,7 @@ public bool UpdateExample(Callback callback, string workspaceId, string req.OnResponse = OnUpdateExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}/examples/{2}", workspaceId, intent, text)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}/examples/{2}", workspaceId, intent, text), GetServiceUrl()); if (connector == null) { return false; @@ -1630,7 +1579,7 @@ public bool DeleteExample(Callback callback, string workspaceId, string req.OnResponse = OnDeleteExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/intents/{1}/examples/{2}", workspaceId, intent, text)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/intents/{1}/examples/{2}", workspaceId, intent, text), GetServiceUrl()); if (connector == null) { return false; @@ -1674,15 +1623,13 @@ private void OnDeleteExampleResponse(RESTConnector.Request req, RESTConnector.Re /// The callback function that is invoked when the operation completes. /// Unique identifier of the workspace. /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned counterexamples will be sorted. To reverse the sort /// order, prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// CounterexampleCollection - public bool ListCounterexamples(Callback callback, string workspaceId, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListCounterexamples(Callback callback, string workspaceId, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListCounterexamples`"); @@ -1713,10 +1660,6 @@ public bool ListCounterexamples(Callback callback, str { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -1732,7 +1675,7 @@ public bool ListCounterexamples(Callback callback, str req.OnResponse = OnListCounterexamplesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/counterexamples", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/counterexamples", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -1822,7 +1765,7 @@ public bool CreateCounterexample(Callback callback, string works req.OnResponse = OnCreateCounterexampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/counterexamples", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/counterexamples", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -1905,7 +1848,7 @@ public bool GetCounterexample(Callback callback, string workspac req.OnResponse = OnGetCounterexampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/counterexamples/{1}", workspaceId, text)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/counterexamples/{1}", workspaceId, text), GetServiceUrl()); if (connector == null) { return false; @@ -1995,7 +1938,7 @@ public bool UpdateCounterexample(Callback callback, string works req.OnResponse = OnUpdateCounterexampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/counterexamples/{1}", workspaceId, text)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/counterexamples/{1}", workspaceId, text), GetServiceUrl()); if (connector == null) { return false; @@ -2072,7 +2015,7 @@ public bool DeleteCounterexample(Callback callback, string workspaceId, req.OnResponse = OnDeleteCounterexampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/counterexamples/{1}", workspaceId, text)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/counterexamples/{1}", workspaceId, text), GetServiceUrl()); if (connector == null) { return false; @@ -2119,15 +2062,13 @@ private void OnDeleteCounterexampleResponse(RESTConnector.Request req, RESTConne /// returned data includes only information about the element itself. If **export**=`true`, all content, /// including subelements, is included. (optional, default to false) /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned entities will be sorted. To reverse the sort order, /// prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// EntityCollection - public bool ListEntities(Callback callback, string workspaceId, bool? export = null, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListEntities(Callback callback, string workspaceId, bool? export = null, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListEntities`"); @@ -2162,10 +2103,6 @@ public bool ListEntities(Callback callback, string workspaceId { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -2181,7 +2118,7 @@ public bool ListEntities(Callback callback, string workspaceId req.OnResponse = OnListEntitiesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -2283,7 +2220,7 @@ public bool CreateEntity(Callback callback, string workspaceId, string e req.OnResponse = OnCreateEntityResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -2373,7 +2310,7 @@ public bool GetEntity(Callback callback, string workspaceId, string enti req.OnResponse = OnGetEntityResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}", workspaceId, entity)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}", workspaceId, entity), GetServiceUrl()); if (connector == null) { return false; @@ -2476,7 +2413,7 @@ public bool UpdateEntity(Callback callback, string workspaceId, string e req.OnResponse = OnUpdateEntityResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}", workspaceId, entity)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}", workspaceId, entity), GetServiceUrl()); if (connector == null) { return false; @@ -2552,7 +2489,7 @@ public bool DeleteEntity(Callback callback, string workspaceId, string e req.OnResponse = OnDeleteEntityResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}", workspaceId, entity)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}", workspaceId, entity), GetServiceUrl()); if (connector == null) { return false; @@ -2642,7 +2579,7 @@ public bool ListMentions(Callback callback, string work req.OnResponse = OnListMentionsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/mentions", workspaceId, entity)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/mentions", workspaceId, entity), GetServiceUrl()); if (connector == null) { return false; @@ -2689,15 +2626,13 @@ private void OnListMentionsResponse(RESTConnector.Request req, RESTConnector.Res /// returned data includes only information about the element itself. If **export**=`true`, all content, /// including subelements, is included. (optional, default to false) /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned entity values will be sorted. To reverse the sort order, /// prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// ValueCollection - public bool ListValues(Callback callback, string workspaceId, string entity, bool? export = null, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListValues(Callback callback, string workspaceId, string entity, bool? export = null, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListValues`"); @@ -2734,10 +2669,6 @@ public bool ListValues(Callback callback, string workspaceId, s { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -2753,7 +2684,7 @@ public bool ListValues(Callback callback, string workspaceId, s req.OnResponse = OnListValuesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values", workspaceId, entity)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values", workspaceId, entity), GetServiceUrl()); if (connector == null) { return false; @@ -2803,7 +2734,7 @@ private void OnListValuesResponse(RESTConnector.Request req, RESTConnector.Respo /// - It cannot contain carriage return, newline, or tab characters. /// - It cannot consist of only whitespace characters. /// Any metadata related to the entity value. (optional) - /// Specifies the type of entity value. (optional, default to synonyms) + /// Specifies the type of entity value. (optional, default to synonyms) /// An array of synonyms for the entity value. A value can specify either synonyms or /// patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: /// - It cannot contain carriage return, newline, or tab characters. @@ -2814,7 +2745,7 @@ private void OnListValuesResponse(RESTConnector.Request req, RESTConnector.Respo /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). /// (optional) /// Value - public bool CreateValue(Callback callback, string workspaceId, string entity, string value, Dictionary metadata = null, string valueType = null, List synonyms = null, List patterns = null) + public bool CreateValue(Callback callback, string workspaceId, string entity, string value, Dictionary metadata = null, string type = null, List synonyms = null, List patterns = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `CreateValue`"); @@ -2853,8 +2784,8 @@ public bool CreateValue(Callback callback, string workspaceId, string ent bodyObject["value"] = value; if (metadata != null) bodyObject["metadata"] = JToken.FromObject(metadata); - if (!string.IsNullOrEmpty(valueType)) - bodyObject["type"] = valueType; + if (!string.IsNullOrEmpty(type)) + bodyObject["type"] = type; if (synonyms != null && synonyms.Count > 0) bodyObject["synonyms"] = JToken.FromObject(synonyms); if (patterns != null && patterns.Count > 0) @@ -2863,7 +2794,7 @@ public bool CreateValue(Callback callback, string workspaceId, string ent req.OnResponse = OnCreateValueResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values", workspaceId, entity)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values", workspaceId, entity), GetServiceUrl()); if (connector == null) { return false; @@ -2955,7 +2886,7 @@ public bool GetValue(Callback callback, string workspaceId, string entity req.OnResponse = OnGetValueResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}", workspaceId, entity, value)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}", workspaceId, entity, value), GetServiceUrl()); if (connector == null) { return false; @@ -3007,7 +2938,7 @@ private void OnGetValueResponse(RESTConnector.Request req, RESTConnector.Respons /// - It cannot contain carriage return, newline, or tab characters. /// - It cannot consist of only whitespace characters. (optional) /// Any metadata related to the entity value. (optional) - /// Specifies the type of entity value. (optional, default to synonyms) + /// Specifies the type of entity value. (optional, default to synonyms) /// An array of synonyms for the entity value. A value can specify either synonyms or /// patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: /// - It cannot contain carriage return, newline, or tab characters. @@ -3018,7 +2949,7 @@ private void OnGetValueResponse(RESTConnector.Request req, RESTConnector.Respons /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-entities#entities-create-dictionary-based). /// (optional) /// Value - public bool UpdateValue(Callback callback, string workspaceId, string entity, string value, string newValue = null, Dictionary newMetadata = null, string newValueType = null, List newSynonyms = null, List newPatterns = null) + public bool UpdateValue(Callback callback, string workspaceId, string entity, string value, string newValue = null, Dictionary newMetadata = null, string newType = null, List newSynonyms = null, List newPatterns = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `UpdateValue`"); @@ -3057,8 +2988,8 @@ public bool UpdateValue(Callback callback, string workspaceId, string ent bodyObject["value"] = newValue; if (newMetadata != null) bodyObject["metadata"] = JToken.FromObject(newMetadata); - if (!string.IsNullOrEmpty(newValueType)) - bodyObject["type"] = newValueType; + if (!string.IsNullOrEmpty(newType)) + bodyObject["type"] = newType; if (newSynonyms != null && newSynonyms.Count > 0) bodyObject["synonyms"] = JToken.FromObject(newSynonyms); if (newPatterns != null && newPatterns.Count > 0) @@ -3067,7 +2998,7 @@ public bool UpdateValue(Callback callback, string workspaceId, string ent req.OnResponse = OnUpdateValueResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}", workspaceId, entity, value)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}", workspaceId, entity, value), GetServiceUrl()); if (connector == null) { return false; @@ -3146,7 +3077,7 @@ public bool DeleteValue(Callback callback, string workspaceId, string en req.OnResponse = OnDeleteValueResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}", workspaceId, entity, value)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}", workspaceId, entity, value), GetServiceUrl()); if (connector == null) { return false; @@ -3191,15 +3122,13 @@ private void OnDeleteValueResponse(RESTConnector.Request req, RESTConnector.Resp /// The name of the entity. /// The text of the entity value. /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned entity value synonyms will be sorted. To reverse the sort /// order, prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// SynonymCollection - public bool ListSynonyms(Callback callback, string workspaceId, string entity, string value, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListSynonyms(Callback callback, string workspaceId, string entity, string value, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListSynonyms`"); @@ -3234,10 +3163,6 @@ public bool ListSynonyms(Callback callback, string workspaceI { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -3253,7 +3178,7 @@ public bool ListSynonyms(Callback callback, string workspaceI req.OnResponse = OnListSynonymsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms", workspaceId, entity, value)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms", workspaceId, entity, value), GetServiceUrl()); if (connector == null) { return false; @@ -3347,7 +3272,7 @@ public bool CreateSynonym(Callback callback, string workspaceId, string req.OnResponse = OnCreateSynonymResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms", workspaceId, entity, value)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms", workspaceId, entity, value), GetServiceUrl()); if (connector == null) { return false; @@ -3435,7 +3360,7 @@ public bool GetSynonym(Callback callback, string workspaceId, string en req.OnResponse = OnGetSynonymResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}", workspaceId, entity, value, synonym)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}", workspaceId, entity, value, synonym), GetServiceUrl()); if (connector == null) { return false; @@ -3530,7 +3455,7 @@ public bool UpdateSynonym(Callback callback, string workspaceId, string req.OnResponse = OnUpdateSynonymResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}", workspaceId, entity, value, synonym)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}", workspaceId, entity, value, synonym), GetServiceUrl()); if (connector == null) { return false; @@ -3612,7 +3537,7 @@ public bool DeleteSynonym(Callback callback, string workspaceId, string req.OnResponse = OnDeleteSynonymResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}", workspaceId, entity, value, synonym)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}", workspaceId, entity, value, synonym), GetServiceUrl()); if (connector == null) { return false; @@ -3655,15 +3580,13 @@ private void OnDeleteSynonymResponse(RESTConnector.Request req, RESTConnector.Re /// The callback function that is invoked when the operation completes. /// Unique identifier of the workspace. /// The number of records to return in each page of results. (optional) - /// Whether to include information about the number of records returned. (optional, - /// default to false) /// The attribute by which returned dialog nodes will be sorted. To reverse the sort order, /// prefix the value with a minus sign (`-`). (optional) /// A token identifying the page of results to retrieve. (optional) /// Whether to include the audit properties (`created` and `updated` timestamps) in /// the response. (optional, default to false) /// DialogNodeCollection - public bool ListDialogNodes(Callback callback, string workspaceId, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null, bool? includeAudit = null) + public bool ListDialogNodes(Callback callback, string workspaceId, long? pageLimit = null, string sort = null, string cursor = null, bool? includeAudit = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListDialogNodes`"); @@ -3694,10 +3617,6 @@ public bool ListDialogNodes(Callback callback, string work { req.Parameters["page_limit"] = pageLimit; } - if (includeCount != null) - { - req.Parameters["include_count"] = (bool)includeCount ? "true" : "false"; - } if (!string.IsNullOrEmpty(sort)) { req.Parameters["sort"] = sort; @@ -3713,7 +3632,7 @@ public bool ListDialogNodes(Callback callback, string work req.OnResponse = OnListDialogNodesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/dialog_nodes", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/dialog_nodes", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -3779,7 +3698,7 @@ private void OnListDialogNodesResponse(RESTConnector.Request req, RESTConnector. /// restrictions: /// - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. /// (optional) - /// How the dialog node is processed. (optional) + /// How the dialog node is processed. (optional) /// How an `event_handler` node is processed. (optional) /// The location in the dialog context where output is stored. (optional) /// An array of objects describing any actions to be invoked by the dialog node. @@ -3791,7 +3710,7 @@ private void OnListDialogNodesResponse(RESTConnector.Request req, RESTConnector. /// A label that can be displayed externally to describe the purpose of the node to /// users. (optional) /// DialogNode - public bool CreateDialogNode(Callback callback, string workspaceId, string dialogNode, string description = null, string conditions = null, string parent = null, string previousSibling = null, JObject output = null, Dictionary context = null, Dictionary metadata = null, DialogNodeNextStep nextStep = null, string title = null, string nodeType = null, string eventName = null, string variable = null, List actions = null, string digressIn = null, string digressOut = null, string digressOutSlots = null, string userLabel = null) + public bool CreateDialogNode(Callback callback, string workspaceId, string dialogNode, string description = null, string conditions = null, string parent = null, string previousSibling = null, DialogNodeOutput output = null, Dictionary context = null, Dictionary metadata = null, DialogNodeNextStep nextStep = null, string title = null, string type = null, string eventName = null, string variable = null, List actions = null, string digressIn = null, string digressOut = null, string digressOutSlots = null, string userLabel = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `CreateDialogNode`"); @@ -3844,8 +3763,8 @@ public bool CreateDialogNode(Callback callback, string workspaceId, bodyObject["next_step"] = JToken.FromObject(nextStep); if (!string.IsNullOrEmpty(title)) bodyObject["title"] = title; - if (!string.IsNullOrEmpty(nodeType)) - bodyObject["type"] = nodeType; + if (!string.IsNullOrEmpty(type)) + bodyObject["type"] = type; if (!string.IsNullOrEmpty(eventName)) bodyObject["event_name"] = eventName; if (!string.IsNullOrEmpty(variable)) @@ -3864,7 +3783,7 @@ public bool CreateDialogNode(Callback callback, string workspaceId, req.OnResponse = OnCreateDialogNodeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/dialog_nodes", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/dialog_nodes", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -3946,7 +3865,7 @@ public bool GetDialogNode(Callback callback, string workspaceId, str req.OnResponse = OnGetDialogNodeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/dialog_nodes/{1}", workspaceId, dialogNode)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/dialog_nodes/{1}", workspaceId, dialogNode), GetServiceUrl()); if (connector == null) { return false; @@ -4014,7 +3933,7 @@ private void OnGetDialogNodeResponse(RESTConnector.Request req, RESTConnector.Re /// restrictions: /// - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. /// (optional) - /// How the dialog node is processed. (optional) + /// How the dialog node is processed. (optional) /// How an `event_handler` node is processed. (optional) /// The location in the dialog context where output is stored. (optional) /// An array of objects describing any actions to be invoked by the dialog node. @@ -4027,7 +3946,7 @@ private void OnGetDialogNodeResponse(RESTConnector.Request req, RESTConnector.Re /// A label that can be displayed externally to describe the purpose of the node to /// users. (optional) /// DialogNode - public bool UpdateDialogNode(Callback callback, string workspaceId, string dialogNode, string newDialogNode = null, string newDescription = null, string newConditions = null, string newParent = null, string newPreviousSibling = null, JObject newOutput = null, Dictionary newContext = null, Dictionary newMetadata = null, DialogNodeNextStep newNextStep = null, string newTitle = null, string newNodeType = null, string newEventName = null, string newVariable = null, List newActions = null, string newDigressIn = null, string newDigressOut = null, string newDigressOutSlots = null, string newUserLabel = null) + public bool UpdateDialogNode(Callback callback, string workspaceId, string dialogNode, string newDialogNode = null, string newDescription = null, string newConditions = null, string newParent = null, string newPreviousSibling = null, DialogNodeOutput newOutput = null, Dictionary newContext = null, Dictionary newMetadata = null, DialogNodeNextStep newNextStep = null, string newTitle = null, string newType = null, string newEventName = null, string newVariable = null, List newActions = null, string newDigressIn = null, string newDigressOut = null, string newDigressOutSlots = null, string newUserLabel = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `UpdateDialogNode`"); @@ -4080,8 +3999,8 @@ public bool UpdateDialogNode(Callback callback, string workspaceId, bodyObject["next_step"] = JToken.FromObject(newNextStep); if (!string.IsNullOrEmpty(newTitle)) bodyObject["title"] = newTitle; - if (!string.IsNullOrEmpty(newNodeType)) - bodyObject["type"] = newNodeType; + if (!string.IsNullOrEmpty(newType)) + bodyObject["type"] = newType; if (!string.IsNullOrEmpty(newEventName)) bodyObject["event_name"] = newEventName; if (!string.IsNullOrEmpty(newVariable)) @@ -4100,7 +4019,7 @@ public bool UpdateDialogNode(Callback callback, string workspaceId, req.OnResponse = OnUpdateDialogNodeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/dialog_nodes/{1}", workspaceId, dialogNode)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/dialog_nodes/{1}", workspaceId, dialogNode), GetServiceUrl()); if (connector == null) { return false; @@ -4176,7 +4095,7 @@ public bool DeleteDialogNode(Callback callback, string workspaceId, stri req.OnResponse = OnDeleteDialogNodeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/dialog_nodes/{1}", workspaceId, dialogNode)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/dialog_nodes/{1}", workspaceId, dialogNode), GetServiceUrl()); if (connector == null) { return false; @@ -4220,8 +4139,7 @@ private void OnDeleteDialogNodeResponse(RESTConnector.Request req, RESTConnector /// The callback function that is invoked when the operation completes. /// Unique identifier of the workspace. /// 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 (`-`). (optional, default to - /// request_timestamp) + /// the sort order, prefix the parameter value with a minus sign (`-`). (optional) /// A cacheable parameter that limits the results to those matching the specified filter. /// For more information, see the /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-filter-reference#filter-reference). @@ -4275,7 +4193,7 @@ public bool ListLogs(Callback callback, string workspaceId, strin req.OnResponse = OnListLogsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/workspaces/{0}/logs", workspaceId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/workspaces/{0}/logs", workspaceId), GetServiceUrl()); if (connector == null) { return false; @@ -4322,8 +4240,7 @@ private void OnListLogsResponse(RESTConnector.Request req, RESTConnector.Respons /// or `request.context.metadata.deployment`. For more information, see the /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-filter-reference#filter-reference). /// 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 (`-`). (optional, default to - /// request_timestamp) + /// the sort order, prefix the parameter value with a minus sign (`-`). (optional) /// The number of records to return in each page of results. (optional) /// A token identifying the page of results to retrieve. (optional) /// LogCollection @@ -4373,7 +4290,7 @@ public bool ListAllLogs(Callback callback, string filter, string req.OnResponse = OnListAllLogsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/logs"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/logs", GetServiceUrl()); if (connector == null) { return false; @@ -4453,7 +4370,7 @@ public bool DeleteUserData(Callback callback, string customerId) req.OnResponse = OnDeleteUserDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/user_data"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/user_data", GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/Assistant/V1/Model/Context.cs b/Scripts/Services/Assistant/V1/Model/Context.cs index 482474c20..30a3ac350 100644 --- a/Scripts/Services/Assistant/V1/Model/Context.cs +++ b/Scripts/Services/Assistant/V1/Model/Context.cs @@ -15,15 +15,15 @@ * */ +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V1.Model { /// /// State information for the conversation. To maintain state, include the context from the previous response. /// - public class Context + public class Context: DynamicModel { /// /// The unique identifier of the conversation. @@ -34,7 +34,7 @@ public class Context /// For internal use only. /// [JsonProperty("system", NullValueHandling = NullValueHandling.Ignore)] - public JObject System { get; set; } + public SystemResponse System { get; set; } /// /// Metadata related to the message. /// diff --git a/Scripts/Services/Assistant/V1/Model/CreateValue.cs b/Scripts/Services/Assistant/V1/Model/CreateValue.cs index e1f68a0bd..da779b100 100644 --- a/Scripts/Services/Assistant/V1/Model/CreateValue.cs +++ b/Scripts/Services/Assistant/V1/Model/CreateValue.cs @@ -29,7 +29,7 @@ public class CreateValue /// /// Specifies the type of entity value. /// - public class ValueTypeValue + public class TypeValue { /// /// Constant SYNONYMS for synonyms @@ -44,10 +44,10 @@ public class ValueTypeValue /// /// Specifies the type of entity value. - /// Constants for possible values can be found using CreateValue.ValueTypeValue + /// Constants for possible values can be found using CreateValue.TypeValue /// [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public string ValueType { get; set; } + public string Type { get; set; } /// /// The text of the entity value. This string must conform to the following restrictions: /// - It cannot contain carriage return, newline, or tab characters. diff --git a/Scripts/Services/Assistant/V1/Model/DialogNode.cs b/Scripts/Services/Assistant/V1/Model/DialogNode.cs index d5e7b7e06..807b98809 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNode.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNode.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using System; namespace IBM.Watson.Assistant.V1.Model @@ -30,7 +29,7 @@ public class DialogNode /// /// How the dialog node is processed. /// - public class NodeTypeValue + public class TypeValue { /// /// Constant STANDARD for standard @@ -165,10 +164,10 @@ public class DigressOutSlotsValue /// /// How the dialog node is processed. - /// Constants for possible values can be found using DialogNode.NodeTypeValue + /// Constants for possible values can be found using DialogNode.TypeValue /// [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public string NodeType { get; set; } + public string Type { get; set; } /// /// How an `event_handler` node is processed. /// Constants for possible values can be found using DialogNode.EventNameValue @@ -226,7 +225,7 @@ public class DigressOutSlotsValue /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). /// [JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)] - public JObject Output { get; set; } + public DialogNodeOutput Output { get; set; } /// /// The context for the dialog node. /// diff --git a/Scripts/Services/Assistant/V1/Model/DialogNodeAction.cs b/Scripts/Services/Assistant/V1/Model/DialogNodeAction.cs index cce7476c0..825b10250 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNodeAction.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNodeAction.cs @@ -28,7 +28,7 @@ public class DialogNodeAction /// /// The type of action to invoke. /// - public class ActionTypeValue + public class TypeValue { /// /// Constant CLIENT for client @@ -51,10 +51,10 @@ public class ActionTypeValue /// /// The type of action to invoke. - /// Constants for possible values can be found using DialogNodeAction.ActionTypeValue + /// Constants for possible values can be found using DialogNodeAction.TypeValue /// [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public string ActionType { get; set; } + public string Type { get; set; } /// /// The name of the action. /// diff --git a/Scripts/Services/Assistant/V1/Model/DialogNodeNextStep.cs b/Scripts/Services/Assistant/V1/Model/DialogNodeNextStep.cs index a0734d708..5e8a9f9ac 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNodeNextStep.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNodeNextStep.cs @@ -43,8 +43,7 @@ public class DialogNodeNextStep /// - `reprompt` /// - `skip_slot` /// - `skip_all_slots` - /// - /// If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. + /// If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. /// public class BehaviorValue { @@ -118,8 +117,7 @@ public class SelectorValue /// - `reprompt` /// - `skip_slot` /// - `skip_all_slots` - /// - /// If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. + /// If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. /// Constants for possible values can be found using DialogNodeNextStep.BehaviorValue /// [JsonProperty("behavior", NullValueHandling = NullValueHandling.Ignore)] diff --git a/Scripts/Services/Assistant/V1/Model/DialogNodeOutput.cs b/Scripts/Services/Assistant/V1/Model/DialogNodeOutput.cs index aabffd22d..f32c12c05 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNodeOutput.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNodeOutput.cs @@ -16,6 +16,7 @@ */ using System.Collections.Generic; +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; namespace IBM.Watson.Assistant.V1.Model @@ -24,7 +25,7 @@ namespace IBM.Watson.Assistant.V1.Model /// The output of the dialog node. For more information about how to specify dialog node output, see the /// [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). /// - public class DialogNodeOutput + public class DialogNodeOutput: DynamicModel { /// /// An array of objects describing the output defined for the dialog node. diff --git a/Scripts/Services/Assistant/V1/Model/DialogNodeOutputGeneric.cs b/Scripts/Services/Assistant/V1/Model/DialogNodeOutputGeneric.cs index 052638028..030389720 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNodeOutputGeneric.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNodeOutputGeneric.cs @@ -28,6 +28,9 @@ public class DialogNodeOutputGeneric /// /// The type of response returned by the dialog node. The specified response type must be supported by the /// client application or channel. + /// + /// **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only + /// by the v2 runtime API. /// public class ResponseTypeValue { @@ -51,6 +54,10 @@ public class ResponseTypeValue /// Constant CONNECT_TO_AGENT for connect_to_agent /// public const string CONNECT_TO_AGENT = "connect_to_agent"; + /// + /// Constant SEARCH_SKILL for search_skill + /// + public const string SEARCH_SKILL = "search_skill"; } @@ -92,9 +99,28 @@ public class PreferenceValue } + /// + /// The type of the search query. Required when **response_type**=`search_skill`. + /// + public class QueryTypeValue + { + /// + /// Constant NATURAL_LANGUAGE for natural_language + /// + public const string NATURAL_LANGUAGE = "natural_language"; + /// + /// Constant DISCOVERY_QUERY_LANGUAGE for discovery_query_language + /// + public const string DISCOVERY_QUERY_LANGUAGE = "discovery_query_language"; + + } + /// /// The type of response returned by the dialog node. The specified response type must be supported by the /// client application or channel. + /// + /// **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only + /// by the v2 runtime API. /// Constants for possible values can be found using DialogNodeOutputGeneric.ResponseTypeValue /// [JsonProperty("response_type", NullValueHandling = NullValueHandling.Ignore)] @@ -114,6 +140,12 @@ public class PreferenceValue [JsonProperty("preference", NullValueHandling = NullValueHandling.Ignore)] public string Preference { get; set; } /// + /// The type of the search query. Required when **response_type**=`search_skill`. + /// Constants for possible values can be found using DialogNodeOutputGeneric.QueryTypeValue + /// + [JsonProperty("query_type", NullValueHandling = NullValueHandling.Ignore)] + public string QueryType { get; set; } + /// /// A list of one or more objects defining text responses. Required when **response_type**=`text`. /// [JsonProperty("values", NullValueHandling = NullValueHandling.Ignore)] @@ -130,7 +162,7 @@ public class PreferenceValue [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] public long? Time { get; set; } /// - /// Whether to send a \"user is typing\" event during the pause. Ignored if the channel does not support this + /// Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this /// event. Valid only when **response_type**=`pause`. /// [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] @@ -162,5 +194,26 @@ public class PreferenceValue /// [JsonProperty("message_to_human_agent", NullValueHandling = NullValueHandling.Ignore)] public string MessageToHumanAgent { get; set; } + /// + /// The text of the search query. This can be either a natural-language query or a query that uses the Discovery + /// query language syntax, depending on the value of the **query_type** property. For more information, see the + /// [Discovery service + /// documentation](https://cloud.ibm.com/docs/services/discovery/query-operators.html#query-operators). Required + /// when **response_type**=`search_skill`. + /// + [JsonProperty("query", NullValueHandling = NullValueHandling.Ignore)] + public string Query { get; set; } + /// + /// An optional filter that narrows the set of documents to be searched. For more information, see the + /// [Discovery service documentation]([Discovery service + /// documentation](https://cloud.ibm.com/docs/services/discovery/query-parameters.html#filter). + /// + [JsonProperty("filter", NullValueHandling = NullValueHandling.Ignore)] + public string Filter { get; set; } + /// + /// The version of the Discovery service API to use for the query. + /// + [JsonProperty("discovery_version", NullValueHandling = NullValueHandling.Ignore)] + public string DiscoveryVersion { get; set; } } } diff --git a/Scripts/Services/Assistant/V1/Model/DialogNodeOutputOptionsElementValue.cs b/Scripts/Services/Assistant/V1/Model/DialogNodeOutputOptionsElementValue.cs index 4bc52f2bc..06ba12ea5 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNodeOutputOptionsElementValue.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNodeOutputOptionsElementValue.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V1.Model { @@ -31,7 +30,7 @@ public class DialogNodeOutputOptionsElementValue /// An input object that includes the input text. /// [JsonProperty("input", NullValueHandling = NullValueHandling.Ignore)] - public JObject Input { get; set; } + public MessageInput Input { get; set; } /// /// An array of intents to be used while processing the input. /// @@ -39,7 +38,7 @@ public class DialogNodeOutputOptionsElementValue /// response to user input** method. /// [JsonProperty("intents", NullValueHandling = NullValueHandling.Ignore)] - public List Intents { get; set; } + public List Intents { get; set; } /// /// An array of entities to be used while processing the user input. /// @@ -47,6 +46,6 @@ public class DialogNodeOutputOptionsElementValue /// response to user input** method. /// [JsonProperty("entities", NullValueHandling = NullValueHandling.Ignore)] - public List Entities { get; set; } + public List Entities { get; set; } } } diff --git a/Scripts/Services/Assistant/V1/Model/DialogNodeOutputTextValuesElement.cs b/Scripts/Services/Assistant/V1/Model/DialogNodeOutputTextValuesElement.cs index ae73839fc..0d2b810a4 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogNodeOutputTextValuesElement.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogNodeOutputTextValuesElement.cs @@ -25,7 +25,7 @@ namespace IBM.Watson.Assistant.V1.Model public class DialogNodeOutputTextValuesElement { /// - /// The text of a response. This string can include newline characters (`\\n`), Markdown tagging, or other + /// The text of a response. This string can include newline characters (`\n`), Markdown tagging, or other /// special characters, if supported by the channel. /// [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)] diff --git a/Scripts/Services/Assistant/V1/Model/DialogRuntimeResponseGeneric.cs b/Scripts/Services/Assistant/V1/Model/DialogRuntimeResponseGeneric.cs index 09d412b0c..165306607 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogRuntimeResponseGeneric.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogRuntimeResponseGeneric.cs @@ -104,7 +104,7 @@ public class PreferenceValue [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] public long? Time { get; set; } /// - /// Whether to send a \"user is typing\" event during the pause. + /// Whether to send a "user is typing" event during the pause. /// [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] public bool? Typing { get; set; } diff --git a/Scripts/Services/Assistant/V1/Model/DialogSuggestion.cs b/Scripts/Services/Assistant/V1/Model/DialogSuggestion.cs index 934b63e7d..273fcc50e 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogSuggestion.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogSuggestion.cs @@ -15,7 +15,6 @@ * */ -using System.Collections.Generic; using Newtonsoft.Json; namespace IBM.Watson.Assistant.V1.Model @@ -42,7 +41,7 @@ public class DialogSuggestion /// corresponding option. /// [JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)] - public Dictionary Output { get; set; } + public DialogSuggestionOutput Output { get; set; } /// /// The ID of the dialog node that the **label** property is taken from. The **label** property is populated /// using the value of the dialog node's **user_label** property. diff --git a/Scripts/Services/Assistant/V1/Model/DialogSuggestionOutput.cs b/Scripts/Services/Assistant/V1/Model/DialogSuggestionOutput.cs new file mode 100644 index 000000000..689052e94 --- /dev/null +++ b/Scripts/Services/Assistant/V1/Model/DialogSuggestionOutput.cs @@ -0,0 +1,55 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using IBM.Cloud.SDK.Model; +using Newtonsoft.Json; + +namespace IBM.Watson.Assistant.V1.Model +{ + /// + /// The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding + /// option. + /// + public class DialogSuggestionOutput: DynamicModel + { + /// + /// An array of the nodes that were triggered to create the response, in the order in which they were visited. + /// This information is useful for debugging and for tracing the path taken through the node tree. + /// + [JsonProperty("nodes_visited", NullValueHandling = NullValueHandling.Ignore)] + public List NodesVisited { get; set; } + /// + /// An array of objects containing detailed diagnostic information about the nodes that were triggered during + /// processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message + /// request. + /// + [JsonProperty("nodes_visited_details", NullValueHandling = NullValueHandling.Ignore)] + public List NodesVisitedDetails { get; set; } + /// + /// An array of responses to the user. + /// + [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)] + public List Text { get; set; } + /// + /// Output intended for any channel. It is the responsibility of the client application to implement the + /// supported response types. + /// + [JsonProperty("generic", NullValueHandling = NullValueHandling.Ignore)] + public List Generic { get; set; } + } +} diff --git a/Scripts/Services/Assistant/V1/Model/DialogSuggestionOutput.cs.meta b/Scripts/Services/Assistant/V1/Model/DialogSuggestionOutput.cs.meta new file mode 100644 index 000000000..9207f1a0f --- /dev/null +++ b/Scripts/Services/Assistant/V1/Model/DialogSuggestionOutput.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bf80bc67f4c0449b4959b24d429662bf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Assistant/V1/Model/DialogSuggestionResponseGeneric.cs b/Scripts/Services/Assistant/V1/Model/DialogSuggestionResponseGeneric.cs new file mode 100644 index 000000000..9e0fe1690 --- /dev/null +++ b/Scripts/Services/Assistant/V1/Model/DialogSuggestionResponseGeneric.cs @@ -0,0 +1,151 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.Assistant.V1.Model +{ + /// + /// DialogSuggestionResponseGeneric. + /// + public class DialogSuggestionResponseGeneric + { + /// + /// The type of response returned by the dialog node. The specified response type must be supported by the + /// client application or channel. + /// + /// **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available + /// for Plus and Premium users. The **search_skill** response type is available only for Plus and Premium users, + /// and is used only by the v2 runtime API. + /// + public class ResponseTypeValue + { + /// + /// Constant TEXT for text + /// + public const string TEXT = "text"; + /// + /// Constant PAUSE for pause + /// + public const string PAUSE = "pause"; + /// + /// Constant IMAGE for image + /// + public const string IMAGE = "image"; + /// + /// Constant OPTION for option + /// + public const string OPTION = "option"; + /// + /// Constant CONNECT_TO_AGENT for connect_to_agent + /// + public const string CONNECT_TO_AGENT = "connect_to_agent"; + /// + /// Constant SEARCH_SKILL for search_skill + /// + public const string SEARCH_SKILL = "search_skill"; + + } + + /// + /// The preferred type of control to display. + /// + public class PreferenceValue + { + /// + /// Constant DROPDOWN for dropdown + /// + public const string DROPDOWN = "dropdown"; + /// + /// Constant BUTTON for button + /// + public const string BUTTON = "button"; + + } + + /// + /// The type of response returned by the dialog node. The specified response type must be supported by the + /// client application or channel. + /// + /// **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available + /// for Plus and Premium users. The **search_skill** response type is available only for Plus and Premium users, + /// and is used only by the v2 runtime API. + /// Constants for possible values can be found using DialogSuggestionResponseGeneric.ResponseTypeValue + /// + [JsonProperty("response_type", NullValueHandling = NullValueHandling.Ignore)] + public string ResponseType { get; set; } + /// + /// The preferred type of control to display. + /// Constants for possible values can be found using DialogSuggestionResponseGeneric.PreferenceValue + /// + [JsonProperty("preference", NullValueHandling = NullValueHandling.Ignore)] + public string Preference { get; set; } + /// + /// The text of the response. + /// + [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)] + public string Text { get; set; } + /// + /// How long to pause, in milliseconds. + /// + [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] + public long? Time { get; set; } + /// + /// Whether to send a "user is typing" event during the pause. + /// + [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] + public bool? Typing { get; set; } + /// + /// The URL of the image. + /// + [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] + public string Source { get; set; } + /// + /// The title or introductory text to show before the response. + /// + [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)] + public string Title { get; set; } + /// + /// The description to show with the the response. + /// + [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] + public string Description { get; set; } + /// + /// An array of objects describing the options from which the user can choose. + /// + [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)] + public List Options { get; set; } + /// + /// A message to be sent to the human agent who will be taking over the conversation. + /// + [JsonProperty("message_to_human_agent", NullValueHandling = NullValueHandling.Ignore)] + public string MessageToHumanAgent { get; set; } + /// + /// A label identifying the topic of the conversation, derived from the **user_label** property of the relevant + /// node. + /// + [JsonProperty("topic", NullValueHandling = NullValueHandling.Ignore)] + public virtual string Topic { get; private set; } + /// + /// The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated + /// using the value of the dialog node's **user_label** property. + /// + [JsonProperty("dialog_node", NullValueHandling = NullValueHandling.Ignore)] + public string DialogNode { get; set; } + } +} diff --git a/Scripts/Services/Assistant/V1/Model/DialogSuggestionResponseGeneric.cs.meta b/Scripts/Services/Assistant/V1/Model/DialogSuggestionResponseGeneric.cs.meta new file mode 100644 index 000000000..f8ae6379e --- /dev/null +++ b/Scripts/Services/Assistant/V1/Model/DialogSuggestionResponseGeneric.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c0054016448a644018ad6cc11f1224cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Assistant/V1/Model/DialogSuggestionValue.cs b/Scripts/Services/Assistant/V1/Model/DialogSuggestionValue.cs index 3ec321e84..2838a188a 100644 --- a/Scripts/Services/Assistant/V1/Model/DialogSuggestionValue.cs +++ b/Scripts/Services/Assistant/V1/Model/DialogSuggestionValue.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V1.Model { @@ -31,16 +30,16 @@ public class DialogSuggestionValue /// An input object that includes the input text. /// [JsonProperty("input", NullValueHandling = NullValueHandling.Ignore)] - public JObject Input { get; set; } + public MessageInput Input { get; set; } /// /// An array of intents to be sent along with the user input. /// [JsonProperty("intents", NullValueHandling = NullValueHandling.Ignore)] - public List Intents { get; set; } + public List Intents { get; set; } /// /// An array of entities to be sent along with the user input. /// [JsonProperty("entities", NullValueHandling = NullValueHandling.Ignore)] - public List Entities { get; set; } + public List Entities { get; set; } } } diff --git a/Scripts/Services/Assistant/V1/Model/MessageInput.cs b/Scripts/Services/Assistant/V1/Model/MessageInput.cs index 434bbc051..64b7600f5 100644 --- a/Scripts/Services/Assistant/V1/Model/MessageInput.cs +++ b/Scripts/Services/Assistant/V1/Model/MessageInput.cs @@ -15,6 +15,7 @@ * */ +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; namespace IBM.Watson.Assistant.V1.Model @@ -22,7 +23,7 @@ namespace IBM.Watson.Assistant.V1.Model /// /// An input object that includes the input text. /// - public class MessageInput + public class MessageInput: DynamicModel { /// /// The text of the user input. This string cannot contain carriage return, newline, or tab characters. diff --git a/Scripts/Services/Assistant/V1/Model/MessageRequest.cs b/Scripts/Services/Assistant/V1/Model/MessageRequest.cs index 808808eb8..89268f0fc 100644 --- a/Scripts/Services/Assistant/V1/Model/MessageRequest.cs +++ b/Scripts/Services/Assistant/V1/Model/MessageRequest.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V1.Model { @@ -30,19 +29,19 @@ public class MessageRequest /// An input object that includes the input text. /// [JsonProperty("input", NullValueHandling = NullValueHandling.Ignore)] - public JObject Input { get; set; } + public MessageInput Input { get; set; } /// /// 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. /// [JsonProperty("intents", NullValueHandling = NullValueHandling.Ignore)] - public List Intents { get; set; } + public List Intents { get; set; } /// /// 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. /// [JsonProperty("entities", NullValueHandling = NullValueHandling.Ignore)] - public List Entities { get; set; } + public List Entities { get; set; } /// /// Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. /// @@ -52,13 +51,13 @@ public class MessageRequest /// State information for the conversation. To maintain state, include the context from the previous response. /// [JsonProperty("context", NullValueHandling = NullValueHandling.Ignore)] - public JObject Context { get; set; } + public Context Context { get; set; } /// /// An output object that includes the response to the user, the dialog nodes that were triggered, and messages /// from the log. /// [JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)] - public JObject Output { get; set; } + public OutputData Output { get; set; } /// /// An array of objects describing any actions requested by the dialog node. /// diff --git a/Scripts/Services/Assistant/V1/Model/MessageResponse.cs b/Scripts/Services/Assistant/V1/Model/MessageResponse.cs index 6bbc2f2d1..77fdf3d33 100644 --- a/Scripts/Services/Assistant/V1/Model/MessageResponse.cs +++ b/Scripts/Services/Assistant/V1/Model/MessageResponse.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V1.Model { @@ -30,17 +29,17 @@ public class MessageResponse /// An input object that includes the input text. /// [JsonProperty("input", NullValueHandling = NullValueHandling.Ignore)] - public JObject Input { get; set; } + public MessageInput Input { get; set; } /// /// An array of intents recognized in the user input, sorted in descending order of confidence. /// [JsonProperty("intents", NullValueHandling = NullValueHandling.Ignore)] - public List Intents { get; set; } + public List Intents { get; set; } /// /// An array of entities identified in the user input. /// [JsonProperty("entities", NullValueHandling = NullValueHandling.Ignore)] - public List Entities { get; set; } + public List Entities { get; set; } /// /// Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. /// @@ -50,13 +49,13 @@ public class MessageResponse /// State information for the conversation. To maintain state, include the context from the previous response. /// [JsonProperty("context", NullValueHandling = NullValueHandling.Ignore)] - public JObject Context { get; set; } + public Context Context { get; set; } /// /// An output object that includes the response to the user, the dialog nodes that were triggered, and messages /// from the log. /// [JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)] - public JObject Output { get; set; } + public OutputData Output { get; set; } /// /// An array of objects describing any actions requested by the dialog node. /// diff --git a/Scripts/Services/Assistant/V1/Model/OutputData.cs b/Scripts/Services/Assistant/V1/Model/OutputData.cs index 9f9f77ec0..fd47e085b 100644 --- a/Scripts/Services/Assistant/V1/Model/OutputData.cs +++ b/Scripts/Services/Assistant/V1/Model/OutputData.cs @@ -16,8 +16,8 @@ */ using System.Collections.Generic; +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V1.Model { @@ -25,13 +25,26 @@ namespace IBM.Watson.Assistant.V1.Model /// An output object that includes the response to the user, the dialog nodes that were triggered, and messages from /// the log. /// - public class OutputData + public class OutputData: DynamicModel { + /// + /// An array of the nodes that were triggered to create the response, in the order in which they were visited. + /// This information is useful for debugging and for tracing the path taken through the node tree. + /// + [JsonProperty("nodes_visited", NullValueHandling = NullValueHandling.Ignore)] + public List NodesVisited { get; set; } + /// + /// An array of objects containing detailed diagnostic information about the nodes that were triggered during + /// processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message + /// request. + /// + [JsonProperty("nodes_visited_details", NullValueHandling = NullValueHandling.Ignore)] + public List NodesVisitedDetails { get; set; } /// /// An array of up to 50 messages logged with the request. /// [JsonProperty("log_messages", NullValueHandling = NullValueHandling.Ignore)] - public List LogMessages { get; set; } + public List LogMessages { get; set; } /// /// An array of responses to the user. /// @@ -42,19 +55,6 @@ public class OutputData /// supported response types. /// [JsonProperty("generic", NullValueHandling = NullValueHandling.Ignore)] - public List Generic { get; set; } - /// - /// An array of the nodes that were triggered to create the response, in the order in which they were visited. - /// This information is useful for debugging and for tracing the path taken through the node tree. - /// - [JsonProperty("nodes_visited", NullValueHandling = NullValueHandling.Ignore)] - public List NodesVisited { get; set; } - /// - /// An array of objects containing detailed diagnostic information about the nodes that were triggered during - /// processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message - /// request. - /// - [JsonProperty("nodes_visited_details", NullValueHandling = NullValueHandling.Ignore)] - public List NodesVisitedDetails { get; set; } + public List Generic { get; set; } } } diff --git a/Scripts/Services/Assistant/V1/Model/RuntimeEntity.cs b/Scripts/Services/Assistant/V1/Model/RuntimeEntity.cs index 95a078778..b14e57024 100644 --- a/Scripts/Services/Assistant/V1/Model/RuntimeEntity.cs +++ b/Scripts/Services/Assistant/V1/Model/RuntimeEntity.cs @@ -56,12 +56,5 @@ public class RuntimeEntity /// [JsonProperty("groups", NullValueHandling = NullValueHandling.Ignore)] public List Groups { get; set; } - /// - /// An object containing detailed information about the entity recognized in the user input. - /// - /// This property is a part of the new system entities, which are a beta feature. - /// - [JsonProperty("interpretation", NullValueHandling = NullValueHandling.Ignore)] - public RuntimeEntityInterpretation Interpretation { get; set; } } } diff --git a/Scripts/Services/Assistant/V1/Model/RuntimeEntityInterpretation.cs b/Scripts/Services/Assistant/V1/Model/RuntimeEntityInterpretation.cs deleted file mode 100644 index 533347572..000000000 --- a/Scripts/Services/Assistant/V1/Model/RuntimeEntityInterpretation.cs +++ /dev/null @@ -1,234 +0,0 @@ -/** -* Copyright 2018, 2019 IBM Corp. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -*/ - -using Newtonsoft.Json; - -namespace IBM.Watson.Assistant.V1.Model -{ - /// - /// RuntimeEntityInterpretation. - /// - public class RuntimeEntityInterpretation - { - /// - /// The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - /// - public class GranularityValue - { - /// - /// Constant DAY for day - /// - public const string DAY = "day"; - /// - /// Constant FORTNIGHT for fortnight - /// - public const string FORTNIGHT = "fortnight"; - /// - /// Constant HOUR for hour - /// - public const string HOUR = "hour"; - /// - /// Constant INSTANT for instant - /// - public const string INSTANT = "instant"; - /// - /// Constant MINUTE for minute - /// - public const string MINUTE = "minute"; - /// - /// Constant MONTH for month - /// - public const string MONTH = "month"; - /// - /// Constant QUARTER for quarter - /// - public const string QUARTER = "quarter"; - /// - /// Constant SECOND for second - /// - public const string SECOND = "second"; - /// - /// Constant WEEK for week - /// - public const string WEEK = "week"; - /// - /// Constant WEEKEND for weekend - /// - public const string WEEKEND = "weekend"; - /// - /// Constant YEAR for year - /// - public const string YEAR = "year"; - - } - - /// - /// The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - /// Constants for possible values can be found using RuntimeEntityInterpretation.GranularityValue - /// - [JsonProperty("granularity", NullValueHandling = NullValueHandling.Ignore)] - public string Granularity { get; set; } - /// - /// The calendar used to represent a recognized date (for example, `Gregorian`). - /// - [JsonProperty("calendar_type", NullValueHandling = NullValueHandling.Ignore)] - public string CalendarType { get; set; } - /// - /// 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). - /// - [JsonProperty("datetime_link", NullValueHandling = NullValueHandling.Ignore)] - public string DatetimeLink { get; set; } - /// - /// 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. - /// - [JsonProperty("festival", NullValueHandling = NullValueHandling.Ignore)] - public string Festival { get; set; } - /// - /// 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`). - /// - [JsonProperty("range_link", NullValueHandling = NullValueHandling.Ignore)] - public string RangeLink { get; set; } - /// - /// 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`). - /// - [JsonProperty("range_modifier", NullValueHandling = NullValueHandling.Ignore)] - public string RangeModifier { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_day", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeDay { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_month", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeMonth { get; set; } - /// - /// 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). - /// - [JsonProperty("relative_week", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeWeek { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_weekend", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeWeekend { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_year", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeYear { get; set; } - /// - /// A recognized mention of a specific date, represented numerically as the date within the month (for example, - /// `30` for `June 30`.). - /// - [JsonProperty("specific_day", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificDay { get; set; } - /// - /// A recognized mention of a specific day of the week as a lowercase string (for example, `monday`). - /// - [JsonProperty("specific_day_of_week", NullValueHandling = NullValueHandling.Ignore)] - public string SpecificDayOfWeek { get; set; } - /// - /// A recognized mention of a specific month, represented numerically (for example, `7` for `July`). - /// - [JsonProperty("specific_month", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificMonth { get; set; } - /// - /// A recognized mention of a specific quarter, represented numerically (for example, `3` for `the third - /// quarter`). - /// - [JsonProperty("specific_quarter", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificQuarter { get; set; } - /// - /// A recognized mention of a specific year (for example, `2016`). - /// - [JsonProperty("specific_year", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificYear { get; set; } - /// - /// A recognized numeric value, represented as an integer or double. - /// - [JsonProperty("numeric_value", NullValueHandling = NullValueHandling.Ignore)] - public float? NumericValue { get; set; } - /// - /// The type of numeric value recognized in the user input (`integer` or `rational`). - /// - [JsonProperty("subtype", NullValueHandling = NullValueHandling.Ignore)] - public string Subtype { get; set; } - /// - /// 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`). In addition, the returned entity value is set to a specific time: - /// - /// - `09:00:00` for `morning` - /// - `15:00:00` for `afternoon` - /// - `18:00:00` for `evening` - /// - `22:00:00` for `night` - /// - `00:00:00` for `midnight`. - /// - [JsonProperty("part_of_day", NullValueHandling = NullValueHandling.Ignore)] - public string PartOfDay { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_hour", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeHour { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_minute", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeMinute { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_second", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeSecond { get; set; } - /// - /// A recognized specific hour mentioned as part of a time value (for example, `10` for `10:15 AM`.). - /// - [JsonProperty("specific_hour", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificHour { get; set; } - /// - /// A recognized specific minute mentioned as part of a time value (for example, `15` for `10:15 AM`.). - /// - [JsonProperty("specific_minute", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificMinute { get; set; } - /// - /// A recognized specific second mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - /// - [JsonProperty("specific_second", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificSecond { get; set; } - /// - /// A recognized time zone mentioned as part of a time value (for example, `EST`). - /// - [JsonProperty("timezone", NullValueHandling = NullValueHandling.Ignore)] - public string Timezone { get; set; } - } -} diff --git a/Scripts/Services/Assistant/V1/Model/RuntimeResponseGeneric.cs b/Scripts/Services/Assistant/V1/Model/RuntimeResponseGeneric.cs new file mode 100644 index 000000000..c3f570fbe --- /dev/null +++ b/Scripts/Services/Assistant/V1/Model/RuntimeResponseGeneric.cs @@ -0,0 +1,157 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.Assistant.V1.Model +{ + /// + /// RuntimeResponseGeneric. + /// + public class RuntimeResponseGeneric + { + /// + /// The type of response returned by the dialog node. The specified response type must be supported by the + /// client application or channel. + /// + /// **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available + /// for Plus and Premium users. + /// + public class ResponseTypeValue + { + /// + /// Constant TEXT for text + /// + public const string TEXT = "text"; + /// + /// Constant PAUSE for pause + /// + public const string PAUSE = "pause"; + /// + /// Constant IMAGE for image + /// + public const string IMAGE = "image"; + /// + /// Constant OPTION for option + /// + public const string OPTION = "option"; + /// + /// Constant CONNECT_TO_AGENT for connect_to_agent + /// + public const string CONNECT_TO_AGENT = "connect_to_agent"; + /// + /// Constant SUGGESTION for suggestion + /// + public const string SUGGESTION = "suggestion"; + + } + + /// + /// The preferred type of control to display. + /// + public class PreferenceValue + { + /// + /// Constant DROPDOWN for dropdown + /// + public const string DROPDOWN = "dropdown"; + /// + /// Constant BUTTON for button + /// + public const string BUTTON = "button"; + + } + + /// + /// The type of response returned by the dialog node. The specified response type must be supported by the + /// client application or channel. + /// + /// **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available + /// for Plus and Premium users. + /// Constants for possible values can be found using RuntimeResponseGeneric.ResponseTypeValue + /// + [JsonProperty("response_type", NullValueHandling = NullValueHandling.Ignore)] + public string ResponseType { get; set; } + /// + /// The preferred type of control to display. + /// Constants for possible values can be found using RuntimeResponseGeneric.PreferenceValue + /// + [JsonProperty("preference", NullValueHandling = NullValueHandling.Ignore)] + public string Preference { get; set; } + /// + /// The text of the response. + /// + [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)] + public string Text { get; set; } + /// + /// How long to pause, in milliseconds. + /// + [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] + public long? Time { get; set; } + /// + /// Whether to send a "user is typing" event during the pause. + /// + [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] + public bool? Typing { get; set; } + /// + /// The URL of the image. + /// + [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] + public string Source { get; set; } + /// + /// The title or introductory text to show before the response. + /// + [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)] + public string Title { get; set; } + /// + /// The description to show with the the response. + /// + [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] + public string Description { get; set; } + /// + /// An array of objects describing the options from which the user can choose. + /// + [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)] + public List Options { get; set; } + /// + /// A message to be sent to the human agent who will be taking over the conversation. + /// + [JsonProperty("message_to_human_agent", NullValueHandling = NullValueHandling.Ignore)] + public string MessageToHumanAgent { get; set; } + /// + /// A label identifying the topic of the conversation, derived from the **user_label** property of the relevant + /// node. + /// + [JsonProperty("topic", NullValueHandling = NullValueHandling.Ignore)] + public virtual string Topic { get; private set; } + /// + /// The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated + /// using the value of the dialog node's **user_label** property. + /// + [JsonProperty("dialog_node", NullValueHandling = NullValueHandling.Ignore)] + public string DialogNode { get; set; } + /// + /// An array of objects describing the possible matching dialog nodes from which the user can choose. + /// + /// **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for + /// Premium users. + /// + [JsonProperty("suggestions", NullValueHandling = NullValueHandling.Ignore)] + public List Suggestions { get; set; } + } +} diff --git a/Scripts/Services/Assistant/V1/Model/RuntimeResponseGeneric.cs.meta b/Scripts/Services/Assistant/V1/Model/RuntimeResponseGeneric.cs.meta new file mode 100644 index 000000000..9be4c29ac --- /dev/null +++ b/Scripts/Services/Assistant/V1/Model/RuntimeResponseGeneric.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2417ec4b5b90340a38338e99ff548041 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Assistant/V1/Model/SystemResponse.cs b/Scripts/Services/Assistant/V1/Model/SystemResponse.cs index ddec89eb6..9692336b6 100644 --- a/Scripts/Services/Assistant/V1/Model/SystemResponse.cs +++ b/Scripts/Services/Assistant/V1/Model/SystemResponse.cs @@ -15,12 +15,14 @@ * */ +using IBM.Cloud.SDK.Model; + namespace IBM.Watson.Assistant.V1.Model { /// /// For internal use only. /// - public class SystemResponse + public class SystemResponse: DynamicModel { } } diff --git a/Scripts/Services/Assistant/V1/Model/Value.cs b/Scripts/Services/Assistant/V1/Model/Value.cs index 211d819b2..2e4f9cc25 100644 --- a/Scripts/Services/Assistant/V1/Model/Value.cs +++ b/Scripts/Services/Assistant/V1/Model/Value.cs @@ -29,7 +29,7 @@ public class Value /// /// Specifies the type of entity value. /// - public class ValueTypeValue + public class TypeValue { /// /// Constant SYNONYMS for synonyms @@ -44,10 +44,10 @@ public class ValueTypeValue /// /// Specifies the type of entity value. - /// Constants for possible values can be found using Value.ValueTypeValue + /// Constants for possible values can be found using Value.TypeValue /// [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public string ValueType { get; set; } + public string Type { get; set; } /// /// The text of the entity value. This string must conform to the following restrictions: /// - It cannot contain carriage return, newline, or tab characters. diff --git a/Scripts/Services/Assistant/V2/AssistantService.cs b/Scripts/Services/Assistant/V2/AssistantService.cs index ffc755fff..e3f09c4a7 100644 --- a/Scripts/Services/Assistant/V2/AssistantService.cs +++ b/Scripts/Services/Assistant/V2/AssistantService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Assistant.V2.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.Assistant.V2 public partial class AssistantService : BaseService { private const string serviceId = "assistant"; - private const string defaultUrl = "https://gateway.watsonplatform.net/assistant/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/assistant/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// AssistantService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public AssistantService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public AssistantService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// AssistantService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public AssistantService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public AssistantService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of AssistantService"); @@ -111,18 +81,10 @@ public AssistantService(string versionDate, Credentials credentials) : base(vers VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the Assistant service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -170,7 +132,7 @@ public bool CreateSession(Callback callback, string assistantId req.OnResponse = OnCreateSessionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions", assistantId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v2/assistants/{0}/sessions", assistantId), GetServiceUrl()); if (connector == null) { return false; @@ -249,7 +211,7 @@ public bool DeleteSession(Callback callback, string assistantId, string req.OnResponse = OnDeleteSessionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions/{1}", assistantId, sessionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v2/assistants/{0}/sessions/{1}", assistantId, sessionId), GetServiceUrl()); if (connector == null) { return false; @@ -343,7 +305,7 @@ public bool Message(Callback callback, string assistantId, stri req.OnResponse = OnMessageResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v2/assistants/{0}/sessions/{1}/message", assistantId, sessionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v2/assistants/{0}/sessions/{1}/message", assistantId, sessionId), GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/Assistant/V2/Model/DialogNodeAction.cs b/Scripts/Services/Assistant/V2/Model/DialogNodeAction.cs index 71fd571dc..06faba5ec 100644 --- a/Scripts/Services/Assistant/V2/Model/DialogNodeAction.cs +++ b/Scripts/Services/Assistant/V2/Model/DialogNodeAction.cs @@ -28,7 +28,7 @@ public class DialogNodeAction /// /// The type of action to invoke. /// - public class ActionTypeValue + public class TypeValue { /// /// Constant CLIENT for client @@ -51,10 +51,10 @@ public class ActionTypeValue /// /// The type of action to invoke. - /// Constants for possible values can be found using DialogNodeAction.ActionTypeValue + /// Constants for possible values can be found using DialogNodeAction.TypeValue /// [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public string ActionType { get; set; } + public string Type { get; set; } /// /// The name of the action. /// diff --git a/Scripts/Services/Assistant/V2/Model/DialogRuntimeResponseGeneric.cs b/Scripts/Services/Assistant/V2/Model/DialogRuntimeResponseGeneric.cs index 47086f53b..28a39f448 100644 --- a/Scripts/Services/Assistant/V2/Model/DialogRuntimeResponseGeneric.cs +++ b/Scripts/Services/Assistant/V2/Model/DialogRuntimeResponseGeneric.cs @@ -108,7 +108,7 @@ public class PreferenceValue [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] public long? Time { get; set; } /// - /// Whether to send a \"user is typing\" event during the pause. + /// Whether to send a "user is typing" event during the pause. /// [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] public bool? Typing { get; set; } diff --git a/Scripts/Services/Assistant/V2/Model/MessageContext.cs b/Scripts/Services/Assistant/V2/Model/MessageContext.cs index 903cb5a9d..ce750f037 100644 --- a/Scripts/Services/Assistant/V2/Model/MessageContext.cs +++ b/Scripts/Services/Assistant/V2/Model/MessageContext.cs @@ -16,7 +16,6 @@ */ using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Assistant.V2.Model { @@ -37,6 +36,6 @@ public class MessageContext /// that apply to the dialog skill used by the assistant. /// [JsonProperty("skills", NullValueHandling = NullValueHandling.Ignore)] - public JObject Skills { get; set; } + public MessageContextSkills Skills { get; set; } } } diff --git a/Scripts/Services/Assistant/V2/Model/MessageContextSkills.cs b/Scripts/Services/Assistant/V2/Model/MessageContextSkills.cs index 424f23829..582836766 100644 --- a/Scripts/Services/Assistant/V2/Model/MessageContextSkills.cs +++ b/Scripts/Services/Assistant/V2/Model/MessageContextSkills.cs @@ -15,6 +15,8 @@ * */ +using IBM.Cloud.SDK.Model; + namespace IBM.Watson.Assistant.V2.Model { /// @@ -23,7 +25,7 @@ namespace IBM.Watson.Assistant.V2.Model /// **Note:** Currently, only a single property named `main skill` is supported. This object contains variables that /// apply to the dialog skill used by the assistant. /// - public class MessageContextSkills + public class MessageContextSkills: DynamicModel { } } diff --git a/Scripts/Services/Assistant/V2/Model/MessageOutput.cs b/Scripts/Services/Assistant/V2/Model/MessageOutput.cs index f268d4cf8..212e8c567 100644 --- a/Scripts/Services/Assistant/V2/Model/MessageOutput.cs +++ b/Scripts/Services/Assistant/V2/Model/MessageOutput.cs @@ -30,7 +30,7 @@ public class MessageOutput /// supported response types. /// [JsonProperty("generic", NullValueHandling = NullValueHandling.Ignore)] - public List Generic { get; set; } + public List Generic { get; set; } /// /// An array of intents recognized in the user input, sorted in descending order of confidence. /// diff --git a/Scripts/Services/Assistant/V2/Model/RuntimeEntity.cs b/Scripts/Services/Assistant/V2/Model/RuntimeEntity.cs index 3f1c13563..97a1445f5 100644 --- a/Scripts/Services/Assistant/V2/Model/RuntimeEntity.cs +++ b/Scripts/Services/Assistant/V2/Model/RuntimeEntity.cs @@ -56,12 +56,5 @@ public class RuntimeEntity /// [JsonProperty("groups", NullValueHandling = NullValueHandling.Ignore)] public List Groups { get; set; } - /// - /// An object containing detailed information about the entity recognized in the user input. - /// - /// This property is a part of the new system entities, which are a beta feature. - /// - [JsonProperty("interpretation", NullValueHandling = NullValueHandling.Ignore)] - public RuntimeEntityInterpretation Interpretation { get; set; } } } diff --git a/Scripts/Services/Assistant/V2/Model/RuntimeEntityInterpretation.cs b/Scripts/Services/Assistant/V2/Model/RuntimeEntityInterpretation.cs deleted file mode 100644 index 9c1e0cbfc..000000000 --- a/Scripts/Services/Assistant/V2/Model/RuntimeEntityInterpretation.cs +++ /dev/null @@ -1,234 +0,0 @@ -/** -* Copyright 2018, 2019 IBM Corp. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -*/ - -using Newtonsoft.Json; - -namespace IBM.Watson.Assistant.V2.Model -{ - /// - /// RuntimeEntityInterpretation. - /// - public class RuntimeEntityInterpretation - { - /// - /// The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - /// - public class GranularityValue - { - /// - /// Constant DAY for day - /// - public const string DAY = "day"; - /// - /// Constant FORTNIGHT for fortnight - /// - public const string FORTNIGHT = "fortnight"; - /// - /// Constant HOUR for hour - /// - public const string HOUR = "hour"; - /// - /// Constant INSTANT for instant - /// - public const string INSTANT = "instant"; - /// - /// Constant MINUTE for minute - /// - public const string MINUTE = "minute"; - /// - /// Constant MONTH for month - /// - public const string MONTH = "month"; - /// - /// Constant QUARTER for quarter - /// - public const string QUARTER = "quarter"; - /// - /// Constant SECOND for second - /// - public const string SECOND = "second"; - /// - /// Constant WEEK for week - /// - public const string WEEK = "week"; - /// - /// Constant WEEKEND for weekend - /// - public const string WEEKEND = "weekend"; - /// - /// Constant YEAR for year - /// - public const string YEAR = "year"; - - } - - /// - /// The precision or duration of a time range specified by a recognized `@sys-time` or `@sys-date` entity. - /// Constants for possible values can be found using RuntimeEntityInterpretation.GranularityValue - /// - [JsonProperty("granularity", NullValueHandling = NullValueHandling.Ignore)] - public string Granularity { get; set; } - /// - /// The calendar used to represent a recognized date (for example, `Gregorian`). - /// - [JsonProperty("calendar_type", NullValueHandling = NullValueHandling.Ignore)] - public string CalendarType { get; set; } - /// - /// 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). - /// - [JsonProperty("datetime_link", NullValueHandling = NullValueHandling.Ignore)] - public string DatetimeLink { get; set; } - /// - /// 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. - /// - [JsonProperty("festival", NullValueHandling = NullValueHandling.Ignore)] - public string Festival { get; set; } - /// - /// 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`). - /// - [JsonProperty("range_link", NullValueHandling = NullValueHandling.Ignore)] - public string RangeLink { get; set; } - /// - /// 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`). - /// - [JsonProperty("range_modifier", NullValueHandling = NullValueHandling.Ignore)] - public string RangeModifier { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_day", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeDay { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_month", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeMonth { get; set; } - /// - /// 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). - /// - [JsonProperty("relative_week", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeWeek { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_weekend", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeWeekend { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_year", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeYear { get; set; } - /// - /// A recognized mention of a specific date, represented numerically as the date within the month (for example, - /// `30` for `June 30`.). - /// - [JsonProperty("specific_day", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificDay { get; set; } - /// - /// A recognized mention of a specific day of the week as a lowercase string (for example, `monday`). - /// - [JsonProperty("specific_day_of_week", NullValueHandling = NullValueHandling.Ignore)] - public string SpecificDayOfWeek { get; set; } - /// - /// A recognized mention of a specific month, represented numerically (for example, `7` for `July`). - /// - [JsonProperty("specific_month", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificMonth { get; set; } - /// - /// A recognized mention of a specific quarter, represented numerically (for example, `3` for `the third - /// quarter`). - /// - [JsonProperty("specific_quarter", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificQuarter { get; set; } - /// - /// A recognized mention of a specific year (for example, `2016`). - /// - [JsonProperty("specific_year", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificYear { get; set; } - /// - /// A recognized numeric value, represented as an integer or double. - /// - [JsonProperty("numeric_value", NullValueHandling = NullValueHandling.Ignore)] - public float? NumericValue { get; set; } - /// - /// The type of numeric value recognized in the user input (`integer` or `rational`). - /// - [JsonProperty("subtype", NullValueHandling = NullValueHandling.Ignore)] - public string Subtype { get; set; } - /// - /// 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`). In addition, the returned entity value is set to a specific time: - /// - /// - `09:00:00` for `morning` - /// - `15:00:00` for `afternoon` - /// - `18:00:00` for `evening` - /// - `22:00:00` for `night` - /// - `00:00:00` for `midnight`. - /// - [JsonProperty("part_of_day", NullValueHandling = NullValueHandling.Ignore)] - public string PartOfDay { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_hour", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeHour { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_minute", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeMinute { get; set; } - /// - /// 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`). - /// - [JsonProperty("relative_second", NullValueHandling = NullValueHandling.Ignore)] - public float? RelativeSecond { get; set; } - /// - /// A recognized specific hour mentioned as part of a time value (for example, `10` for `10:15 AM`.). - /// - [JsonProperty("specific_hour", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificHour { get; set; } - /// - /// A recognized specific minute mentioned as part of a time value (for example, `15` for `10:15 AM`.). - /// - [JsonProperty("specific_minute", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificMinute { get; set; } - /// - /// A recognized specific second mentioned as part of a time value (for example, `30` for `10:15:30 AM`.). - /// - [JsonProperty("specific_second", NullValueHandling = NullValueHandling.Ignore)] - public float? SpecificSecond { get; set; } - /// - /// A recognized time zone mentioned as part of a time value (for example, `EST`). - /// - [JsonProperty("timezone", NullValueHandling = NullValueHandling.Ignore)] - public string Timezone { get; set; } - } -} diff --git a/Scripts/Services/Assistant/V2/Model/RuntimeResponseGeneric.cs b/Scripts/Services/Assistant/V2/Model/RuntimeResponseGeneric.cs new file mode 100644 index 000000000..912c64bcc --- /dev/null +++ b/Scripts/Services/Assistant/V2/Model/RuntimeResponseGeneric.cs @@ -0,0 +1,166 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.Assistant.V2.Model +{ + /// + /// RuntimeResponseGeneric. + /// + public class RuntimeResponseGeneric + { + /// + /// The type of response returned by the dialog node. The specified response type must be supported by the + /// client application or channel. + /// + /// **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available + /// for Premium users. + /// + public class ResponseTypeValue + { + /// + /// Constant TEXT for text + /// + public const string TEXT = "text"; + /// + /// Constant PAUSE for pause + /// + public const string PAUSE = "pause"; + /// + /// Constant IMAGE for image + /// + public const string IMAGE = "image"; + /// + /// Constant OPTION for option + /// + public const string OPTION = "option"; + /// + /// Constant CONNECT_TO_AGENT for connect_to_agent + /// + public const string CONNECT_TO_AGENT = "connect_to_agent"; + /// + /// Constant SUGGESTION for suggestion + /// + public const string SUGGESTION = "suggestion"; + /// + /// Constant SEARCH for search + /// + public const string SEARCH = "search"; + + } + + /// + /// The preferred type of control to display. + /// + public class PreferenceValue + { + /// + /// Constant DROPDOWN for dropdown + /// + public const string DROPDOWN = "dropdown"; + /// + /// Constant BUTTON for button + /// + public const string BUTTON = "button"; + + } + + /// + /// The type of response returned by the dialog node. The specified response type must be supported by the + /// client application or channel. + /// + /// **Note:** The **suggestion** response type is part of the disambiguation feature, which is only available + /// for Premium users. + /// Constants for possible values can be found using RuntimeResponseGeneric.ResponseTypeValue + /// + [JsonProperty("response_type", NullValueHandling = NullValueHandling.Ignore)] + public string ResponseType { get; set; } + /// + /// The preferred type of control to display. + /// Constants for possible values can be found using RuntimeResponseGeneric.PreferenceValue + /// + [JsonProperty("preference", NullValueHandling = NullValueHandling.Ignore)] + public string Preference { get; set; } + /// + /// The text of the response. + /// + [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)] + public string Text { get; set; } + /// + /// How long to pause, in milliseconds. + /// + [JsonProperty("time", NullValueHandling = NullValueHandling.Ignore)] + public long? Time { get; set; } + /// + /// Whether to send a "user is typing" event during the pause. + /// + [JsonProperty("typing", NullValueHandling = NullValueHandling.Ignore)] + public bool? Typing { get; set; } + /// + /// The URL of the image. + /// + [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] + public string Source { get; set; } + /// + /// The title or introductory text to show before the response. + /// + [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)] + public string Title { get; set; } + /// + /// The description to show with the the response. + /// + [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] + public string Description { get; set; } + /// + /// An array of objects describing the options from which the user can choose. + /// + [JsonProperty("options", NullValueHandling = NullValueHandling.Ignore)] + public List Options { get; set; } + /// + /// A message to be sent to the human agent who will be taking over the conversation. + /// + [JsonProperty("message_to_human_agent", NullValueHandling = NullValueHandling.Ignore)] + public string MessageToHumanAgent { get; set; } + /// + /// A label identifying the topic of the conversation, derived from the **user_label** property of the relevant + /// node. + /// + [JsonProperty("topic", NullValueHandling = NullValueHandling.Ignore)] + public virtual string Topic { get; private set; } + /// + /// An array of objects describing the possible matching dialog nodes from which the user can choose. + /// + /// **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for + /// Premium users. + /// + [JsonProperty("suggestions", NullValueHandling = NullValueHandling.Ignore)] + public List Suggestions { get; set; } + /// + /// The title or introductory text to show before the response. This text is defined in the search skill + /// configuration. + /// + [JsonProperty("header", NullValueHandling = NullValueHandling.Ignore)] + public string Header { get; set; } + /// + /// An array of objects containing search results. + /// + [JsonProperty("results", NullValueHandling = NullValueHandling.Ignore)] + public List Results { get; set; } + } +} diff --git a/Scripts/Services/Assistant/V2/Model/RuntimeResponseGeneric.cs.meta b/Scripts/Services/Assistant/V2/Model/RuntimeResponseGeneric.cs.meta new file mode 100644 index 000000000..483e2a353 --- /dev/null +++ b/Scripts/Services/Assistant/V2/Model/RuntimeResponseGeneric.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9592b32c136e044bbb4519114e25bab9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Assistant/V2/Model/SearchResult.cs.meta b/Scripts/Services/Assistant/V2/Model/SearchResult.cs.meta new file mode 100644 index 000000000..75ed65d1a --- /dev/null +++ b/Scripts/Services/Assistant/V2/Model/SearchResult.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5de7d26dd33a94d34b849f640e6ab3ad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs b/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs index fa94949ea..bba57e04c 100644 --- a/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs +++ b/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs @@ -16,6 +16,7 @@ */ using System.Collections.Generic; +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; namespace IBM.Watson.Assistant.V2.Model @@ -24,7 +25,7 @@ namespace IBM.Watson.Assistant.V2.Model /// An object containing segments of text from search results with query-matching text highlighted using HTML /// tags. /// - public class SearchResultHighlight + public class SearchResultHighlight: DynamicModel> { /// /// An array of strings containing segments taken from body text in the search results, with query-matching diff --git a/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs.meta b/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs.meta new file mode 100644 index 000000000..573095dfe --- /dev/null +++ b/Scripts/Services/Assistant/V2/Model/SearchResultHighlight.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 34ed9a5dca0d54cfcbfb6af6c469a079 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Assistant/V2/Model/SearchResultMetadata.cs.meta b/Scripts/Services/Assistant/V2/Model/SearchResultMetadata.cs.meta new file mode 100644 index 000000000..838fa5364 --- /dev/null +++ b/Scripts/Services/Assistant/V2/Model/SearchResultMetadata.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c613a90cc21a54182a85e788da1e2839 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/CompareComplyService.cs b/Scripts/Services/CompareComply/V1/CompareComplyService.cs index a0cdeb9f2..190c1e379 100644 --- a/Scripts/Services/CompareComply/V1/CompareComplyService.cs +++ b/Scripts/Services/CompareComply/V1/CompareComplyService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.CompareComply.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.CompareComply.V1 public partial class CompareComplyService : BaseService { private const string serviceId = "compare_comply"; - private const string defaultUrl = "https://gateway.watsonplatform.net/compare-comply/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/compare-comply/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// CompareComplyService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public CompareComplyService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public CompareComplyService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// CompareComplyService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public CompareComplyService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public CompareComplyService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of CompareComplyService"); @@ -111,18 +81,10 @@ public CompareComplyService(string versionDate, Credentials credentials) : base( VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the CompareComply service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -133,21 +95,18 @@ public CompareComplyService(string versionDate, Credentials credentials) : base( /// /// The callback function that is invoked when the operation completes. /// The document to convert. - /// The filename for file. /// The content type of file. (optional) /// The analysis model to be used by the service. For the **Element classification** and /// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the /// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in /// batch-processing requests. (optional) /// HTMLReturn - public bool ConvertToHtml(Callback callback, System.IO.MemoryStream file, string filename, string fileContentType = null, string model = null) + public bool ConvertToHtml(Callback callback, System.IO.MemoryStream file, string fileContentType = null, string model = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ConvertToHtml`"); if (file == null) throw new ArgumentNullException("`file` is required for `ConvertToHtml`"); - if (string.IsNullOrEmpty(filename)) - throw new ArgumentNullException("`filename` is required for `ConvertToHtml`"); RequestObject req = new RequestObject { @@ -172,7 +131,7 @@ public bool ConvertToHtml(Callback callback, System.IO.MemoryStream req.Forms = new Dictionary(); if (file != null) { - req.Forms["file"] = new RESTConnector.Form(file, filename, fileContentType); + req.Forms["file"] = new RESTConnector.Form(file, "filename", fileContentType); } if (!string.IsNullOrEmpty(model)) { @@ -181,7 +140,7 @@ public bool ConvertToHtml(Callback callback, System.IO.MemoryStream req.OnResponse = OnConvertToHtmlResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/html_conversion"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/html_conversion", GetServiceUrl()); if (connector == null) { return false; @@ -266,7 +225,7 @@ public bool ClassifyElements(Callback callback, System.IO.Memory req.OnResponse = OnClassifyElementsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/element_classification"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/element_classification", GetServiceUrl()); if (connector == null) { return false; @@ -351,7 +310,7 @@ public bool ExtractTables(Callback callback, System.IO.MemoryStream req.OnResponse = OnExtractTablesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/tables"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/tables", GetServiceUrl()); if (connector == null) { return false; @@ -454,7 +413,7 @@ public bool CompareDocuments(Callback callback, System.IO.MemoryS req.OnResponse = OnCompareDocumentsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/comparison"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/comparison", GetServiceUrl()); if (connector == null) { return false; @@ -541,7 +500,7 @@ public bool AddFeedback(Callback callback, FeedbackDataInput fee req.OnResponse = OnAddFeedbackResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/feedback"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/feedback", GetServiceUrl()); if (connector == null) { return false; @@ -713,7 +672,7 @@ public bool ListFeedback(Callback callback, string feedbackType = req.OnResponse = OnListFeedbackResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/feedback"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/feedback", GetServiceUrl()); if (connector == null) { return false; @@ -792,7 +751,7 @@ public bool GetFeedback(Callback callback, string feedbackId, strin req.OnResponse = OnGetFeedbackResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/feedback/{0}", feedbackId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/feedback/{0}", feedbackId), GetServiceUrl()); if (connector == null) { return false; @@ -871,7 +830,7 @@ public bool DeleteFeedback(Callback callback, string feedbackId req.OnResponse = OnDeleteFeedbackResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/feedback/{0}", feedbackId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/feedback/{0}", feedbackId), GetServiceUrl()); if (connector == null) { return false; @@ -1010,7 +969,7 @@ public bool CreateBatch(Callback callback, string function, System. req.OnResponse = OnCreateBatchResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/batches"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/batches", GetServiceUrl()); if (connector == null) { return false; @@ -1078,7 +1037,7 @@ public bool ListBatches(Callback callback) req.OnResponse = OnListBatchesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/batches"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/batches", GetServiceUrl()); if (connector == null) { return false; @@ -1149,7 +1108,7 @@ public bool GetBatch(Callback callback, string batchId) req.OnResponse = OnGetBatchResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/batches/{0}", batchId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/batches/{0}", batchId), GetServiceUrl()); if (connector == null) { return false; @@ -1236,7 +1195,7 @@ public bool UpdateBatch(Callback callback, string batchId, string a req.OnResponse = OnUpdateBatchResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/batches/{0}", batchId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/batches/{0}", batchId), GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/CompareComply/V1/Model/Contexts.cs.meta b/Scripts/Services/CompareComply/V1/Model/Contexts.cs.meta new file mode 100644 index 000000000..da872adcb --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/Contexts.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 455d03913cfcd45788021fcac02533ab +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/ContractCurrencies.cs.meta b/Scripts/Services/CompareComply/V1/Model/ContractCurrencies.cs.meta new file mode 100644 index 000000000..ddbad6abd --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/ContractCurrencies.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4682a2429680f48c9a42eb9502f77f3a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/ContractTerms.cs.meta b/Scripts/Services/CompareComply/V1/Model/ContractTerms.cs.meta new file mode 100644 index 000000000..99d502fdc --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/ContractTerms.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a56d0df95350749668c595aeb120d4b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/ContractTypes.cs.meta b/Scripts/Services/CompareComply/V1/Model/ContractTypes.cs.meta new file mode 100644 index 000000000..5331d38b0 --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/ContractTypes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9c9375bb991540e8b164435765c7081 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/Interpretation.cs.meta b/Scripts/Services/CompareComply/V1/Model/Interpretation.cs.meta new file mode 100644 index 000000000..c5e611dcd --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/Interpretation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef39af4f15bf5480da6cc0fe8a5cd895 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/Mention.cs.meta b/Scripts/Services/CompareComply/V1/Model/Mention.cs.meta new file mode 100644 index 000000000..261c7c116 --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/Mention.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b0988f51de70842d8adc0bcc1d703a3e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/Paragraphs.cs.meta b/Scripts/Services/CompareComply/V1/Model/Paragraphs.cs.meta new file mode 100644 index 000000000..9a94e6eb3 --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/Paragraphs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f23ab7e851359416bbe058520f0f0ee1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/PaymentTerms.cs.meta b/Scripts/Services/CompareComply/V1/Model/PaymentTerms.cs.meta new file mode 100644 index 000000000..fb98777b8 --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/PaymentTerms.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0942fa37e2c364725a324618c721fc87 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/CompareComply/V1/Model/TableTitle.cs.meta b/Scripts/Services/CompareComply/V1/Model/TableTitle.cs.meta new file mode 100644 index 000000000..8e497dc55 --- /dev/null +++ b/Scripts/Services/CompareComply/V1/Model/TableTitle.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 448d10d7423084fe7a37edb800c6adb1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Discovery/V1/DiscoveryService.cs b/Scripts/Services/Discovery/V1/DiscoveryService.cs index 53d4730fa..ea1650165 100644 --- a/Scripts/Services/Discovery/V1/DiscoveryService.cs +++ b/Scripts/Services/Discovery/V1/DiscoveryService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Discovery.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.Discovery.V1 public partial class DiscoveryService : BaseService { private const string serviceId = "discovery"; - private const string defaultUrl = "https://gateway.watsonplatform.net/discovery/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/discovery/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// DiscoveryService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public DiscoveryService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public DiscoveryService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// DiscoveryService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public DiscoveryService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public DiscoveryService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of DiscoveryService"); @@ -111,18 +81,10 @@ public DiscoveryService(string versionDate, Credentials credentials) : base(vers VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the Discovery service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -182,7 +144,7 @@ public bool CreateEnvironment(Callback callback, string name, req.OnResponse = OnCreateEnvironmentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/environments"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/environments", GetServiceUrl()); if (connector == null) { return false; @@ -255,7 +217,7 @@ public bool ListEnvironments(Callback callback, string req.OnResponse = OnListEnvironmentsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/environments"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/environments", GetServiceUrl()); if (connector == null) { return false; @@ -324,7 +286,7 @@ public bool GetEnvironment(Callback callback, string environme req.OnResponse = OnGetEnvironmentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -411,7 +373,7 @@ public bool UpdateEnvironment(Callback callback, string enviro req.OnResponse = OnUpdateEnvironmentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -480,7 +442,7 @@ public bool DeleteEnvironment(Callback callback, stri req.OnResponse = OnDeleteEnvironmentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -558,7 +520,7 @@ public bool ListFields(Callback callback, string e req.OnResponse = OnListFieldsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/fields", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/fields", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -663,7 +625,7 @@ public bool CreateConfiguration(Callback callback, string environ req.OnResponse = OnCreateConfigurationResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/configurations", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/configurations", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -739,7 +701,7 @@ public bool ListConfigurations(Callback callback, st req.OnResponse = OnListConfigurationsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/configurations", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/configurations", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -811,7 +773,7 @@ public bool GetConfiguration(Callback callback, string environmen req.OnResponse = OnGetConfigurationResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/configurations/{1}", environmentId, configurationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/configurations/{1}", environmentId, configurationId), GetServiceUrl()); if (connector == null) { return false; @@ -918,7 +880,7 @@ public bool UpdateConfiguration(Callback callback, string environ req.OnResponse = OnUpdateConfigurationResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/configurations/{1}", environmentId, configurationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/configurations/{1}", environmentId, configurationId), GetServiceUrl()); if (connector == null) { return false; @@ -995,7 +957,7 @@ public bool DeleteConfiguration(Callback callback, req.OnResponse = OnDeleteConfigurationResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/configurations/{1}", environmentId, configurationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/configurations/{1}", environmentId, configurationId), GetServiceUrl()); if (connector == null) { return false; @@ -1029,124 +991,6 @@ private void OnDeleteConfigurationResponse(RESTConnector.Request req, RESTConnec ((RequestObject)req).Callback(response, resp.Error); } /// - /// Test configuration. - /// - /// **Deprecated** This method is no longer supported and is scheduled to be removed from service on July 31st - /// 2019. - /// - /// Runs a sample document through the default or your configuration and returns diagnostic information - /// designed to help you understand how the document was processed. The document is not added to the index. - /// - /// The callback function that is invoked when the operation completes. - /// The ID of the environment. - /// The configuration to use to process the document. If this part is provided, then - /// the provided configuration is used to process the document. If the **configuration_id** is also provided - /// (both are present at the same time), then request is rejected. The maximum supported configuration size is 1 - /// MB. Configuration parts larger than 1 MB are rejected. - /// See the `GET /configurations/{configuration_id}` operation for an example configuration. (optional) - /// The content of the document to ingest. The maximum supported file size when adding a file - /// to a collection is 50 megabytes, the maximum supported file size when testing a confiruration is 1 megabyte. - /// Files larger than the supported size are rejected. (optional) - /// The filename for file. (optional) - /// The content type of file. (optional) - /// The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are - /// rejected. - /// Example: ``` { - /// "Creator": "Johnny Appleseed", - /// "Subject": "Apples" - /// } ```. (optional) - /// Specify to only run the input document through the given step instead of running the - /// input document through the entire ingestion workflow. Valid values are `convert`, `enrich`, and `normalize`. - /// (optional) - /// The ID of the configuration to use to process the document. If the - /// **configuration** form part is also provided (both are present at the same time), then the request will be - /// rejected. (optional) - /// TestDocument - public bool TestConfigurationInEnvironment(Callback callback, string environmentId, string configuration = null, System.IO.MemoryStream file = null, string filename = null, string fileContentType = null, string metadata = null, string step = null, string configurationId = null) - { - if (callback == null) - throw new ArgumentNullException("`callback` is required for `TestConfigurationInEnvironment`"); - if (string.IsNullOrEmpty(environmentId)) - throw new ArgumentNullException("`environmentId` is required for `TestConfigurationInEnvironment`"); - - RequestObject req = new RequestObject - { - Callback = callback, - HttpMethod = UnityWebRequest.kHttpVerbPOST, - DisableSslVerification = DisableSslVerification - }; - - foreach (KeyValuePair kvp in customRequestHeaders) - { - req.Headers.Add(kvp.Key, kvp.Value); - } - - ClearCustomRequestHeaders(); - - foreach (KeyValuePair kvp in Common.GetSdkHeaders("discovery", "V1", "TestConfigurationInEnvironment")) - { - req.Headers.Add(kvp.Key, kvp.Value); - } - - req.Parameters["version"] = VersionDate; - req.Forms = new Dictionary(); - if (!string.IsNullOrEmpty(configuration)) - { - req.Forms["configuration"] = new RESTConnector.Form(configuration); - } - if (file != null) - { - req.Forms["file"] = new RESTConnector.Form(file, filename, fileContentType); - } - if (!string.IsNullOrEmpty(metadata)) - { - req.Forms["metadata"] = new RESTConnector.Form(metadata); - } - if (!string.IsNullOrEmpty(step)) - { - req.Parameters["step"] = step; - } - if (!string.IsNullOrEmpty(configurationId)) - { - req.Parameters["configuration_id"] = configurationId; - } - - req.OnResponse = OnTestConfigurationInEnvironmentResponse; - - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/preview", environmentId)); - if (connector == null) - { - return false; - } - - return connector.Send(req); - } - - private void OnTestConfigurationInEnvironmentResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - DetailedResponse response = new DetailedResponse(); - foreach (KeyValuePair kvp in resp.Headers) - { - response.Headers.Add(kvp.Key, kvp.Value); - } - response.StatusCode = resp.HttpResponseCode; - - try - { - string json = Encoding.UTF8.GetString(resp.Data); - response.Result = JsonConvert.DeserializeObject(json); - response.Response = json; - } - catch (Exception e) - { - Log.Error("DiscoveryService.OnTestConfigurationInEnvironmentResponse()", "Exception: {0}", e.ToString()); - resp.Success = false; - } - - if (((RequestObject)req).Callback != null) - ((RequestObject)req).Callback(response, resp.Error); - } - /// /// Create a collection. /// /// The callback function that is invoked when the operation completes. @@ -1203,7 +1047,7 @@ public bool CreateCollection(Callback callback, string environmentId req.OnResponse = OnCreateCollectionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -1279,7 +1123,7 @@ public bool ListCollections(Callback callback, string e req.OnResponse = OnListCollectionsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -1351,7 +1195,7 @@ public bool GetCollection(Callback callback, string environmentId, s req.OnResponse = OnGetCollectionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1438,7 +1282,7 @@ public bool UpdateCollection(Callback callback, string environmentId req.OnResponse = OnUpdateCollectionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1510,7 +1354,7 @@ public bool DeleteCollection(Callback callback, string req.OnResponse = OnDeleteCollectionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1584,7 +1428,7 @@ public bool ListCollectionFields(Callback callback req.OnResponse = OnListCollectionFieldsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/fields", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/fields", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1659,7 +1503,7 @@ public bool ListExpansions(Callback callback, string environmentId, req.OnResponse = OnListExpansionsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/expansions", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/expansions", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1696,8 +1540,7 @@ private void OnListExpansionsResponse(RESTConnector.Request req, RESTConnector.R /// Create or update expansion list. /// /// Create or replace the Expansion list for this collection. The maximum number of expanded terms per - /// collection is `500`. - /// The current expansion list is replaced with the uploaded content. + /// collection is `500`. The current expansion list is replaced with the uploaded content. /// /// The callback function that is invoked when the operation completes. /// The ID of the environment. @@ -1757,7 +1600,7 @@ public bool CreateExpansions(Callback callback, string environmentId req.OnResponse = OnCreateExpansionsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/expansions", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/expansions", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1832,7 +1675,7 @@ public bool DeleteExpansions(Callback callback, string environmentId, st req.OnResponse = OnDeleteExpansionsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/expansions", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/expansions", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1906,7 +1749,7 @@ public bool GetTokenizationDictionaryStatus(Callback ca req.OnResponse = OnGetTokenizationDictionaryStatusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -1990,7 +1833,7 @@ public bool CreateTokenizationDictionary(Callback callb req.OnResponse = OnCreateTokenizationDictionaryResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2064,7 +1907,7 @@ public bool DeleteTokenizationDictionary(Callback callback, string envir req.OnResponse = OnDeleteTokenizationDictionaryResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2138,7 +1981,7 @@ public bool GetStopwordListStatus(Callback callback, st req.OnResponse = OnGetStopwordListStatusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/word_lists/stopwords", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/word_lists/stopwords", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2223,7 +2066,7 @@ public bool CreateStopwordList(Callback callback, strin req.OnResponse = OnCreateStopwordListResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/word_lists/stopwords", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/word_lists/stopwords", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2298,7 +2141,7 @@ public bool DeleteStopwordList(Callback callback, string environmentId, req.OnResponse = OnDeleteStopwordListResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/word_lists/stopwords", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/word_lists/stopwords", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2367,8 +2210,7 @@ private void OnDeleteStopwordListResponse(RESTConnector.Request req, RESTConnect /// The filename for file. (optional) /// The content type of file. (optional) /// The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are - /// rejected. - /// Example: ``` { + /// rejected. Example: ``` { /// "Creator": "Johnny Appleseed", /// "Subject": "Apples" /// } ```. (optional) @@ -2414,7 +2256,7 @@ public bool AddDocument(Callback callback, string environmentI req.OnResponse = OnAddDocumentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/documents", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/documents", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2493,7 +2335,7 @@ public bool GetDocumentStatus(Callback callback, string environm req.OnResponse = OnGetDocumentStatusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/documents/{2}", environmentId, collectionId, documentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/documents/{2}", environmentId, collectionId, documentId), GetServiceUrl()); if (connector == null) { return false; @@ -2545,8 +2387,7 @@ private void OnGetDocumentStatusResponse(RESTConnector.Request req, RESTConnecto /// The filename for file. (optional) /// The content type of file. (optional) /// The maximum supported metadata file size is 1 MB. Metadata parts larger than 1 MB are - /// rejected. - /// Example: ``` { + /// rejected. Example: ``` { /// "Creator": "Johnny Appleseed", /// "Subject": "Apples" /// } ```. (optional) @@ -2594,7 +2435,7 @@ public bool UpdateDocument(Callback callback, string environme req.OnResponse = OnUpdateDocumentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/documents/{2}", environmentId, collectionId, documentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/documents/{2}", environmentId, collectionId, documentId), GetServiceUrl()); if (connector == null) { return false; @@ -2672,7 +2513,7 @@ public bool DeleteDocument(Callback callback, string env req.OnResponse = OnDeleteDocumentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/documents/{2}", environmentId, collectionId, documentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/documents/{2}", environmentId, collectionId, documentId), GetServiceUrl()); if (connector == null) { return false; @@ -2728,7 +2569,7 @@ private void OnDeleteDocumentResponse(RESTConnector.Request req, RESTConnector.R /// filters. Useful for applications to build lists, tables, and time series. For a full list of possible /// aggregations, see the Query reference. (optional) /// Number of results to return. (optional) - /// A comma-separated list of the portion of the document hierarchy to return. + /// A comma-separated list of the portion of the document hierarchy to return. /// (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. (optional) @@ -2752,8 +2593,6 @@ private void OnDeleteDocumentResponse(RESTConnector.Request req, RESTConnector.R /// When specified, duplicate results based on the field specified are removed /// from the returned results. Duplicate comparison is limited to the current query only, **offset** is not /// considered. This parameter is currently Beta functionality. (optional) - /// A comma-separated list of collection IDs to be queried against. Required when - /// querying multiple collections, invalid when performing a single collection query. (optional) /// When `true`, results are returned based on their similarity to the document IDs /// specified in the **similar.document_ids** parameter. (optional, default to false) /// A comma-separated list of document IDs to find similar documents. @@ -2768,10 +2607,16 @@ private void OnDeleteDocumentResponse(RESTConnector.Request req, RESTConnector.R /// towards field values closer to the current date. When a **number** type field is specified, returned results /// are biased towards higher field values. This parameter cannot be used in the same query as the **sort** /// parameter. (optional) - /// If `true`, queries are not stored in the Discovery **Logs** endpoint. (optional, + /// When `true` and the **natural_language_query** parameter is used, the + /// **natural_languge_query** parameter is spell checked. The most likely correction is retunred in the + /// **suggested_query** field of the response (if one exists). + /// + /// **Important:** this parameter is only valid when using the Cloud Pak version of Discovery. (optional, /// default to false) + /// If `true`, queries are not stored in the Discovery **Logs** endpoint. + /// (optional, default to false) /// QueryResponse - public bool Query(Callback callback, string environmentId, string collectionId, string filter = null, string query = null, string naturalLanguageQuery = null, bool? passages = null, string aggregation = null, long? count = null, string returnFields = null, long? offset = null, string sort = null, bool? highlight = null, string passagesFields = null, long? passagesCount = null, long? passagesCharacters = null, bool? deduplicate = null, string deduplicateField = null, string collectionIds = null, bool? similar = null, string similarDocumentIds = null, string similarFields = null, string bias = null, bool? loggingOptOut = null) + public bool Query(Callback callback, string environmentId, string collectionId, string filter = null, string query = null, string naturalLanguageQuery = null, bool? passages = null, string aggregation = null, long? count = null, string _return = null, long? offset = null, string sort = null, bool? highlight = null, string passagesFields = null, long? passagesCount = null, long? passagesCharacters = null, bool? deduplicate = null, string deduplicateField = null, bool? similar = null, string similarDocumentIds = null, string similarFields = null, string bias = null, bool? spellingSuggestions = null, bool? xWatsonLoggingOptOut = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Query`"); @@ -2803,9 +2648,9 @@ public bool Query(Callback callback, string environmentId, string req.Headers["Content-Type"] = "application/json"; req.Headers["Accept"] = "application/json"; - if (loggingOptOut != null) + if (xWatsonLoggingOptOut != null) { - req.Headers["X-Watson-Logging-Opt-Out"] = (bool)loggingOptOut ? "true" : "false"; + req.Headers["X-Watson-Logging-Opt-Out"] = (bool)xWatsonLoggingOptOut ? "true" : "false"; } JObject bodyObject = new JObject(); @@ -2821,8 +2666,8 @@ public bool Query(Callback callback, string environmentId, string bodyObject["aggregation"] = aggregation; if (count != null) bodyObject["count"] = JToken.FromObject(count); - if (!string.IsNullOrEmpty(returnFields)) - bodyObject["return"] = returnFields; + if (!string.IsNullOrEmpty(_return)) + bodyObject["return"] = _return; if (offset != null) bodyObject["offset"] = JToken.FromObject(offset); if (!string.IsNullOrEmpty(sort)) @@ -2839,8 +2684,6 @@ public bool Query(Callback callback, string environmentId, string bodyObject["deduplicate"] = JToken.FromObject(deduplicate); if (!string.IsNullOrEmpty(deduplicateField)) bodyObject["deduplicate.field"] = deduplicateField; - if (!string.IsNullOrEmpty(collectionIds)) - bodyObject["collection_ids"] = collectionIds; if (similar != null) bodyObject["similar"] = JToken.FromObject(similar); if (!string.IsNullOrEmpty(similarDocumentIds)) @@ -2849,11 +2692,13 @@ public bool Query(Callback callback, string environmentId, string bodyObject["similar.fields"] = similarFields; if (!string.IsNullOrEmpty(bias)) bodyObject["bias"] = bias; + if (spellingSuggestions != null) + bodyObject["spelling_suggestions"] = JToken.FromObject(spellingSuggestions); req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); req.OnResponse = OnQueryResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/query", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/query", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -2911,7 +2756,7 @@ private void OnQueryResponse(RESTConnector.Request req, RESTConnector.Response r /// aggregations, see the Query reference. (optional) /// Number of results to return. The maximum for the **count** and **offset** values /// together in any one query is **10000**. (optional) - /// A comma-separated list of the portion of the document hierarchy to return. + /// A comma-separated list of the portion of the document hierarchy to return. /// (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 @@ -2941,7 +2786,7 @@ private void OnQueryResponse(RESTConnector.Request req, RESTConnector.Response r /// A comma-separated list of field names that are used as a basis for comparison to /// identify similar documents. If not specified, the entire document is used for comparison. (optional) /// QueryNoticesResponse - public bool QueryNotices(Callback callback, string environmentId, string collectionId, string filter = null, string query = null, string naturalLanguageQuery = null, bool? passages = null, string aggregation = null, long? count = null, List returnFields = null, long? offset = null, List sort = null, bool? highlight = null, List passagesFields = null, long? passagesCount = null, long? passagesCharacters = null, string deduplicateField = null, bool? similar = null, List similarDocumentIds = null, List similarFields = null) + public bool QueryNotices(Callback callback, string environmentId, string collectionId, string filter = null, string query = null, string naturalLanguageQuery = null, bool? passages = null, string aggregation = null, long? count = null, List _return = null, long? offset = null, List sort = null, bool? highlight = null, List passagesFields = null, long? passagesCount = null, long? passagesCharacters = null, string deduplicateField = null, bool? similar = null, List similarDocumentIds = null, List similarFields = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `QueryNotices`"); @@ -2994,9 +2839,9 @@ public bool QueryNotices(Callback callback, string environ { req.Parameters["count"] = count; } - if (returnFields != null && returnFields.Count > 0) + if (_return != null && _return.Count > 0) { - req.Parameters["return"] = string.Join(",", returnFields.ToArray()); + req.Parameters["return"] = string.Join(",", _return.ToArray()); } if (offset != null) { @@ -3041,7 +2886,7 @@ public bool QueryNotices(Callback callback, string environ req.OnResponse = OnQueryNoticesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/notices", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/notices", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -3083,6 +2928,7 @@ private void OnQueryNoticesResponse(RESTConnector.Request req, RESTConnector.Res /// /// The callback function that is invoked when the operation completes. /// The ID of the environment. + /// A comma-separated list of collection IDs to be queried against. /// 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. /// (optional) @@ -3097,7 +2943,7 @@ private void OnQueryNoticesResponse(RESTConnector.Request req, RESTConnector.Res /// filters. Useful for applications to build lists, tables, and time series. For a full list of possible /// aggregations, see the Query reference. (optional) /// Number of results to return. (optional) - /// A comma-separated list of the portion of the document hierarchy to return. + /// A comma-separated list of the portion of the document hierarchy to return. /// (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. (optional) @@ -3121,8 +2967,6 @@ private void OnQueryNoticesResponse(RESTConnector.Request req, RESTConnector.Res /// When specified, duplicate results based on the field specified are removed /// from the returned results. Duplicate comparison is limited to the current query only, **offset** is not /// considered. This parameter is currently Beta functionality. (optional) - /// A comma-separated list of collection IDs to be queried against. Required when - /// querying multiple collections, invalid when performing a single collection query. (optional) /// When `true`, results are returned based on their similarity to the document IDs /// specified in the **similar.document_ids** parameter. (optional, default to false) /// A comma-separated list of document IDs to find similar documents. @@ -3137,10 +2981,10 @@ private void OnQueryNoticesResponse(RESTConnector.Request req, RESTConnector.Res /// towards field values closer to the current date. When a **number** type field is specified, returned results /// are biased towards higher field values. This parameter cannot be used in the same query as the **sort** /// parameter. (optional) - /// If `true`, queries are not stored in the Discovery **Logs** endpoint. (optional, - /// default to false) + /// If `true`, queries are not stored in the Discovery **Logs** endpoint. + /// (optional, default to false) /// QueryResponse - public bool FederatedQuery(Callback callback, string environmentId, string filter = null, string query = null, string naturalLanguageQuery = null, bool? passages = null, string aggregation = null, long? count = null, string returnFields = null, long? offset = null, string sort = null, bool? highlight = null, string passagesFields = null, long? passagesCount = null, long? passagesCharacters = null, bool? deduplicate = null, string deduplicateField = null, string collectionIds = null, bool? similar = null, string similarDocumentIds = null, string similarFields = null, string bias = null, bool? loggingOptOut = null) + public bool FederatedQuery(Callback callback, string environmentId, string collectionIds, string filter = null, string query = null, string naturalLanguageQuery = null, bool? passages = null, string aggregation = null, long? count = null, string _return = null, long? offset = null, string sort = null, bool? highlight = null, string passagesFields = null, long? passagesCount = null, long? passagesCharacters = null, bool? deduplicate = null, string deduplicateField = null, bool? similar = null, string similarDocumentIds = null, string similarFields = null, string bias = null, bool? xWatsonLoggingOptOut = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `FederatedQuery`"); @@ -3170,12 +3014,14 @@ public bool FederatedQuery(Callback callback, string environmentI req.Headers["Content-Type"] = "application/json"; req.Headers["Accept"] = "application/json"; - if (loggingOptOut != null) + if (xWatsonLoggingOptOut != null) { - req.Headers["X-Watson-Logging-Opt-Out"] = (bool)loggingOptOut ? "true" : "false"; + req.Headers["X-Watson-Logging-Opt-Out"] = (bool)xWatsonLoggingOptOut ? "true" : "false"; } JObject bodyObject = new JObject(); + if (!string.IsNullOrEmpty(collectionIds)) + bodyObject["collection_ids"] = collectionIds; if (!string.IsNullOrEmpty(filter)) bodyObject["filter"] = filter; if (!string.IsNullOrEmpty(query)) @@ -3188,8 +3034,8 @@ public bool FederatedQuery(Callback callback, string environmentI bodyObject["aggregation"] = aggregation; if (count != null) bodyObject["count"] = JToken.FromObject(count); - if (!string.IsNullOrEmpty(returnFields)) - bodyObject["return"] = returnFields; + if (!string.IsNullOrEmpty(_return)) + bodyObject["return"] = _return; if (offset != null) bodyObject["offset"] = JToken.FromObject(offset); if (!string.IsNullOrEmpty(sort)) @@ -3206,8 +3052,6 @@ public bool FederatedQuery(Callback callback, string environmentI bodyObject["deduplicate"] = JToken.FromObject(deduplicate); if (!string.IsNullOrEmpty(deduplicateField)) bodyObject["deduplicate.field"] = deduplicateField; - if (!string.IsNullOrEmpty(collectionIds)) - bodyObject["collection_ids"] = collectionIds; if (similar != null) bodyObject["similar"] = JToken.FromObject(similar); if (!string.IsNullOrEmpty(similarDocumentIds)) @@ -3220,7 +3064,7 @@ public bool FederatedQuery(Callback callback, string environmentI req.OnResponse = OnFederatedQueryResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/query", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/query", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -3276,7 +3120,7 @@ private void OnFederatedQueryResponse(RESTConnector.Request req, RESTConnector.R /// aggregations, see the Query reference. (optional) /// Number of results to return. The maximum for the **count** and **offset** values /// together in any one query is **10000**. (optional) - /// A comma-separated list of the portion of the document hierarchy to return. + /// A comma-separated list of the portion of the document hierarchy to return. /// (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 @@ -3300,7 +3144,7 @@ private void OnFederatedQueryResponse(RESTConnector.Request req, RESTConnector.R /// A comma-separated list of field names that are used as a basis for comparison to /// identify similar documents. If not specified, the entire document is used for comparison. (optional) /// QueryNoticesResponse - public bool FederatedQueryNotices(Callback callback, string environmentId, List collectionIds, string filter = null, string query = null, string naturalLanguageQuery = null, string aggregation = null, long? count = null, List returnFields = null, long? offset = null, List sort = null, bool? highlight = null, string deduplicateField = null, bool? similar = null, List similarDocumentIds = null, List similarFields = null) + public bool FederatedQueryNotices(Callback callback, string environmentId, List collectionIds, string filter = null, string query = null, string naturalLanguageQuery = null, string aggregation = null, long? count = null, List _return = null, long? offset = null, List sort = null, bool? highlight = null, string deduplicateField = null, bool? similar = null, List similarDocumentIds = null, List similarFields = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `FederatedQueryNotices`"); @@ -3353,9 +3197,9 @@ public bool FederatedQueryNotices(Callback callback, strin { req.Parameters["count"] = count; } - if (returnFields != null && returnFields.Count > 0) + if (_return != null && _return.Count > 0) { - req.Parameters["return"] = string.Join(",", returnFields.ToArray()); + req.Parameters["return"] = string.Join(",", _return.ToArray()); } if (offset != null) { @@ -3388,7 +3232,7 @@ public bool FederatedQueryNotices(Callback callback, strin req.OnResponse = OnFederatedQueryNoticesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/notices", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/notices", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -3422,38 +3266,35 @@ private void OnFederatedQueryNoticesResponse(RESTConnector.Request req, RESTConn ((RequestObject)req).Callback(response, resp.Error); } /// - /// Knowledge Graph entity query. + /// Get Autocomplete Suggestions. /// - /// See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) - /// for more details. + /// Returns completion query suggestions for the specified prefix. /n/n **Important:** this method is only + /// valid when using the Cloud Pak version of Discovery. /// /// The callback function that is invoked when the operation completes. /// The ID of the environment. /// The ID of the collection. - /// The entity query feature to perform. Supported features are `disambiguate` and - /// `similar_entities`. (optional) - /// A text string that appears within the entity text field. (optional) - /// Entity text to provide context for the queried entity and rank based on that - /// association. For example, if you wanted to query the city of London in England your query would look for - /// `London` with the context of `England`. (optional) - /// The number of results to return. The default is `10`. The maximum is `1000`. + /// The prefix to use for autocompletion. For example, the prefix `Ho` could autocomplete + /// to `Hot`, `Housing`, or `How do I upgrade`. Possible completions are. + /// The field in the result documents that autocompletion suggestions are identified from. /// (optional) - /// The number of evidence items to return for each result. The default is `0`. The - /// maximum number of evidence items per query is 10,000. (optional) - /// QueryEntitiesResponse - public bool QueryEntities(Callback callback, string environmentId, string collectionId, string feature = null, QueryEntitiesEntity entity = null, QueryEntitiesContext context = null, long? count = null, long? evidenceCount = null) + /// The number of autocompletion suggestions to return. (optional) + /// Completions + public bool GetAutocompletion(Callback callback, string environmentId, string collectionId, string prefix, string field = null, long? count = null) { if (callback == null) - throw new ArgumentNullException("`callback` is required for `QueryEntities`"); + throw new ArgumentNullException("`callback` is required for `GetAutocompletion`"); if (string.IsNullOrEmpty(environmentId)) - throw new ArgumentNullException("`environmentId` is required for `QueryEntities`"); + throw new ArgumentNullException("`environmentId` is required for `GetAutocompletion`"); if (string.IsNullOrEmpty(collectionId)) - throw new ArgumentNullException("`collectionId` is required for `QueryEntities`"); + throw new ArgumentNullException("`collectionId` is required for `GetAutocompletion`"); + if (string.IsNullOrEmpty(prefix)) + throw new ArgumentNullException("`prefix` is required for `GetAutocompletion`"); - RequestObject req = new RequestObject + RequestObject req = new RequestObject { Callback = callback, - HttpMethod = UnityWebRequest.kHttpVerbPOST, + HttpMethod = UnityWebRequest.kHttpVerbGET, DisableSslVerification = DisableSslVerification }; @@ -3464,135 +3305,28 @@ public bool QueryEntities(Callback callback, string envir ClearCustomRequestHeaders(); - foreach (KeyValuePair kvp in Common.GetSdkHeaders("discovery", "V1", "QueryEntities")) + foreach (KeyValuePair kvp in Common.GetSdkHeaders("discovery", "V1", "GetAutocompletion")) { req.Headers.Add(kvp.Key, kvp.Value); } req.Parameters["version"] = VersionDate; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - - JObject bodyObject = new JObject(); - if (!string.IsNullOrEmpty(feature)) - bodyObject["feature"] = feature; - if (entity != null) - bodyObject["entity"] = JToken.FromObject(entity); - if (context != null) - bodyObject["context"] = JToken.FromObject(context); - if (count != null) - bodyObject["count"] = JToken.FromObject(count); - if (evidenceCount != null) - bodyObject["evidence_count"] = JToken.FromObject(evidenceCount); - req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); - - req.OnResponse = OnQueryEntitiesResponse; - - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/query_entities", environmentId, collectionId)); - if (connector == null) + if (!string.IsNullOrEmpty(prefix)) { - return false; + req.Parameters["prefix"] = prefix; } - - return connector.Send(req); - } - - private void OnQueryEntitiesResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - DetailedResponse response = new DetailedResponse(); - foreach (KeyValuePair kvp in resp.Headers) + if (!string.IsNullOrEmpty(field)) { - response.Headers.Add(kvp.Key, kvp.Value); - } - response.StatusCode = resp.HttpResponseCode; - - try - { - string json = Encoding.UTF8.GetString(resp.Data); - response.Result = JsonConvert.DeserializeObject(json); - response.Response = json; + req.Parameters["field"] = field; } - catch (Exception e) - { - Log.Error("DiscoveryService.OnQueryEntitiesResponse()", "Exception: {0}", e.ToString()); - resp.Success = false; - } - - if (((RequestObject)req).Callback != null) - ((RequestObject)req).Callback(response, resp.Error); - } - /// - /// Knowledge Graph relationship query. - /// - /// See the [Knowledge Graph documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) - /// for more details. - /// - /// The callback function that is invoked when the operation completes. - /// The ID of the environment. - /// The ID of the collection. - /// An array of entities to find relationships for. (optional) - /// Entity text to provide context for the queried entity and rank based on that - /// association. For example, if you wanted to query the city of London in England your query would look for - /// `London` with the context of `England`. (optional) - /// The sorting method for the relationships, can be `score` or `frequency`. `frequency` is - /// the number of unique times each entity is identified. The default is `score`. This parameter cannot be used - /// in the same query as the **bias** parameter. (optional) - /// (optional) - /// The number of results to return. The default is `10`. The maximum is `1000`. - /// (optional) - /// The number of evidence items to return for each result. The default is `0`. The - /// maximum number of evidence items per query is 10,000. (optional) - /// QueryRelationsResponse - public bool QueryRelations(Callback callback, string environmentId, string collectionId, List entities = null, QueryEntitiesContext context = null, string sort = null, QueryRelationsFilter filter = null, long? count = null, long? evidenceCount = null) - { - if (callback == null) - throw new ArgumentNullException("`callback` is required for `QueryRelations`"); - if (string.IsNullOrEmpty(environmentId)) - throw new ArgumentNullException("`environmentId` is required for `QueryRelations`"); - if (string.IsNullOrEmpty(collectionId)) - throw new ArgumentNullException("`collectionId` is required for `QueryRelations`"); - - RequestObject req = new RequestObject - { - Callback = callback, - HttpMethod = UnityWebRequest.kHttpVerbPOST, - DisableSslVerification = DisableSslVerification - }; - - foreach (KeyValuePair kvp in customRequestHeaders) - { - req.Headers.Add(kvp.Key, kvp.Value); - } - - ClearCustomRequestHeaders(); - - foreach (KeyValuePair kvp in Common.GetSdkHeaders("discovery", "V1", "QueryRelations")) + if (count != null) { - req.Headers.Add(kvp.Key, kvp.Value); + req.Parameters["count"] = count; } - req.Parameters["version"] = VersionDate; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - - JObject bodyObject = new JObject(); - if (entities != null && entities.Count > 0) - bodyObject["entities"] = JToken.FromObject(entities); - if (context != null) - bodyObject["context"] = JToken.FromObject(context); - if (!string.IsNullOrEmpty(sort)) - bodyObject["sort"] = sort; - if (filter != null) - bodyObject["filter"] = JToken.FromObject(filter); - if (count != null) - bodyObject["count"] = JToken.FromObject(count); - if (evidenceCount != null) - bodyObject["evidence_count"] = JToken.FromObject(evidenceCount); - req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); - - req.OnResponse = OnQueryRelationsResponse; + req.OnResponse = OnGetAutocompletionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/query_relations", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/autocompletion", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -3601,9 +3335,9 @@ public bool QueryRelations(Callback callback, string env return connector.Send(req); } - private void OnQueryRelationsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetAutocompletionResponse(RESTConnector.Request req, RESTConnector.Response resp) { - DetailedResponse response = new DetailedResponse(); + DetailedResponse response = new DetailedResponse(); foreach (KeyValuePair kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); @@ -3613,17 +3347,17 @@ private void OnQueryRelationsResponse(RESTConnector.Request req, RESTConnector.R try { string json = Encoding.UTF8.GetString(resp.Data); - response.Result = JsonConvert.DeserializeObject(json); + response.Result = JsonConvert.DeserializeObject(json); response.Response = json; } catch (Exception e) { - Log.Error("DiscoveryService.OnQueryRelationsResponse()", "Exception: {0}", e.ToString()); + Log.Error("DiscoveryService.OnGetAutocompletionResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } - if (((RequestObject)req).Callback != null) - ((RequestObject)req).Callback(response, resp.Error); + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); } /// /// List training data. @@ -3666,7 +3400,7 @@ public bool ListTrainingData(Callback callback, string environm req.OnResponse = OnListTrainingDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -3756,7 +3490,7 @@ public bool AddTrainingData(Callback callback, string environment req.OnResponse = OnAddTrainingDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -3830,7 +3564,7 @@ public bool DeleteAllTrainingData(Callback callback, string environmentI req.OnResponse = OnDeleteAllTrainingDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data", environmentId, collectionId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data", environmentId, collectionId), GetServiceUrl()); if (connector == null) { return false; @@ -3907,7 +3641,7 @@ public bool GetTrainingData(Callback callback, string environment req.OnResponse = OnGetTrainingDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}", environmentId, collectionId, queryId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}", environmentId, collectionId, queryId), GetServiceUrl()); if (connector == null) { return false; @@ -3984,7 +3718,7 @@ public bool DeleteTrainingData(Callback callback, string environmentId, req.OnResponse = OnDeleteTrainingDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}", environmentId, collectionId, queryId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}", environmentId, collectionId, queryId), GetServiceUrl()); if (connector == null) { return false; @@ -4061,7 +3795,7 @@ public bool ListTrainingExamples(Callback callback, string req.OnResponse = OnListTrainingExamplesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples", environmentId, collectionId, queryId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples", environmentId, collectionId, queryId), GetServiceUrl()); if (connector == null) { return false; @@ -4152,7 +3886,7 @@ public bool CreateTrainingExample(Callback callback, string env req.OnResponse = OnCreateTrainingExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples", environmentId, collectionId, queryId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples", environmentId, collectionId, queryId), GetServiceUrl()); if (connector == null) { return false; @@ -4232,7 +3966,7 @@ public bool DeleteTrainingExample(Callback callback, string environmentI req.OnResponse = OnDeleteTrainingExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}", environmentId, collectionId, queryId, exampleId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}", environmentId, collectionId, queryId, exampleId), GetServiceUrl()); if (connector == null) { return false; @@ -4323,7 +4057,7 @@ public bool UpdateTrainingExample(Callback callback, string env req.OnResponse = OnUpdateTrainingExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}", environmentId, collectionId, queryId, exampleId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}", environmentId, collectionId, queryId, exampleId), GetServiceUrl()); if (connector == null) { return false; @@ -4403,7 +4137,7 @@ public bool GetTrainingExample(Callback callback, string enviro req.OnResponse = OnGetTrainingExampleResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}", environmentId, collectionId, queryId, exampleId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}", environmentId, collectionId, queryId, exampleId), GetServiceUrl()); if (connector == null) { return false; @@ -4483,7 +4217,7 @@ public bool DeleteUserData(Callback callback, string customerId) req.OnResponse = OnDeleteUserDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/user_data"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/user_data", GetServiceUrl()); if (connector == null) { return false; @@ -4567,7 +4301,7 @@ public bool CreateEvent(Callback callback, string type, Eve req.OnResponse = OnCreateEventResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/events"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/events", GetServiceUrl()); if (connector == null) { return false; @@ -4669,7 +4403,7 @@ public bool QueryLog(Callback callback, string filter = null, req.OnResponse = OnQueryLogResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/logs"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/logs", GetServiceUrl()); if (connector == null) { return false; @@ -4754,7 +4488,7 @@ public bool GetMetricsQuery(Callback callback, DateTime? startTi req.OnResponse = OnGetMetricsQueryResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/metrics/number_of_queries"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/metrics/number_of_queries", GetServiceUrl()); if (connector == null) { return false; @@ -4841,7 +4575,7 @@ public bool GetMetricsQueryEvent(Callback callback, DateTime? st req.OnResponse = OnGetMetricsQueryEventResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/metrics/number_of_queries_with_event"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/metrics/number_of_queries_with_event", GetServiceUrl()); if (connector == null) { return false; @@ -4927,7 +4661,7 @@ public bool GetMetricsQueryNoResults(Callback callback, DateTime req.OnResponse = OnGetMetricsQueryNoResultsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/metrics/number_of_queries_with_no_search_results"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/metrics/number_of_queries_with_no_search_results", GetServiceUrl()); if (connector == null) { return false; @@ -5014,7 +4748,7 @@ public bool GetMetricsEventRate(Callback callback, DateTime? sta req.OnResponse = OnGetMetricsEventRateResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/metrics/event_rate"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/metrics/event_rate", GetServiceUrl()); if (connector == null) { return false; @@ -5090,7 +4824,7 @@ public bool GetMetricsQueryTokenEvent(Callback callback, lo req.OnResponse = OnGetMetricsQueryTokenEventResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/metrics/top_query_tokens_with_event_rate"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/metrics/top_query_tokens_with_event_rate", GetServiceUrl()); if (connector == null) { return false; @@ -5163,7 +4897,7 @@ public bool ListCredentials(Callback callback, string environme req.OnResponse = OnListCredentialsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/credentials", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/credentials", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -5262,7 +4996,7 @@ public bool CreateCredentials(Callback callback, string enviro req.OnResponse = OnCreateCredentialsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/credentials", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/credentials", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -5339,7 +5073,7 @@ public bool GetCredentials(Callback callback, string environme req.OnResponse = OnGetCredentialsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/credentials/{1}", environmentId, credentialId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/credentials/{1}", environmentId, credentialId), GetServiceUrl()); if (connector == null) { return false; @@ -5440,7 +5174,7 @@ public bool UpdateCredentials(Callback callback, string enviro req.OnResponse = OnUpdateCredentialsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/credentials/{1}", environmentId, credentialId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/credentials/{1}", environmentId, credentialId), GetServiceUrl()); if (connector == null) { return false; @@ -5514,7 +5248,7 @@ public bool DeleteCredentials(Callback callback, string envir req.OnResponse = OnDeleteCredentialsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/credentials/{1}", environmentId, credentialId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/credentials/{1}", environmentId, credentialId), GetServiceUrl()); if (connector == null) { return false; @@ -5585,7 +5319,7 @@ public bool ListGateways(Callback callback, string environmentId) req.OnResponse = OnListGatewaysResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/gateways", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/gateways", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -5664,7 +5398,7 @@ public bool CreateGateway(Callback callback, string environmentId, stri req.OnResponse = OnCreateGatewayResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/gateways", environmentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/gateways", environmentId), GetServiceUrl()); if (connector == null) { return false; @@ -5738,7 +5472,7 @@ public bool GetGateway(Callback callback, string environmentId, string req.OnResponse = OnGetGatewayResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/gateways/{1}", environmentId, gatewayId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/gateways/{1}", environmentId, gatewayId), GetServiceUrl()); if (connector == null) { return false; @@ -5812,7 +5546,7 @@ public bool DeleteGateway(Callback callback, string environmentId req.OnResponse = OnDeleteGatewayResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/environments/{0}/gateways/{1}", environmentId, gatewayId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/environments/{0}/gateways/{1}", environmentId, gatewayId), GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/Discovery/V1/Model/AggregationResult.cs b/Scripts/Services/Discovery/V1/Model/AggregationResult.cs index 2a6e26a69..43f9087a8 100644 --- a/Scripts/Services/Discovery/V1/Model/AggregationResult.cs +++ b/Scripts/Services/Discovery/V1/Model/AggregationResult.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// AggregationResult. + /// Aggregation results for the specified query. /// public class AggregationResult { diff --git a/Scripts/Services/Discovery/V1/Model/Collection.cs b/Scripts/Services/Discovery/V1/Model/Collection.cs index 0561ac36c..2da681d1c 100644 --- a/Scripts/Services/Discovery/V1/Model/Collection.cs +++ b/Scripts/Services/Discovery/V1/Model/Collection.cs @@ -88,7 +88,7 @@ public class StatusValue [JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)] public string Language { get; set; } /// - /// Gets or Sets DocumentCounts + /// Object containing collection document count information. /// [JsonProperty("document_counts", NullValueHandling = NullValueHandling.Ignore)] public DocumentCounts DocumentCounts { get; set; } @@ -98,7 +98,7 @@ public class StatusValue [JsonProperty("disk_usage", NullValueHandling = NullValueHandling.Ignore)] public CollectionDiskUsage DiskUsage { get; set; } /// - /// Gets or Sets TrainingStatus + /// Training status details. /// [JsonProperty("training_status", NullValueHandling = NullValueHandling.Ignore)] public TrainingStatus TrainingStatus { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/Completions.cs b/Scripts/Services/Discovery/V1/Model/Completions.cs new file mode 100644 index 000000000..da8d8984a --- /dev/null +++ b/Scripts/Services/Discovery/V1/Model/Completions.cs @@ -0,0 +1,34 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.Discovery.V1.Model +{ + /// + /// An object containing an array of autocompletion suggestions. + /// + public class Completions + { + /// + /// Array of autcomplete suggestion based on the provided prefix. + /// + [JsonProperty("completions", NullValueHandling = NullValueHandling.Ignore)] + public List _Completions { get; set; } + } +} diff --git a/Scripts/Services/Discovery/V1/Model/Completions.cs.meta b/Scripts/Services/Discovery/V1/Model/Completions.cs.meta new file mode 100644 index 000000000..299718d32 --- /dev/null +++ b/Scripts/Services/Discovery/V1/Model/Completions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8561e0d151f674d94911334321810420 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/Discovery/V1/Model/CredentialDetails.cs b/Scripts/Services/Discovery/V1/Model/CredentialDetails.cs index 10035664a..b31507e52 100644 --- a/Scripts/Services/Discovery/V1/Model/CredentialDetails.cs +++ b/Scripts/Services/Discovery/V1/Model/CredentialDetails.cs @@ -30,12 +30,12 @@ public class CredentialDetails /// The authentication method for this credentials definition. The **credential_type** specified must be /// supported by the **source_type**. The following combinations are possible: /// - /// - `\"source_type\": \"box\"` - valid `credential_type`s: `oauth2` - /// - `\"source_type\": \"salesforce\"` - valid `credential_type`s: `username_password` - /// - `\"source_type\": \"sharepoint\"` - valid `credential_type`s: `saml` with **source_version** of `online`, - /// or `ntlm_v1` with **source_version** of `2016` - /// - `\"source_type\": \"web_crawl\"` - valid `credential_type`s: `noauth` or `basic` - /// - \"source_type\": \"cloud_object_storage\"` - valid `credential_type`s: `aws4_hmac`. + /// - `"source_type": "box"` - valid `credential_type`s: `oauth2` + /// - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` + /// - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or + /// `ntlm_v1` with **source_version** of `2016` + /// - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + /// - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. /// public class CredentialTypeValue { @@ -87,12 +87,12 @@ public class SourceVersionValue /// The authentication method for this credentials definition. The **credential_type** specified must be /// supported by the **source_type**. The following combinations are possible: /// - /// - `\"source_type\": \"box\"` - valid `credential_type`s: `oauth2` - /// - `\"source_type\": \"salesforce\"` - valid `credential_type`s: `username_password` - /// - `\"source_type\": \"sharepoint\"` - valid `credential_type`s: `saml` with **source_version** of `online`, - /// or `ntlm_v1` with **source_version** of `2016` - /// - `\"source_type\": \"web_crawl\"` - valid `credential_type`s: `noauth` or `basic` - /// - \"source_type\": \"cloud_object_storage\"` - valid `credential_type`s: `aws4_hmac`. + /// - `"source_type": "box"` - valid `credential_type`s: `oauth2` + /// - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` + /// - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with **source_version** of `online`, or + /// `ntlm_v1` with **source_version** of `2016` + /// - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + /// - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. /// Constants for possible values can be found using CredentialDetails.CredentialTypeValue /// [JsonProperty("credential_type", NullValueHandling = NullValueHandling.Ignore)] diff --git a/Scripts/Services/Discovery/V1/Model/CredentialsList.cs b/Scripts/Services/Discovery/V1/Model/CredentialsList.cs index e15409d9f..5010364ad 100644 --- a/Scripts/Services/Discovery/V1/Model/CredentialsList.cs +++ b/Scripts/Services/Discovery/V1/Model/CredentialsList.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// CredentialsList. + /// Object containing array of credential definitions. /// public class CredentialsList { diff --git a/Scripts/Services/Discovery/V1/Model/DeleteCollectionResponse.cs b/Scripts/Services/Discovery/V1/Model/DeleteCollectionResponse.cs index 4a489873d..d71ed1880 100644 --- a/Scripts/Services/Discovery/V1/Model/DeleteCollectionResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/DeleteCollectionResponse.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// DeleteCollectionResponse. + /// Response object returned when deleting a colleciton. /// public class DeleteCollectionResponse { diff --git a/Scripts/Services/Discovery/V1/Model/DeleteConfigurationResponse.cs b/Scripts/Services/Discovery/V1/Model/DeleteConfigurationResponse.cs index f405d360b..03a871b1f 100644 --- a/Scripts/Services/Discovery/V1/Model/DeleteConfigurationResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/DeleteConfigurationResponse.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// DeleteConfigurationResponse. + /// Information returned when a configuration is deleted. /// public class DeleteConfigurationResponse { diff --git a/Scripts/Services/Discovery/V1/Model/DeleteDocumentResponse.cs b/Scripts/Services/Discovery/V1/Model/DeleteDocumentResponse.cs index 7aa277a26..3289afded 100644 --- a/Scripts/Services/Discovery/V1/Model/DeleteDocumentResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/DeleteDocumentResponse.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// DeleteDocumentResponse. + /// Information returned when a document is deleted. /// public class DeleteDocumentResponse { diff --git a/Scripts/Services/Discovery/V1/Model/DeleteEnvironmentResponse.cs b/Scripts/Services/Discovery/V1/Model/DeleteEnvironmentResponse.cs index 637f19b9b..cf519ac74 100644 --- a/Scripts/Services/Discovery/V1/Model/DeleteEnvironmentResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/DeleteEnvironmentResponse.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// DeleteEnvironmentResponse. + /// Response object returned when deleting an environment. /// public class DeleteEnvironmentResponse { diff --git a/Scripts/Services/Discovery/V1/Model/DocumentAccepted.cs b/Scripts/Services/Discovery/V1/Model/DocumentAccepted.cs index 116845792..1e27a8a12 100644 --- a/Scripts/Services/Discovery/V1/Model/DocumentAccepted.cs +++ b/Scripts/Services/Discovery/V1/Model/DocumentAccepted.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// DocumentAccepted. + /// Information returned after an uploaded document is accepted. /// public class DocumentAccepted { diff --git a/Scripts/Services/Discovery/V1/Model/DocumentCounts.cs b/Scripts/Services/Discovery/V1/Model/DocumentCounts.cs index d556f94d5..f702ada15 100644 --- a/Scripts/Services/Discovery/V1/Model/DocumentCounts.cs +++ b/Scripts/Services/Discovery/V1/Model/DocumentCounts.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// DocumentCounts. + /// Object containing collection document count information. /// public class DocumentCounts { diff --git a/Scripts/Services/Discovery/V1/Model/Enrichment.cs b/Scripts/Services/Discovery/V1/Model/Enrichment.cs index 7df2e2c23..49f952fc4 100644 --- a/Scripts/Services/Discovery/V1/Model/Enrichment.cs +++ b/Scripts/Services/Discovery/V1/Model/Enrichment.cs @@ -20,7 +20,8 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// Enrichment. + /// Enrichment step to perform on the document. Each enrichment is performed on the specified field in the order + /// that they are listed in the configuration. /// public class Enrichment { @@ -61,7 +62,7 @@ public class Enrichment /// documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). /// [JsonProperty("enrichment", NullValueHandling = NullValueHandling.Ignore)] - public string EnrichmentName { get; set; } + public string _Enrichment { get; set; } /// /// If true, then most errors generated during the enrichment process will be treated as warnings and will not /// cause the document to fail processing. diff --git a/Scripts/Services/Discovery/V1/Model/EnrichmentOptions.cs b/Scripts/Services/Discovery/V1/Model/EnrichmentOptions.cs index dedf88fb3..5ce29ace0 100644 --- a/Scripts/Services/Discovery/V1/Model/EnrichmentOptions.cs +++ b/Scripts/Services/Discovery/V1/Model/EnrichmentOptions.cs @@ -81,7 +81,7 @@ public class LanguageValue [JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)] public string Language { get; set; } /// - /// Gets or Sets Features + /// Object containing Natural Language Understanding features to be used. /// [JsonProperty("features", NullValueHandling = NullValueHandling.Ignore)] public NluEnrichmentFeatures Features { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/Field.cs b/Scripts/Services/Discovery/V1/Model/Field.cs index 0979e78f9..7d71d7b90 100644 --- a/Scripts/Services/Discovery/V1/Model/Field.cs +++ b/Scripts/Services/Discovery/V1/Model/Field.cs @@ -20,14 +20,14 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// Field. + /// Object containing field details. /// public class Field { /// /// The type of the field. /// - public class FieldTypeValue + public class TypeValue { /// /// Constant NESTED for nested @@ -78,14 +78,14 @@ public class FieldTypeValue /// /// The type of the field. - /// Constants for possible values can be found using Field.FieldTypeValue + /// Constants for possible values can be found using Field.TypeValue /// [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] - public string FieldType { get; set; } + public string Type { get; set; } /// /// The name of the field. /// [JsonProperty("field", NullValueHandling = NullValueHandling.Ignore)] - public virtual string FieldName { get; private set; } + public virtual string _Field { get; private set; } } } diff --git a/Scripts/Services/Discovery/V1/Model/FontSetting.cs b/Scripts/Services/Discovery/V1/Model/FontSetting.cs index 4747ea7e5..112318fc7 100644 --- a/Scripts/Services/Discovery/V1/Model/FontSetting.cs +++ b/Scripts/Services/Discovery/V1/Model/FontSetting.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// FontSetting. + /// Font matching configuration. /// public class FontSetting { diff --git a/Scripts/Services/Discovery/V1/Model/HtmlSettings.cs b/Scripts/Services/Discovery/V1/Model/HtmlSettings.cs index 5161c7b89..e444b2162 100644 --- a/Scripts/Services/Discovery/V1/Model/HtmlSettings.cs +++ b/Scripts/Services/Discovery/V1/Model/HtmlSettings.cs @@ -36,12 +36,12 @@ public class HtmlSettings [JsonProperty("exclude_tags_keep_content", NullValueHandling = NullValueHandling.Ignore)] public List ExcludeTagsKeepContent { get; set; } /// - /// Gets or Sets KeepContent + /// Object containing an array of XPaths. /// [JsonProperty("keep_content", NullValueHandling = NullValueHandling.Ignore)] public XPathPatterns KeepContent { get; set; } /// - /// Gets or Sets ExcludeContent + /// Object containing an array of XPaths. /// [JsonProperty("exclude_content", NullValueHandling = NullValueHandling.Ignore)] public XPathPatterns ExcludeContent { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/ListCollectionsResponse.cs b/Scripts/Services/Discovery/V1/Model/ListCollectionsResponse.cs index 6f74c4186..cf8bf7530 100644 --- a/Scripts/Services/Discovery/V1/Model/ListCollectionsResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/ListCollectionsResponse.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// ListCollectionsResponse. + /// Response object containing an array of collection details. /// public class ListCollectionsResponse { diff --git a/Scripts/Services/Discovery/V1/Model/ListConfigurationsResponse.cs b/Scripts/Services/Discovery/V1/Model/ListConfigurationsResponse.cs index f229d575e..c485379de 100644 --- a/Scripts/Services/Discovery/V1/Model/ListConfigurationsResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/ListConfigurationsResponse.cs @@ -21,12 +21,12 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// ListConfigurationsResponse. + /// Object containing an array of available configurations. /// public class ListConfigurationsResponse { /// - /// An array of Configurations that are available for the service instance. + /// An array of configurations that are available for the service instance. /// [JsonProperty("configurations", NullValueHandling = NullValueHandling.Ignore)] public List Configurations { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/ListEnvironmentsResponse.cs b/Scripts/Services/Discovery/V1/Model/ListEnvironmentsResponse.cs index 0d8a03e76..1263ddac7 100644 --- a/Scripts/Services/Discovery/V1/Model/ListEnvironmentsResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/ListEnvironmentsResponse.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// ListEnvironmentsResponse. + /// Response object containing an array of configured environments. /// public class ListEnvironmentsResponse { diff --git a/Scripts/Services/Discovery/V1/Model/NluEnrichmentCategories.cs b/Scripts/Services/Discovery/V1/Model/NluEnrichmentCategories.cs index 464ee02f0..327432600 100644 --- a/Scripts/Services/Discovery/V1/Model/NluEnrichmentCategories.cs +++ b/Scripts/Services/Discovery/V1/Model/NluEnrichmentCategories.cs @@ -15,12 +15,14 @@ * */ +using IBM.Cloud.SDK.Model; + namespace IBM.Watson.Discovery.V1.Model { /// /// An object that indicates the Categories enrichment will be applied to the specified field. /// - public class NluEnrichmentCategories + public class NluEnrichmentCategories: DynamicModel { } } diff --git a/Scripts/Services/Discovery/V1/Model/NluEnrichmentEntities.cs b/Scripts/Services/Discovery/V1/Model/NluEnrichmentEntities.cs index 7d02126e6..87862317b 100644 --- a/Scripts/Services/Discovery/V1/Model/NluEnrichmentEntities.cs +++ b/Scripts/Services/Discovery/V1/Model/NluEnrichmentEntities.cs @@ -57,7 +57,7 @@ public class NluEnrichmentEntities public bool? SentenceLocations { get; set; } /// /// The enrichement model to use with entity extraction. May be a custom model provided by Watson Knowledge - /// Studio, the public model for use with Knowledge Graph `en-news`, or the default public model `alchemy`. + /// Studio, or the default public model `alchemy`. /// [JsonProperty("model", NullValueHandling = NullValueHandling.Ignore)] public string Model { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/NluEnrichmentFeatures.cs b/Scripts/Services/Discovery/V1/Model/NluEnrichmentFeatures.cs index 247b5219c..cd9e5e8f2 100644 --- a/Scripts/Services/Discovery/V1/Model/NluEnrichmentFeatures.cs +++ b/Scripts/Services/Discovery/V1/Model/NluEnrichmentFeatures.cs @@ -16,12 +16,11 @@ */ using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Discovery.V1.Model { /// - /// NluEnrichmentFeatures. + /// Object containing Natural Language Understanding features to be used. /// public class NluEnrichmentFeatures { @@ -49,7 +48,7 @@ public class NluEnrichmentFeatures /// An object that indicates the Categories enrichment will be applied to the specified field. /// [JsonProperty("categories", NullValueHandling = NullValueHandling.Ignore)] - public JObject Categories { get; set; } + public NluEnrichmentCategories Categories { get; set; } /// /// An object specifiying the semantic roles enrichment and related parameters. /// diff --git a/Scripts/Services/Discovery/V1/Model/NluEnrichmentRelations.cs b/Scripts/Services/Discovery/V1/Model/NluEnrichmentRelations.cs index 648d96cc4..50b8a2c8a 100644 --- a/Scripts/Services/Discovery/V1/Model/NluEnrichmentRelations.cs +++ b/Scripts/Services/Discovery/V1/Model/NluEnrichmentRelations.cs @@ -26,8 +26,8 @@ public class NluEnrichmentRelations { /// /// *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with - /// relationship extraction. May be a custom model provided by Watson Knowledge Studio, the public model for use - /// with Knowledge Graph `en-news`, the default is`en-news`. + /// relationship extraction. May be a custom model provided by Watson Knowledge Studio, the default public model + /// is`en-news`. /// [JsonProperty("model", NullValueHandling = NullValueHandling.Ignore)] public string Model { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/NormalizationOperation.cs b/Scripts/Services/Discovery/V1/Model/NormalizationOperation.cs index 1ccbda2ad..494d65273 100644 --- a/Scripts/Services/Discovery/V1/Model/NormalizationOperation.cs +++ b/Scripts/Services/Discovery/V1/Model/NormalizationOperation.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// NormalizationOperation. + /// Object containing normalization operations. /// public class NormalizationOperation { diff --git a/Scripts/Services/Discovery/V1/Model/PdfHeadingDetection.cs b/Scripts/Services/Discovery/V1/Model/PdfHeadingDetection.cs index 6232b41b3..85b101415 100644 --- a/Scripts/Services/Discovery/V1/Model/PdfHeadingDetection.cs +++ b/Scripts/Services/Discovery/V1/Model/PdfHeadingDetection.cs @@ -21,12 +21,12 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// PdfHeadingDetection. + /// Object containing heading detection conversion settings for PDF documents. /// public class PdfHeadingDetection { /// - /// Gets or Sets Fonts + /// Array of font matching configurations. /// [JsonProperty("fonts", NullValueHandling = NullValueHandling.Ignore)] public List Fonts { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/PdfSettings.cs b/Scripts/Services/Discovery/V1/Model/PdfSettings.cs index 638ecfa55..f0054ab39 100644 --- a/Scripts/Services/Discovery/V1/Model/PdfSettings.cs +++ b/Scripts/Services/Discovery/V1/Model/PdfSettings.cs @@ -25,7 +25,7 @@ namespace IBM.Watson.Discovery.V1.Model public class PdfSettings { /// - /// Gets or Sets Heading + /// Object containing heading detection conversion settings for PDF documents. /// [JsonProperty("heading", NullValueHandling = NullValueHandling.Ignore)] public PdfHeadingDetection Heading { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/QueryNoticesResponse.cs b/Scripts/Services/Discovery/V1/Model/QueryNoticesResponse.cs index 132ecdf34..5c445893b 100644 --- a/Scripts/Services/Discovery/V1/Model/QueryNoticesResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/QueryNoticesResponse.cs @@ -17,12 +17,11 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Discovery.V1.Model { /// - /// QueryNoticesResponse. + /// Object containing notice query results. /// public class QueryNoticesResponse { @@ -35,7 +34,7 @@ public class QueryNoticesResponse /// Array of document results that match the query. /// [JsonProperty("results", NullValueHandling = NullValueHandling.Ignore)] - public List Results { get; set; } + public List Results { get; set; } /// /// Array of aggregation results that match the query. /// diff --git a/Scripts/Services/Discovery/V1/Model/QueryNoticesResult.cs b/Scripts/Services/Discovery/V1/Model/QueryNoticesResult.cs index 1c0412487..bdf781190 100644 --- a/Scripts/Services/Discovery/V1/Model/QueryNoticesResult.cs +++ b/Scripts/Services/Discovery/V1/Model/QueryNoticesResult.cs @@ -16,14 +16,15 @@ */ using System.Collections.Generic; +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; namespace IBM.Watson.Discovery.V1.Model { /// - /// QueryNoticesResult. + /// Query result object. /// - public class QueryNoticesResult + public class QueryNoticesResult: DynamicModel { /// /// The type of the original source file. diff --git a/Scripts/Services/Discovery/V1/Model/QueryPassages.cs b/Scripts/Services/Discovery/V1/Model/QueryPassages.cs index 14779e0af..491f4f6e8 100644 --- a/Scripts/Services/Discovery/V1/Model/QueryPassages.cs +++ b/Scripts/Services/Discovery/V1/Model/QueryPassages.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// QueryPassages. + /// A passage query result. /// public class QueryPassages { diff --git a/Scripts/Services/Discovery/V1/Model/QueryResponse.cs b/Scripts/Services/Discovery/V1/Model/QueryResponse.cs index 17134432c..89ca7852e 100644 --- a/Scripts/Services/Discovery/V1/Model/QueryResponse.cs +++ b/Scripts/Services/Discovery/V1/Model/QueryResponse.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Discovery.V1.Model { @@ -35,7 +34,7 @@ public class QueryResponse /// Array of document results for the query. /// [JsonProperty("results", NullValueHandling = NullValueHandling.Ignore)] - public List Results { get; set; } + public List Results { get; set; } /// /// Array of aggregation results for the query. /// @@ -64,5 +63,10 @@ public class QueryResponse /// [JsonProperty("retrieval_details", NullValueHandling = NullValueHandling.Ignore)] public RetrievalDetails RetrievalDetails { get; set; } + /// + /// The suggestions for a misspelled natural language query. + /// + [JsonProperty("suggested_query", NullValueHandling = NullValueHandling.Ignore)] + public string SuggestedQuery { get; set; } } } diff --git a/Scripts/Services/Discovery/V1/Model/QueryResult.cs b/Scripts/Services/Discovery/V1/Model/QueryResult.cs index d6fdb7a8c..3da2e92be 100644 --- a/Scripts/Services/Discovery/V1/Model/QueryResult.cs +++ b/Scripts/Services/Discovery/V1/Model/QueryResult.cs @@ -16,14 +16,15 @@ */ using System.Collections.Generic; +using IBM.Cloud.SDK.Model; using Newtonsoft.Json; namespace IBM.Watson.Discovery.V1.Model { /// - /// QueryResult. + /// Query result object. /// - public class QueryResult + public class QueryResult: DynamicModel { /// /// The unique identifier of the document. diff --git a/Scripts/Services/Discovery/V1/Model/Term.cs b/Scripts/Services/Discovery/V1/Model/Term.cs index 631028857..10387157c 100644 --- a/Scripts/Services/Discovery/V1/Model/Term.cs +++ b/Scripts/Services/Discovery/V1/Model/Term.cs @@ -31,7 +31,7 @@ public class Term [JsonProperty("field", NullValueHandling = NullValueHandling.Ignore)] public string Field { get; set; } /// - /// Gets or Sets Count + /// The number of terms identified. /// [JsonProperty("count", NullValueHandling = NullValueHandling.Ignore)] public long? Count { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/TopHitsResults.cs b/Scripts/Services/Discovery/V1/Model/TopHitsResults.cs index d017724e1..69c498520 100644 --- a/Scripts/Services/Discovery/V1/Model/TopHitsResults.cs +++ b/Scripts/Services/Discovery/V1/Model/TopHitsResults.cs @@ -17,12 +17,11 @@ using System.Collections.Generic; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace IBM.Watson.Discovery.V1.Model { /// - /// TopHitsResults. + /// Top hit information for this query. /// public class TopHitsResults { @@ -35,6 +34,6 @@ public class TopHitsResults /// Top results returned by the aggregation. /// [JsonProperty("hits", NullValueHandling = NullValueHandling.Ignore)] - public List Hits { get; set; } + public List Hits { get; set; } } } diff --git a/Scripts/Services/Discovery/V1/Model/TrainingDataSet.cs b/Scripts/Services/Discovery/V1/Model/TrainingDataSet.cs index da55da619..898e0554d 100644 --- a/Scripts/Services/Discovery/V1/Model/TrainingDataSet.cs +++ b/Scripts/Services/Discovery/V1/Model/TrainingDataSet.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// TrainingDataSet. + /// Training information for a specific collection. /// public class TrainingDataSet { diff --git a/Scripts/Services/Discovery/V1/Model/TrainingExample.cs b/Scripts/Services/Discovery/V1/Model/TrainingExample.cs index 6bd1476e5..27793f36e 100644 --- a/Scripts/Services/Discovery/V1/Model/TrainingExample.cs +++ b/Scripts/Services/Discovery/V1/Model/TrainingExample.cs @@ -20,7 +20,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// TrainingExample. + /// Training example details. /// public class TrainingExample { diff --git a/Scripts/Services/Discovery/V1/Model/TrainingExampleList.cs b/Scripts/Services/Discovery/V1/Model/TrainingExampleList.cs index 7eb7b0c42..8a419e272 100644 --- a/Scripts/Services/Discovery/V1/Model/TrainingExampleList.cs +++ b/Scripts/Services/Discovery/V1/Model/TrainingExampleList.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// TrainingExampleList. + /// Object containing an array of training examples. /// public class TrainingExampleList { diff --git a/Scripts/Services/Discovery/V1/Model/TrainingQuery.cs b/Scripts/Services/Discovery/V1/Model/TrainingQuery.cs index 5c6a14dda..10200412a 100644 --- a/Scripts/Services/Discovery/V1/Model/TrainingQuery.cs +++ b/Scripts/Services/Discovery/V1/Model/TrainingQuery.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// TrainingQuery. + /// Training query details. /// public class TrainingQuery { diff --git a/Scripts/Services/Discovery/V1/Model/TrainingStatus.cs b/Scripts/Services/Discovery/V1/Model/TrainingStatus.cs index bf68ae5db..314bb7bf5 100644 --- a/Scripts/Services/Discovery/V1/Model/TrainingStatus.cs +++ b/Scripts/Services/Discovery/V1/Model/TrainingStatus.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// TrainingStatus. + /// Training status details. /// public class TrainingStatus { diff --git a/Scripts/Services/Discovery/V1/Model/WordHeadingDetection.cs b/Scripts/Services/Discovery/V1/Model/WordHeadingDetection.cs index bd92b9553..55b90d110 100644 --- a/Scripts/Services/Discovery/V1/Model/WordHeadingDetection.cs +++ b/Scripts/Services/Discovery/V1/Model/WordHeadingDetection.cs @@ -21,17 +21,17 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// WordHeadingDetection. + /// Object containing heading detection conversion settings for Microsoft Word documents. /// public class WordHeadingDetection { /// - /// Gets or Sets Fonts + /// Array of font matching configurations. /// [JsonProperty("fonts", NullValueHandling = NullValueHandling.Ignore)] public List Fonts { get; set; } /// - /// Gets or Sets Styles + /// Array of Microsoft Word styles to convert. /// [JsonProperty("styles", NullValueHandling = NullValueHandling.Ignore)] public List Styles { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/WordSettings.cs b/Scripts/Services/Discovery/V1/Model/WordSettings.cs index 860482a9e..c541f5459 100644 --- a/Scripts/Services/Discovery/V1/Model/WordSettings.cs +++ b/Scripts/Services/Discovery/V1/Model/WordSettings.cs @@ -25,7 +25,7 @@ namespace IBM.Watson.Discovery.V1.Model public class WordSettings { /// - /// Gets or Sets Heading + /// Object containing heading detection conversion settings for Microsoft Word documents. /// [JsonProperty("heading", NullValueHandling = NullValueHandling.Ignore)] public WordHeadingDetection Heading { get; set; } diff --git a/Scripts/Services/Discovery/V1/Model/WordStyle.cs b/Scripts/Services/Discovery/V1/Model/WordStyle.cs index 851bb6d39..42de4154e 100644 --- a/Scripts/Services/Discovery/V1/Model/WordStyle.cs +++ b/Scripts/Services/Discovery/V1/Model/WordStyle.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// WordStyle. + /// Microsoft Word styles to convert into a specified HTML head level. /// public class WordStyle { diff --git a/Scripts/Services/Discovery/V1/Model/XPathPatterns.cs b/Scripts/Services/Discovery/V1/Model/XPathPatterns.cs index c25b0662e..62678aeb6 100644 --- a/Scripts/Services/Discovery/V1/Model/XPathPatterns.cs +++ b/Scripts/Services/Discovery/V1/Model/XPathPatterns.cs @@ -21,7 +21,7 @@ namespace IBM.Watson.Discovery.V1.Model { /// - /// XPathPatterns. + /// Object containing an array of XPaths. /// public class XPathPatterns { diff --git a/Scripts/Services/LanguageTranslator/V3/LanguageTranslatorService.cs b/Scripts/Services/LanguageTranslator/V3/LanguageTranslatorService.cs index de3b4d2b7..c8441f8d6 100644 --- a/Scripts/Services/LanguageTranslator/V3/LanguageTranslatorService.cs +++ b/Scripts/Services/LanguageTranslator/V3/LanguageTranslatorService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.LanguageTranslator.V3.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.LanguageTranslator.V3 public partial class LanguageTranslatorService : BaseService { private const string serviceId = "language_translator"; - private const string defaultUrl = "https://gateway.watsonplatform.net/language-translator/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/language-translator/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// LanguageTranslatorService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public LanguageTranslatorService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public LanguageTranslatorService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// LanguageTranslatorService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public LanguageTranslatorService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public LanguageTranslatorService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of LanguageTranslatorService"); @@ -111,18 +81,10 @@ public LanguageTranslatorService(string versionDate, Credentials credentials) : VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the LanguageTranslator service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -182,7 +144,7 @@ public bool Translate(Callback callback, List text, s req.OnResponse = OnTranslateResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/translate"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/translate", GetServiceUrl()); if (connector == null) { return false; @@ -251,7 +213,7 @@ public bool ListIdentifiableLanguages(Callback callback) req.OnResponse = OnListIdentifiableLanguagesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/identifiable_languages"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/identifiable_languages", GetServiceUrl()); if (connector == null) { return false; @@ -325,7 +287,7 @@ public bool Identify(Callback callback, string text) req.OnResponse = OnIdentifyResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/identify"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/identify", GetServiceUrl()); if (connector == null) { return false; @@ -366,12 +328,12 @@ private void OnIdentifyResponse(RESTConnector.Request req, RESTConnector.Respons /// The callback function that is invoked when the operation completes. /// Specify a language code to filter results by source language. (optional) /// Specify a language code to filter results by target language. (optional) - /// If the default parameter isn't specified, the service will return all models - /// (default and non-default) for each language pair. To return only default models, set this to `true`. To - /// return only non-default models, set this to `false`. There is exactly one default model per language pair, - /// the IBM provided base model. (optional) + /// If the default parameter isn't specified, the service will return all models (default + /// and non-default) for each language pair. To return only default models, set this to `true`. To return only + /// non-default models, set this to `false`. There is exactly one default model per language pair, the IBM + /// provided base model. (optional) /// TranslationModels - public bool ListModels(Callback callback, string source = null, string target = null, bool? defaultModels = null) + public bool ListModels(Callback callback, string source = null, string target = null, bool? _default = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ListModels`"); @@ -404,14 +366,14 @@ public bool ListModels(Callback callback, string source = nul { req.Parameters["target"] = target; } - if (defaultModels != null) + if (_default != null) { - req.Parameters["default"] = (bool)defaultModels ? "true" : "false"; + req.Parameters["default"] = (bool)_default ? "true" : "false"; } req.OnResponse = OnListModelsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/models"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/models", GetServiceUrl()); if (connector == null) { return false; @@ -523,7 +485,7 @@ public bool CreateModel(Callback callback, string baseModelId, req.OnResponse = OnCreateModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/models"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/models", GetServiceUrl()); if (connector == null) { return false; @@ -594,7 +556,7 @@ public bool DeleteModel(Callback callback, string modelId) req.OnResponse = OnDeleteModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/models/{0}", modelId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/models/{0}", modelId), GetServiceUrl()); if (connector == null) { return false; @@ -667,7 +629,7 @@ public bool GetModel(Callback callback, string modelId) req.OnResponse = OnGetModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/models/{0}", modelId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/models/{0}", modelId), GetServiceUrl()); if (connector == null) { return false; @@ -735,7 +697,7 @@ public bool ListDocuments(Callback callback) req.OnResponse = OnListDocumentsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/documents"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/documents", GetServiceUrl()); if (connector == null) { return false; @@ -843,7 +805,7 @@ public bool TranslateDocument(Callback callback, System.IO.Memor req.OnResponse = OnTranslateDocumentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/documents"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/documents", GetServiceUrl()); if (connector == null) { return false; @@ -914,7 +876,7 @@ public bool GetDocumentStatus(Callback callback, string document req.OnResponse = OnGetDocumentStatusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/documents/{0}", documentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/documents/{0}", documentId), GetServiceUrl()); if (connector == null) { return false; @@ -985,7 +947,7 @@ public bool DeleteDocument(Callback callback, string documentId) req.OnResponse = OnDeleteDocumentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/documents/{0}", documentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/documents/{0}", documentId), GetServiceUrl()); if (connector == null) { return false; @@ -1065,7 +1027,7 @@ public bool GetTranslatedDocument(Callback callback, string documentId, req.OnResponse = OnGetTranslatedDocumentResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/documents/{0}/translated_document", documentId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/documents/{0}/translated_document", documentId), GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/LanguageTranslator/V3/Model/DeleteModelResult.cs b/Scripts/Services/LanguageTranslator/V3/Model/DeleteModelResult.cs index ae30b5229..1e5c9b391 100644 --- a/Scripts/Services/LanguageTranslator/V3/Model/DeleteModelResult.cs +++ b/Scripts/Services/LanguageTranslator/V3/Model/DeleteModelResult.cs @@ -25,7 +25,7 @@ namespace IBM.Watson.LanguageTranslator.V3.Model public class DeleteModelResult { /// - /// \"OK\" indicates that the model was successfully deleted. + /// "OK" indicates that the model was successfully deleted. /// [JsonProperty("status", NullValueHandling = NullValueHandling.Ignore)] public string Status { get; set; } diff --git a/Scripts/Services/LanguageTranslator/V3/Model/Translation.cs b/Scripts/Services/LanguageTranslator/V3/Model/Translation.cs index 4775a708d..373b2a192 100644 --- a/Scripts/Services/LanguageTranslator/V3/Model/Translation.cs +++ b/Scripts/Services/LanguageTranslator/V3/Model/Translation.cs @@ -28,6 +28,6 @@ public class Translation /// Translation output in UTF-8. /// [JsonProperty("translation", NullValueHandling = NullValueHandling.Ignore)] - public string TranslationOutput { get; set; } + public string _Translation { get; set; } } } diff --git a/Scripts/Services/NaturalLanguageClassifier/V1/NaturalLanguageClassifierService.cs b/Scripts/Services/NaturalLanguageClassifier/V1/NaturalLanguageClassifierService.cs index 06e17d66f..c844b4fb3 100644 --- a/Scripts/Services/NaturalLanguageClassifier/V1/NaturalLanguageClassifierService.cs +++ b/Scripts/Services/NaturalLanguageClassifier/V1/NaturalLanguageClassifierService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.NaturalLanguageClassifier.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.NaturalLanguageClassifier.V1 public partial class NaturalLanguageClassifierService : BaseService { private const string serviceId = "natural_language_classifier"; - private const string defaultUrl = "https://gateway.watsonplatform.net/natural-language-classifier/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/natural-language-classifier/api"; #region VersionDate #endregion @@ -81,30 +53,20 @@ public bool DisableSslVerification /// NaturalLanguageClassifierService constructor. /// - public NaturalLanguageClassifierService() : base(serviceId) - { - - } + public NaturalLanguageClassifierService() : this(ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// NaturalLanguageClassifierService constructor. /// - /// The service credentials. - public NaturalLanguageClassifierService(Credentials credentials) : base(credentials, serviceId) + /// The service authenticator. + public NaturalLanguageClassifierService(Authenticator authenticator) : base(authenticator, serviceId) { - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; + Authenticator = authenticator; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the NaturalLanguageClassifier service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -156,7 +118,7 @@ public bool Classify(Callback callback, string classifierId, str req.OnResponse = OnClassifyResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/classifiers/{0}/classify", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/classifiers/{0}/classify", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -239,7 +201,7 @@ public bool ClassifyCollection(Callback callback, stri req.OnResponse = OnClassifyCollectionResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/classifiers/{0}/classify_collection", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/classifiers/{0}/classify_collection", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -278,9 +240,9 @@ private void OnClassifyCollectionResponse(RESTConnector.Request req, RESTConnect /// Sends data to create and train a classifier and returns information about the new classifier. /// /// The callback function that is invoked when the operation completes. - /// Metadata in JSON format. The metadata identifies the language of the data, and an - /// optional name to identify the classifier. Specify the language with the 2-letter primary language code as - /// assigned in ISO standard 639. + /// Metadata in JSON format. The metadata identifies the language of the data, + /// and an optional name to identify the classifier. Specify the language with the 2-letter primary language + /// code as assigned in ISO standard 639. /// /// Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, (`de`), Italian (`it`), /// Japanese (`ja`), Korean (`ko`), Brazilian Portuguese (`pt`), and Spanish (`es`). @@ -288,12 +250,12 @@ private void OnClassifyCollectionResponse(RESTConnector.Request req, RESTConnect /// data can include up to 3,000 classes and 20,000 records. For details, see [Data /// preparation](https://cloud.ibm.com/docs/services/natural-language-classifier?topic=natural-language-classifier-using-your-data). /// Classifier - public bool CreateClassifier(Callback callback, System.IO.MemoryStream metadata, System.IO.MemoryStream trainingData) + public bool CreateClassifier(Callback callback, System.IO.MemoryStream trainingMetadata, System.IO.MemoryStream trainingData) { if (callback == null) throw new ArgumentNullException("`callback` is required for `CreateClassifier`"); - if (metadata == null) - throw new ArgumentNullException("`metadata` is required for `CreateClassifier`"); + if (trainingMetadata == null) + throw new ArgumentNullException("`trainingMetadata` is required for `CreateClassifier`"); if (trainingData == null) throw new ArgumentNullException("`trainingData` is required for `CreateClassifier`"); @@ -317,9 +279,9 @@ public bool CreateClassifier(Callback callback, System.IO.MemoryStre } req.Forms = new Dictionary(); - if (metadata != null) + if (trainingMetadata != null) { - req.Forms["training_metadata"] = new RESTConnector.Form(metadata, "filename", "application/json"); + req.Forms["training_metadata"] = new RESTConnector.Form(trainingMetadata, "filename", "application/json"); } if (trainingData != null) { @@ -328,7 +290,7 @@ public bool CreateClassifier(Callback callback, System.IO.MemoryStre req.OnResponse = OnCreateClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/classifiers"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/classifiers", GetServiceUrl()); if (connector == null) { return false; @@ -395,7 +357,7 @@ public bool ListClassifiers(Callback callback) req.OnResponse = OnListClassifiersResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/classifiers"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/classifiers", GetServiceUrl()); if (connector == null) { return false; @@ -465,7 +427,7 @@ public bool GetClassifier(Callback callback, string classifierId) req.OnResponse = OnGetClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/classifiers/{0}", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/classifiers/{0}", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -533,7 +495,7 @@ public bool DeleteClassifier(Callback callback, string classifierId) req.OnResponse = OnDeleteClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/classifiers/{0}", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/classifiers/{0}", classifierId), GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/NaturalLanguageUnderstanding/V1/Model/SemanticRolesResultModelObject.cs b/Scripts/Services/NaturalLanguageUnderstanding/V1/Model/SemanticRolesResultModelObject.cs new file mode 100644 index 000000000..20722439e --- /dev/null +++ b/Scripts/Services/NaturalLanguageUnderstanding/V1/Model/SemanticRolesResultModelObject.cs @@ -0,0 +1,39 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.NaturalLanguageUnderstanding.V1.Model +{ + /// + /// The extracted object from the sentence. + /// + public class SemanticRolesResultModelObject + { + /// + /// Object text. + /// + [JsonProperty("text", NullValueHandling = NullValueHandling.Ignore)] + public string Text { get; set; } + /// + /// An array of extracted keywords. + /// + [JsonProperty("keywords", NullValueHandling = NullValueHandling.Ignore)] + public List Keywords { get; set; } + } +} diff --git a/Scripts/Services/NaturalLanguageUnderstanding/V1/Model/SemanticRolesResultModelObject.cs.meta b/Scripts/Services/NaturalLanguageUnderstanding/V1/Model/SemanticRolesResultModelObject.cs.meta new file mode 100644 index 000000000..1e0a3069e --- /dev/null +++ b/Scripts/Services/NaturalLanguageUnderstanding/V1/Model/SemanticRolesResultModelObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 17e5eee8d262648128962e5e61f209ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/NaturalLanguageUnderstanding/V1/NaturalLanguageUnderstandingService.cs b/Scripts/Services/NaturalLanguageUnderstanding/V1/NaturalLanguageUnderstandingService.cs index 6c2801238..be77684b2 100644 --- a/Scripts/Services/NaturalLanguageUnderstanding/V1/NaturalLanguageUnderstandingService.cs +++ b/Scripts/Services/NaturalLanguageUnderstanding/V1/NaturalLanguageUnderstandingService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.NaturalLanguageUnderstanding.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.NaturalLanguageUnderstanding.V1 public partial class NaturalLanguageUnderstandingService : BaseService { private const string serviceId = "natural_language_understanding"; - private const string defaultUrl = "https://gateway.watsonplatform.net/natural-language-understanding/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/natural-language-understanding/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// NaturalLanguageUnderstandingService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public NaturalLanguageUnderstandingService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public NaturalLanguageUnderstandingService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// NaturalLanguageUnderstandingService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public NaturalLanguageUnderstandingService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public NaturalLanguageUnderstandingService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of NaturalLanguageUnderstandingService"); @@ -111,18 +81,10 @@ public NaturalLanguageUnderstandingService(string versionDate, Credentials crede VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the NaturalLanguageUnderstanding service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -225,7 +187,7 @@ public bool Analyze(Callback callback, Features features, strin req.OnResponse = OnAnalyzeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/analyze"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/analyze", GetServiceUrl()); if (connector == null) { return false; @@ -295,7 +257,7 @@ public bool ListModels(Callback callback) req.OnResponse = OnListModelsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/models"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/models", GetServiceUrl()); if (connector == null) { return false; @@ -366,7 +328,7 @@ public bool DeleteModel(Callback callback, string modelId) req.OnResponse = OnDeleteModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/models/{0}", modelId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/models/{0}", modelId), GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/PersonalityInsights/V3/Model/Warning.cs b/Scripts/Services/PersonalityInsights/V3/Model/Warning.cs index 667cf52dd..bb704b620 100644 --- a/Scripts/Services/PersonalityInsights/V3/Model/Warning.cs +++ b/Scripts/Services/PersonalityInsights/V3/Model/Warning.cs @@ -56,15 +56,15 @@ public class WarningIdValue public string WarningId { get; set; } /// /// The message associated with the `warning_id`: - /// * `WORD_COUNT_MESSAGE`: \"There were {number} words in the input. We need a minimum of 600, preferably 1,200 - /// or more, to compute statistically significant estimates.\" - /// * `JSON_AS_TEXT`: \"Request input was processed as text/plain as indicated, however detected a JSON input. - /// Did you mean application/json?\" - /// * `CONTENT_TRUNCATED`: \"For maximum accuracy while also optimizing processing time, only the first 250KB of + /// * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a minimum of 600, preferably 1,200 + /// or more, to compute statistically significant estimates." + /// * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, however detected a JSON input. + /// Did you mean application/json?" + /// * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing time, only the first 250KB of /// input text (excluding markup) was analyzed. Accuracy levels off at approximately 3,000 words so this did not - /// affect the accuracy of the profile.\" - /// * `PARTIAL_TEXT_USED`, \"The text provided to compute the profile was trimmed for performance reasons. This - /// action does not affect the accuracy of the output, as not all of the input text was required.\" Applies only + /// affect the accuracy of the profile." + /// * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for performance reasons. This + /// action does not affect the accuracy of the output, as not all of the input text was required." Applies only /// when Arabic input text exceeds a threshold at which additional words do not contribute to the accuracy of /// the profile. /// diff --git a/Scripts/Services/PersonalityInsights/V3/PersonalityInsightsService.cs b/Scripts/Services/PersonalityInsights/V3/PersonalityInsightsService.cs index 13586b212..b7a56605a 100644 --- a/Scripts/Services/PersonalityInsights/V3/PersonalityInsightsService.cs +++ b/Scripts/Services/PersonalityInsights/V3/PersonalityInsightsService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.PersonalityInsights.V3.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.PersonalityInsights.V3 public partial class PersonalityInsightsService : BaseService { private const string serviceId = "personality_insights"; - private const string defaultUrl = "https://gateway.watsonplatform.net/personality-insights/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/personality-insights/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// PersonalityInsightsService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public PersonalityInsightsService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public PersonalityInsightsService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// PersonalityInsightsService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public PersonalityInsightsService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public PersonalityInsightsService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of PersonalityInsightsService"); @@ -111,18 +81,10 @@ public PersonalityInsightsService(string versionDate, Credentials credentials) : VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the PersonalityInsights service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -171,6 +133,8 @@ public PersonalityInsightsService(string versionDate, Credentials credentials) : /// for more information, see [Providing sufficient /// input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient). /// For JSON input, provide an object of type `Content`. + /// The type of the input. For more information, see **Content types** in the method + /// description. (optional, default to text/plain) /// The language of the input text for the request: Arabic, English, Japanese, /// Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is /// interpreted as `en`. @@ -193,10 +157,8 @@ public PersonalityInsightsService(string versionDate, Credentials credentials) : /// false) /// Indicates whether consumption preferences are returned with the /// results. By default, no consumption preferences are returned. (optional, default to false) - /// The type of the input. For more information, see **Content types** in the method - /// description. (optional, default to text/plain) /// Profile - public bool Profile(Callback callback, Content content, string contentLanguage = null, string acceptLanguage = null, bool? rawScores = null, bool? csvHeaders = null, bool? consumptionPreferences = null, string contentType = null) + public bool Profile(Callback callback, Content content, string contentType = null, string contentLanguage = null, string acceptLanguage = null, bool? rawScores = null, bool? csvHeaders = null, bool? consumptionPreferences = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Profile`"); @@ -237,6 +199,11 @@ public bool Profile(Callback callback, Content content, string contentL } req.Headers["Accept"] = "application/json"; + if (!string.IsNullOrEmpty(contentType)) + { + req.Headers["Content-Type"] = contentType; + } + if (!string.IsNullOrEmpty(contentLanguage)) { req.Headers["Content-Language"] = contentLanguage; @@ -246,16 +213,11 @@ public bool Profile(Callback callback, Content content, string contentL { req.Headers["Accept-Language"] = acceptLanguage; } - - if (!string.IsNullOrEmpty(contentType)) - { - req.Headers["Content-Type"] = contentType; - } req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content)); req.OnResponse = OnProfileResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/profile"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/profile", GetServiceUrl()); if (connector == null) { return false; @@ -333,6 +295,8 @@ private void OnProfileResponse(RESTConnector.Request req, RESTConnector.Response /// for more information, see [Providing sufficient /// input](https://cloud.ibm.com/docs/services/personality-insights?topic=personality-insights-input#sufficient). /// For JSON input, provide an object of type `Content`. + /// The type of the input. For more information, see **Content types** in the method + /// description. (optional, default to text/plain) /// The language of the input text for the request: Arabic, English, Japanese, /// Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is /// interpreted as `en`. @@ -355,10 +319,8 @@ private void OnProfileResponse(RESTConnector.Request req, RESTConnector.Response /// false) /// Indicates whether consumption preferences are returned with the /// results. By default, no consumption preferences are returned. (optional, default to false) - /// The type of the input. For more information, see **Content types** in the method - /// description. (optional, default to text/plain) /// System.IO.MemoryStream - public bool ProfileAsCsv(Callback callback, Content content, string contentLanguage = null, string acceptLanguage = null, bool? rawScores = null, bool? csvHeaders = null, bool? consumptionPreferences = null, string contentType = null) + public bool ProfileAsCsv(Callback callback, Content content, string contentType = null, string contentLanguage = null, string acceptLanguage = null, bool? rawScores = null, bool? csvHeaders = null, bool? consumptionPreferences = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ProfileAsCsv`"); @@ -399,6 +361,11 @@ public bool ProfileAsCsv(Callback callback, Content cont } req.Headers["Accept"] = "text/csv"; + if (!string.IsNullOrEmpty(contentType)) + { + req.Headers["Content-Type"] = contentType; + } + if (!string.IsNullOrEmpty(contentLanguage)) { req.Headers["Content-Language"] = contentLanguage; @@ -408,16 +375,11 @@ public bool ProfileAsCsv(Callback callback, Content cont { req.Headers["Accept-Language"] = acceptLanguage; } - - if (!string.IsNullOrEmpty(contentType)) - { - req.Headers["Content-Type"] = contentType; - } req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content)); req.OnResponse = OnProfileAsCsvResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/profile"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/profile", GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/SpeechToText/V1/Model/LanguageModel.cs b/Scripts/Services/SpeechToText/V1/Model/LanguageModel.cs index 8ed880e14..ddabb3d8d 100644 --- a/Scripts/Services/SpeechToText/V1/Model/LanguageModel.cs +++ b/Scripts/Services/SpeechToText/V1/Model/LanguageModel.cs @@ -104,12 +104,14 @@ public class StatusValue [JsonProperty("language", NullValueHandling = NullValueHandling.Ignore)] public string Language { get; set; } /// - /// The dialect of the language for the custom language model. By default, the dialect matches the language of - /// the base model; for example, `en-US` for either of the US English language models. For Spanish models, the - /// field indicates the dialect for which the model was created: - /// * `es-ES` for Castilian Spanish (the default) - /// * `es-LA` for Latin American Spanish - /// * `es-US` for North American (Mexican) Spanish. + /// The dialect of the language for the custom language model. For non-Spanish models, the field matches the + /// language of the base model; for example, `en-US` for either of the US English language models. For Spanish + /// models, the field indicates the dialect for which the model was created: + /// * `es-ES` for Castilian Spanish (`es-ES` models) + /// * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models) + /// * `es-US` for Mexican (North American) Spanish (`es-MX` models) + /// + /// Dialect values are case-insensitive. /// [JsonProperty("dialect", NullValueHandling = NullValueHandling.Ignore)] public string Dialect { get; set; } diff --git a/Scripts/Services/SpeechToText/V1/Model/RecognitionJob.cs b/Scripts/Services/SpeechToText/V1/Model/RecognitionJob.cs index fe9257ba2..339af8b35 100644 --- a/Scripts/Services/SpeechToText/V1/Model/RecognitionJob.cs +++ b/Scripts/Services/SpeechToText/V1/Model/RecognitionJob.cs @@ -109,9 +109,9 @@ public class StatusValue public List Results { get; set; } /// /// An array of warning messages about invalid parameters included with the request. Each warning includes a - /// descriptive message and a list of invalid argument strings, for example, `\"unexpected query parameter - /// 'user_token', query parameter 'callback_url' was not specified\"`. The request succeeds despite the - /// warnings. This field can be returned only by the **Create a job** method. + /// descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter + /// 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. + /// This field can be returned only by the **Create a job** method. /// [JsonProperty("warnings", NullValueHandling = NullValueHandling.Ignore)] public List Warnings { get; set; } diff --git a/Scripts/Services/SpeechToText/V1/Model/SpeakerLabelsResult.cs b/Scripts/Services/SpeechToText/V1/Model/SpeakerLabelsResult.cs index a62b324da..4cb5f8cac 100644 --- a/Scripts/Services/SpeechToText/V1/Model/SpeakerLabelsResult.cs +++ b/Scripts/Services/SpeechToText/V1/Model/SpeakerLabelsResult.cs @@ -56,6 +56,6 @@ public class SpeakerLabelsResult /// `false` means that the service might send further updates to the results. /// [JsonProperty("final", NullValueHandling = NullValueHandling.Ignore)] - public bool? FinalResults { get; set; } + public bool? Final { get; set; } } } diff --git a/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionAlternative.cs b/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionAlternative.cs index 177c750d8..ad3876fb1 100644 --- a/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionAlternative.cs +++ b/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionAlternative.cs @@ -39,17 +39,17 @@ public class SpeechRecognitionAlternative /// /// Time alignments for each word from the transcript as a list of lists. Each inner list consists of three /// elements: the word followed by its start and end time in seconds, for example: - /// `[[\"hello\",0.0,1.2],[\"world\",1.2,2.5]]`. Timestamps are returned only for the best alternative. + /// `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. /// [JsonProperty("timestamps", NullValueHandling = NullValueHandling.Ignore)] - public string[][] Timestamps { get; set; } + public List Timestamps { get; set; } /// /// A confidence score for each word of the transcript as a list of lists. Each inner list consists of two /// elements: the word and its confidence score in the range of 0.0 to 1.0, for example: - /// `[[\"hello\",0.95],[\"world\",0.866]]`. Confidence scores are returned only for the best alternative and - /// only with results marked as final. + /// `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the best alternative and only + /// with results marked as final. /// [JsonProperty("word_confidence", NullValueHandling = NullValueHandling.Ignore)] - public string[][] WordConfidence { get; set; } + public List WordConfidence { get; set; } } } diff --git a/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResult.cs b/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResult.cs index 2f1c07dff..c458a5a27 100644 --- a/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResult.cs +++ b/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResult.cs @@ -31,7 +31,7 @@ public class SpeechRecognitionResult /// final. /// [JsonProperty("final", NullValueHandling = NullValueHandling.Ignore)] - public bool? FinalResults { get; set; } + public bool? Final { get; set; } /// /// An array of alternative transcripts. The `alternatives` array can include additional requested output such /// as word confidence or timestamps. diff --git a/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResults.cs b/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResults.cs index 5585b5ecd..631d004d0 100644 --- a/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResults.cs +++ b/Scripts/Services/SpeechToText/V1/Model/SpeechRecognitionResults.cs @@ -62,13 +62,13 @@ public class SpeechRecognitionResults /// /// An array of warning messages associated with the request: /// * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument - /// strings, for example, `\"Unknown arguments:\"` or `\"Unknown url query arguments:\"` followed by a list of - /// the form `\"{invalid_arg_1}, {invalid_arg_2}.\"` + /// strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the + /// form `"{invalid_arg_1}, {invalid_arg_2}."` /// * The following warning is returned if the request passes a custom model that is based on an older version - /// of a base model for which an updated version is available: `\"Using previous version of base model, because + /// of a base model for which an updated version is available: `"Using previous version of base model, because /// your custom model has been built with it. Please note that this version will be supported only for a limited /// time. Consider updating your custom model to the new base model. If you do not do that you will be - /// automatically switched to base model when you used the non-updated custom model.\"` + /// automatically switched to base model when you used the non-updated custom model."` /// /// In both cases, the request succeeds despite the warnings. /// diff --git a/Scripts/Services/SpeechToText/V1/Model/TrainingResponse.cs b/Scripts/Services/SpeechToText/V1/Model/TrainingResponse.cs new file mode 100644 index 000000000..731e5e655 --- /dev/null +++ b/Scripts/Services/SpeechToText/V1/Model/TrainingResponse.cs @@ -0,0 +1,36 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.SpeechToText.V1.Model +{ + /// + /// The response from training of a custom language or custom acoustic model. + /// + public class TrainingResponse + { + /// + /// An array of `TrainingWarning` objects that lists any invalid resources contained in the custom model. For + /// custom language models, invalid resources are grouped and identified by type of resource. The method can + /// return warnings only if the `strict` parameter is set to `false`. + /// + [JsonProperty("warnings", NullValueHandling = NullValueHandling.Ignore)] + public List Warnings { get; set; } + } +} diff --git a/Scripts/Services/SpeechToText/V1/Model/TrainingResponse.cs.meta b/Scripts/Services/SpeechToText/V1/Model/TrainingResponse.cs.meta new file mode 100644 index 000000000..aef7e0f8f --- /dev/null +++ b/Scripts/Services/SpeechToText/V1/Model/TrainingResponse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dcd99cb41561248b7a0690f67094891a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/SpeechToText/V1/Model/TrainingWarning.cs b/Scripts/Services/SpeechToText/V1/Model/TrainingWarning.cs new file mode 100644 index 000000000..1be2cc357 --- /dev/null +++ b/Scripts/Services/SpeechToText/V1/Model/TrainingWarning.cs @@ -0,0 +1,65 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.SpeechToText.V1.Model +{ + /// + /// A warning from training of a custom language or custom acoustic model. + /// + public class TrainingWarning + { + /// + /// An identifier for the type of invalid resources listed in the `description` field. + /// + public class CodeValue + { + /// + /// Constant INVALID_AUDIO_FILES for invalid_audio_files + /// + public const string INVALID_AUDIO_FILES = "invalid_audio_files"; + /// + /// Constant INVALID_CORPUS_FILES for invalid_corpus_files + /// + public const string INVALID_CORPUS_FILES = "invalid_corpus_files"; + /// + /// Constant INVALID_GRAMMAR_FILES for invalid_grammar_files + /// + public const string INVALID_GRAMMAR_FILES = "invalid_grammar_files"; + /// + /// Constant INVALID_WORDS for invalid_words + /// + public const string INVALID_WORDS = "invalid_words"; + + } + + /// + /// An identifier for the type of invalid resources listed in the `description` field. + /// Constants for possible values can be found using TrainingWarning.CodeValue + /// + [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)] + public string Code { get; set; } + /// + /// A warning message that lists the invalid resources that are excluded from the custom model's training. The + /// message has the following format: `Analysis of the following {resource_type} has not completed successfully: + /// [{resource_names}]. They will be excluded from custom {model_type} model training.`. + /// + [JsonProperty("message", NullValueHandling = NullValueHandling.Ignore)] + public string Message { get; set; } + } +} diff --git a/Scripts/Services/SpeechToText/V1/Model/TrainingWarning.cs.meta b/Scripts/Services/SpeechToText/V1/Model/TrainingWarning.cs.meta new file mode 100644 index 000000000..aa02b9b15 --- /dev/null +++ b/Scripts/Services/SpeechToText/V1/Model/TrainingWarning.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 002cf191bd8b24cb48acb9d7d22c7012 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/SpeechToText/V1/Model/WordError.cs b/Scripts/Services/SpeechToText/V1/Model/WordError.cs index 2050610a7..0db11e84a 100644 --- a/Scripts/Services/SpeechToText/V1/Model/WordError.cs +++ b/Scripts/Services/SpeechToText/V1/Model/WordError.cs @@ -26,10 +26,10 @@ public class WordError { /// /// A key-value pair that describes an error associated with the definition of a word in the words resource. The - /// pair has the format `\"element\": \"message\"`, where `element` is the aspect of the definition that caused - /// the problem and `message` describes the problem. The following example describes a problem with one of the - /// word's sounds-like definitions: `\"{sounds_like_string}\": \"Numbers are not allowed in sounds-like. You can - /// try for example '{suggested_string}'.\"`. + /// pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the + /// problem and `message` describes the problem. The following example describes a problem with one of the + /// word's sounds-like definitions: `"{sounds_like_string}": "Numbers are not allowed in sounds-like. You can + /// try for example '{suggested_string}'."`. /// [JsonProperty("element", NullValueHandling = NullValueHandling.Ignore)] public string Element { get; set; } diff --git a/Scripts/Services/SpeechToText/V1/SpeechToTextService.cs b/Scripts/Services/SpeechToText/V1/SpeechToTextService.cs index 06cf1e72e..76434aadd 100644 --- a/Scripts/Services/SpeechToText/V1/SpeechToTextService.cs +++ b/Scripts/Services/SpeechToText/V1/SpeechToTextService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.SpeechToText.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.SpeechToText.V1 public partial class SpeechToTextService : BaseService { private const string serviceId = "speech_to_text"; - private const string defaultUrl = "https://stream.watsonplatform.net/speech-to-text/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://stream.watsonplatform.net/speech-to-text/api"; #region VersionDate #endregion @@ -81,30 +53,20 @@ public bool DisableSslVerification /// SpeechToTextService constructor. /// - public SpeechToTextService() : base(serviceId) - { - - } + public SpeechToTextService() : this(ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// SpeechToTextService constructor. /// - /// The service credentials. - public SpeechToTextService(Credentials credentials) : base(credentials, serviceId) + /// The service authenticator. + public SpeechToTextService(Authenticator authenticator) : base(authenticator, serviceId) { - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; + Authenticator = authenticator; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the SpeechToText service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -146,7 +108,7 @@ public bool ListModels(Callback callback) req.OnResponse = OnListModelsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/models"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/models", GetServiceUrl()); if (connector == null) { return false; @@ -221,7 +183,7 @@ public bool GetModel(Callback callback, string modelId) req.OnResponse = OnGetModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/models/{0}", modelId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/models/{0}", modelId), GetServiceUrl()); if (connector == null) { return false; @@ -334,6 +296,8 @@ private void OnGetModelResponse(RESTConnector.Request req, RESTConnector.Respons /// /// The callback function that is invoked when the operation completes. /// The audio to transcribe. + /// The format (MIME type) of the audio. For more information about specifying an + /// audio format, see **Audio formats (content types)** in the method description. (optional) /// The identifier of the model that is to be used for the recognition request. See /// [Languages and /// models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). (optional, @@ -430,9 +394,9 @@ private void OnGetModelResponse(RESTConnector.Request req, RESTConnector.Respons /// `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify /// `false` for the parameter. /// - /// **Note:** Applies to US English, Japanese, and Spanish transcription only. To determine whether a language - /// model supports speaker labels, you can also use the **Get a model** method and check that the attribute - /// `speaker_labels` is set to `true`. + /// **Note:** Applies to US English, Japanese, and Spanish (both broadband and narrowband models) and UK English + /// (narrowband model) transcription only. To determine whether a language model supports speaker labels, you + /// can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. /// /// See [Speaker /// labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). @@ -465,10 +429,8 @@ private void OnGetModelResponse(RESTConnector.Request req, RESTConnector.Respons /// If `true`, requests detailed information about the signal characteristics of the /// input audio. The service returns audio metrics with the final transcription results. By default, the service /// returns no audio metrics. (optional, default to false) - /// The format (MIME type) of the audio. For more information about specifying an - /// audio format, see **Audio formats (content types)** in the method description. (optional) /// SpeechRecognitionResults - public bool Recognize(Callback callback, byte[] audio, string model = null, string languageCustomizationId = null, string acousticCustomizationId = null, string baseModelVersion = null, double? customizationWeight = null, long? inactivityTimeout = null, List keywords = null, float? keywordsThreshold = null, long? maxAlternatives = null, float? wordAlternativesThreshold = null, bool? wordConfidence = null, bool? timestamps = null, bool? profanityFilter = null, bool? smartFormatting = null, bool? speakerLabels = null, string customizationId = null, string grammarName = null, bool? redaction = null, string contentType = null, bool? audioMetrics = null) + public bool Recognize(Callback callback, byte[] audio, string contentType = null, string model = null, string languageCustomizationId = null, string acousticCustomizationId = null, string baseModelVersion = null, double? customizationWeight = null, long? inactivityTimeout = null, List keywords = null, float? keywordsThreshold = null, long? maxAlternatives = null, float? wordAlternativesThreshold = null, bool? wordConfidence = null, bool? timestamps = null, bool? profanityFilter = null, bool? smartFormatting = null, bool? speakerLabels = null, string customizationId = null, string grammarName = null, bool? redaction = null, bool? audioMetrics = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Recognize`"); @@ -580,7 +542,7 @@ public bool Recognize(Callback callback, byte[] audio, req.OnResponse = OnRecognizeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/recognize"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/recognize", GetServiceUrl()); if (connector == null) { return false; @@ -692,7 +654,7 @@ public bool RegisterCallback(Callback callback, string callbackU req.OnResponse = OnRegisterCallbackResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/register_callback"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/register_callback", GetServiceUrl()); if (connector == null) { return false; @@ -771,7 +733,7 @@ public bool UnregisterCallback(Callback callback, string callbackUrl) req.OnResponse = OnUnregisterCallbackResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/unregister_callback"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/unregister_callback", GetServiceUrl()); if (connector == null) { return false; @@ -892,6 +854,8 @@ private void OnUnregisterCallbackResponse(RESTConnector.Request req, RESTConnect /// /// The callback function that is invoked when the operation completes. /// The audio to transcribe. + /// The format (MIME type) of the audio. For more information about specifying an + /// audio format, see **Audio formats (content types)** in the method description. (optional) /// The identifier of the model that is to be used for the recognition request. See /// [Languages and /// models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-models#models). (optional, @@ -1019,9 +983,9 @@ private void OnUnregisterCallbackResponse(RESTConnector.Request req, RESTConnect /// `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify /// `false` for the parameter. /// - /// **Note:** Applies to US English, Japanese, and Spanish transcription only. To determine whether a language - /// model supports speaker labels, you can also use the **Get a model** method and check that the attribute - /// `speaker_labels` is set to `true`. + /// **Note:** Applies to US English, Japanese, and Spanish (both broadband and narrowband models) and UK English + /// (narrowband model) transcription only. To determine whether a language model supports speaker labels, you + /// can also use the **Get a model** method and check that the attribute `speaker_labels` is set to `true`. /// /// See [Speaker /// labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). @@ -1070,10 +1034,8 @@ private void OnUnregisterCallbackResponse(RESTConnector.Request req, RESTConnect /// If `true`, requests detailed information about the signal characteristics of the /// input audio. The service returns audio metrics with the final transcription results. By default, the service /// returns no audio metrics. (optional, default to false) - /// The format (MIME type) of the audio. For more information about specifying an - /// audio format, see **Audio formats (content types)** in the method description. (optional) /// RecognitionJob - public bool CreateJob(Callback callback, byte[] audio, string model = null, string callbackUrl = null, string events = null, string userToken = null, long? resultsTtl = null, string languageCustomizationId = null, string acousticCustomizationId = null, string baseModelVersion = null, double? customizationWeight = null, long? inactivityTimeout = null, List keywords = null, float? keywordsThreshold = null, long? maxAlternatives = null, float? wordAlternativesThreshold = null, bool? wordConfidence = null, bool? timestamps = null, bool? profanityFilter = null, bool? smartFormatting = null, bool? speakerLabels = null, string customizationId = null, string grammarName = null, bool? redaction = null, string contentType = null, bool? processingMetrics = null, float? processingMetricsInterval = null, bool? audioMetrics = null) + public bool CreateJob(Callback callback, byte[] audio, string contentType = null, string model = null, string callbackUrl = null, string events = null, string userToken = null, long? resultsTtl = null, string languageCustomizationId = null, string acousticCustomizationId = null, string baseModelVersion = null, double? customizationWeight = null, long? inactivityTimeout = null, List keywords = null, float? keywordsThreshold = null, long? maxAlternatives = null, float? wordAlternativesThreshold = null, bool? wordConfidence = null, bool? timestamps = null, bool? profanityFilter = null, bool? smartFormatting = null, bool? speakerLabels = null, string customizationId = null, string grammarName = null, bool? redaction = null, bool? processingMetrics = null, float? processingMetricsInterval = null, bool? audioMetrics = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `CreateJob`"); @@ -1209,7 +1171,7 @@ public bool CreateJob(Callback callback, byte[] audio, string mo req.OnResponse = OnCreateJobResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/recognitions"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/recognitions", GetServiceUrl()); if (connector == null) { return false; @@ -1284,7 +1246,7 @@ public bool CheckJobs(Callback callback) req.OnResponse = OnCheckJobsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/recognitions"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/recognitions", GetServiceUrl()); if (connector == null) { return false; @@ -1366,7 +1328,7 @@ public bool CheckJob(Callback callback, string id) req.OnResponse = OnCheckJobResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/recognitions/{0}", id)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/recognitions/{0}", id), GetServiceUrl()); if (connector == null) { return false; @@ -1443,7 +1405,7 @@ public bool DeleteJob(Callback callback, string id) req.OnResponse = OnDeleteJobResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/recognitions/{0}", id)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/recognitions/{0}", id), GetServiceUrl()); if (connector == null) { return false; @@ -1499,14 +1461,22 @@ private void OnDeleteJobResponse(RESTConnector.Request req, RESTConnector.Respon /// for /// customization](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-customization#languageSupport). /// The dialect of the specified language that is to be used with the custom language - /// model. The parameter is meaningful only for Spanish models, for which the service creates a custom language - /// model that is suited for speech in one of the following dialects: - /// * `es-ES` for Castilian Spanish (the default) - /// * `es-LA` for Latin American Spanish - /// * `es-US` for North American (Mexican) Spanish - /// - /// A specified dialect must be valid for the base model. By default, the dialect matches the language of the - /// base model; for example, `en-US` for either of the US English language models. (optional) + /// model. For most languages, the dialect matches the language of the base model by default. For example, + /// `en-US` is used for either of the US English language models. + /// + /// For a Spanish language, the service creates a custom language model that is suited for speech in one of the + /// following dialects: + /// * `es-ES` for Castilian Spanish (`es-ES` models) + /// * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models) + /// * `es-US` for Mexican (North American) Spanish (`es-MX` models) + /// + /// The parameter is meaningful only for Spanish models, for which you can always safely omit the parameter to + /// have the service create the correct mapping. + /// + /// If you specify the `dialect` parameter for non-Spanish language models, its value must match the language of + /// the base model. If you specify the `dialect` for Spanish language models, its value must match one of the + /// defined mappings as indicated (`es-ES`, `es-LA`, or `es-MX`). All dialect values are case-insensitive. + /// (optional) /// A description of the new custom language model. Use a localized description that /// matches the language of the custom model. (optional) /// LanguageModel @@ -1554,7 +1524,7 @@ public bool CreateLanguageModel(Callback callback, string name, s req.OnResponse = OnCreateLanguageModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/customizations"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/customizations", GetServiceUrl()); if (connector == null) { return false; @@ -1634,7 +1604,7 @@ public bool ListLanguageModels(Callback callback, string languag req.OnResponse = OnListLanguageModelsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/customizations"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/customizations", GetServiceUrl()); if (connector == null) { return false; @@ -1710,7 +1680,7 @@ public bool GetLanguageModel(Callback callback, string customizat req.OnResponse = OnGetLanguageModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -1787,7 +1757,7 @@ public bool DeleteLanguageModel(Callback callback, string customizationI req.OnResponse = OnDeleteLanguageModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -1876,15 +1846,15 @@ private void OnDeleteLanguageModelResponse(RESTConnector.Request req, RESTConnec /// /// The value that you assign is used for all recognition requests that use the model. You can override it for /// any recognition request by specifying a customization weight for that request. (optional) - /// Object - public bool TrainLanguageModel(Callback callback, string customizationId, string wordTypeToAdd = null, double? customizationWeight = null) + /// TrainingResponse + public bool TrainLanguageModel(Callback callback, string customizationId, string wordTypeToAdd = null, double? customizationWeight = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `TrainLanguageModel`"); if (string.IsNullOrEmpty(customizationId)) throw new ArgumentNullException("`customizationId` is required for `TrainLanguageModel`"); - RequestObject req = new RequestObject + RequestObject req = new RequestObject { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, @@ -1914,7 +1884,7 @@ public bool TrainLanguageModel(Callback callback, string customizationId req.OnResponse = OnTrainLanguageModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/train", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/train", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -1925,7 +1895,7 @@ public bool TrainLanguageModel(Callback callback, string customizationId private void OnTrainLanguageModelResponse(RESTConnector.Request req, RESTConnector.Response resp) { - DetailedResponse response = new DetailedResponse(); + DetailedResponse response = new DetailedResponse(); foreach (KeyValuePair kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); @@ -1935,7 +1905,7 @@ private void OnTrainLanguageModelResponse(RESTConnector.Request req, RESTConnect try { string json = Encoding.UTF8.GetString(resp.Data); - response.Result = JsonConvert.DeserializeObject(json); + response.Result = JsonConvert.DeserializeObject(json); response.Response = json; } catch (Exception e) @@ -1944,8 +1914,8 @@ private void OnTrainLanguageModelResponse(RESTConnector.Request req, RESTConnect resp.Success = false; } - if (((RequestObject)req).Callback != null) - ((RequestObject)req).Callback(response, resp.Error); + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); } /// /// Reset a custom language model. @@ -1992,7 +1962,7 @@ public bool ResetLanguageModel(Callback callback, string customizationId req.OnResponse = OnResetLanguageModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/reset", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/reset", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -2078,7 +2048,7 @@ public bool UpgradeLanguageModel(Callback callback, string customization req.OnResponse = OnUpgradeLanguageModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/upgrade_model", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/upgrade_model", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -2155,7 +2125,7 @@ public bool ListCorpora(Callback callback, string customizationId) req.OnResponse = OnListCorporaResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/corpora", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/corpora", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -2301,7 +2271,7 @@ public bool AddCorpus(Callback callback, string customizationId, string req.OnResponse = OnAddCorpusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/corpora/{1}", customizationId, corpusName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/corpora/{1}", customizationId, corpusName), GetServiceUrl()); if (connector == null) { return false; @@ -2381,7 +2351,7 @@ public bool GetCorpus(Callback callback, string customizationId, string req.OnResponse = OnGetCorpusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/corpora/{1}", customizationId, corpusName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/corpora/{1}", customizationId, corpusName), GetServiceUrl()); if (connector == null) { return false; @@ -2464,7 +2434,7 @@ public bool DeleteCorpus(Callback callback, string customizationId, stri req.OnResponse = OnDeleteCorpusResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/corpora/{1}", customizationId, corpusName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/corpora/{1}", customizationId, corpusName), GetServiceUrl()); if (connector == null) { return false; @@ -2563,7 +2533,7 @@ public bool ListWords(Callback callback, string customizationId, string w req.OnResponse = OnListWordsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -2690,7 +2660,7 @@ public bool AddWords(Callback callback, string customizationId, List callback, string customizationId, string wo req.OnResponse = OnAddWordResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words/{1}", customizationId, wordName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words/{1}", customizationId, wordName), GetServiceUrl()); if (connector == null) { return false; @@ -2907,7 +2877,7 @@ public bool GetWord(Callback callback, string customizationId, string word req.OnResponse = OnGetWordResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words/{1}", customizationId, wordName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words/{1}", customizationId, wordName), GetServiceUrl()); if (connector == null) { return false; @@ -2992,7 +2962,7 @@ public bool DeleteWord(Callback callback, string customizationId, string req.OnResponse = OnDeleteWordResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words/{1}", customizationId, wordName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words/{1}", customizationId, wordName), GetServiceUrl()); if (connector == null) { return false; @@ -3069,7 +3039,7 @@ public bool ListGrammars(Callback callback, string customizationId) req.OnResponse = OnListGrammarsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/grammars", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/grammars", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -3215,7 +3185,7 @@ public bool AddGrammar(Callback callback, string customizationId, string req.OnResponse = OnAddGrammarResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/grammars/{1}", customizationId, grammarName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/grammars/{1}", customizationId, grammarName), GetServiceUrl()); if (connector == null) { return false; @@ -3295,7 +3265,7 @@ public bool GetGrammar(Callback callback, string customizationId, strin req.OnResponse = OnGetGrammarResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/grammars/{1}", customizationId, grammarName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/grammars/{1}", customizationId, grammarName), GetServiceUrl()); if (connector == null) { return false; @@ -3378,7 +3348,7 @@ public bool DeleteGrammar(Callback callback, string customizationId, str req.OnResponse = OnDeleteGrammarResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/grammars/{1}", customizationId, grammarName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/grammars/{1}", customizationId, grammarName), GetServiceUrl()); if (connector == null) { return false; @@ -3476,7 +3446,7 @@ public bool CreateAcousticModel(Callback callback, string name, s req.OnResponse = OnCreateAcousticModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/acoustic_customizations"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/acoustic_customizations", GetServiceUrl()); if (connector == null) { return false; @@ -3556,7 +3526,7 @@ public bool ListAcousticModels(Callback callback, string languag req.OnResponse = OnListAcousticModelsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/acoustic_customizations"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/acoustic_customizations", GetServiceUrl()); if (connector == null) { return false; @@ -3632,7 +3602,7 @@ public bool GetAcousticModel(Callback callback, string customizat req.OnResponse = OnGetAcousticModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -3709,7 +3679,7 @@ public bool DeleteAcousticModel(Callback callback, string customizationI req.OnResponse = OnDeleteAcousticModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -3798,15 +3768,15 @@ private void OnDeleteAcousticModelResponse(RESTConnector.Request req, RESTConnec /// of the audio resources. The custom language model must be based on the same version of the same base model /// as the custom acoustic model. The credentials specified with the request must own both custom models. /// (optional) - /// Object - public bool TrainAcousticModel(Callback callback, string customizationId, string customLanguageModelId = null) + /// TrainingResponse + public bool TrainAcousticModel(Callback callback, string customizationId, string customLanguageModelId = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `TrainAcousticModel`"); if (string.IsNullOrEmpty(customizationId)) throw new ArgumentNullException("`customizationId` is required for `TrainAcousticModel`"); - RequestObject req = new RequestObject + RequestObject req = new RequestObject { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, @@ -3832,7 +3802,7 @@ public bool TrainAcousticModel(Callback callback, string customizationId req.OnResponse = OnTrainAcousticModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/train", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/train", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -3843,7 +3813,7 @@ public bool TrainAcousticModel(Callback callback, string customizationId private void OnTrainAcousticModelResponse(RESTConnector.Request req, RESTConnector.Response resp) { - DetailedResponse response = new DetailedResponse(); + DetailedResponse response = new DetailedResponse(); foreach (KeyValuePair kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); @@ -3853,7 +3823,7 @@ private void OnTrainAcousticModelResponse(RESTConnector.Request req, RESTConnect try { string json = Encoding.UTF8.GetString(resp.Data); - response.Result = JsonConvert.DeserializeObject(json); + response.Result = JsonConvert.DeserializeObject(json); response.Response = json; } catch (Exception e) @@ -3862,8 +3832,8 @@ private void OnTrainAcousticModelResponse(RESTConnector.Request req, RESTConnect resp.Success = false; } - if (((RequestObject)req).Callback != null) - ((RequestObject)req).Callback(response, resp.Error); + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); } /// /// Reset a custom acoustic model. @@ -3912,7 +3882,7 @@ public bool ResetAcousticModel(Callback callback, string customizationId req.OnResponse = OnResetAcousticModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/reset", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/reset", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -4023,7 +3993,7 @@ public bool UpgradeAcousticModel(Callback callback, string customization req.OnResponse = OnUpgradeAcousticModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/upgrade_model", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/upgrade_model", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -4102,7 +4072,7 @@ public bool ListAudio(Callback callback, string customizationId) req.OnResponse = OnListAudioResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/audio", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/audio", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -4243,6 +4213,11 @@ private void OnListAudioResponse(RESTConnector.Request req, RESTConnector.Respon /// individual audio file or an archive file. /// /// With the `curl` command, use the `--data-binary` option to upload the file for the request. + /// For an audio-type resource, the format (MIME type) of the audio. For more + /// information, see **Content types for audio-type resources** in the method description. + /// + /// For an archive-type resource, the media type of the archive file. For more information, see **Content types + /// for archive-type resources** in the method description. (optional) /// **For an archive-type resource,** specify the format of the audio files /// that are contained in the archive file if they are of type `audio/alaw`, `audio/basic`, `audio/l16`, or /// `audio/mulaw`. Include the `rate`, `channels`, and `endianness` parameters where necessary. In this case, @@ -4259,13 +4234,8 @@ private void OnListAudioResponse(RESTConnector.Request req, RESTConnector.Respon /// with the same name. If `false`, the request fails if an audio resource with the same name already exists. /// The parameter has no effect if an audio resource with the same name does not already exist. (optional, /// default to false) - /// For an audio-type resource, the format (MIME type) of the audio. For more - /// information, see **Content types for audio-type resources** in the method description. - /// - /// For an archive-type resource, the media type of the archive file. For more information, see **Content types - /// for archive-type resources** in the method description. (optional) /// object - public bool AddAudio(Callback callback, string customizationId, string audioName, byte[] audioResource, string containedContentType = null, bool? allowOverwrite = null, string contentType = null) + public bool AddAudio(Callback callback, string customizationId, string audioName, byte[] audioResource, string contentType = null, string containedContentType = null, bool? allowOverwrite = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `AddAudio`"); @@ -4301,20 +4271,20 @@ public bool AddAudio(Callback callback, string customizationId, string a } req.Headers["Accept"] = "application/json"; - if (!string.IsNullOrEmpty(containedContentType)) + if (!string.IsNullOrEmpty(contentType)) { - req.Headers["Contained-Content-Type"] = containedContentType; + req.Headers["Content-Type"] = contentType; } - if (!string.IsNullOrEmpty(contentType)) + if (!string.IsNullOrEmpty(containedContentType)) { - req.Headers["Content-Type"] = contentType; + req.Headers["Contained-Content-Type"] = containedContentType; } req.Send = audioResource; req.OnResponse = OnAddAudioResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/audio/{1}", customizationId, audioName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/audio/{1}", customizationId, audioName), GetServiceUrl()); if (connector == null) { return false; @@ -4407,7 +4377,7 @@ public bool GetAudio(Callback callback, string customizationId, st req.OnResponse = OnGetAudioResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/audio/{1}", customizationId, audioName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/audio/{1}", customizationId, audioName), GetServiceUrl()); if (connector == null) { return false; @@ -4492,7 +4462,7 @@ public bool DeleteAudio(Callback callback, string customizationId, strin req.OnResponse = OnDeleteAudioResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/acoustic_customizations/{0}/audio/{1}", customizationId, audioName)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/acoustic_customizations/{0}/audio/{1}", customizationId, audioName), GetServiceUrl()); if (connector == null) { return false; @@ -4575,7 +4545,7 @@ public bool DeleteUserData(Callback callback, string customerId) req.OnResponse = OnDeleteUserDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/user_data"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/user_data", GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/SpeechToText/V1/SpeechToTextServiceExtension.cs b/Scripts/Services/SpeechToText/V1/SpeechToTextServiceExtension.cs index 27e443133..8efd8694b 100644 --- a/Scripts/Services/SpeechToText/V1/SpeechToTextServiceExtension.cs +++ b/Scripts/Services/SpeechToText/V1/SpeechToTextServiceExtension.cs @@ -16,6 +16,7 @@ */ using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.DataTypes; using IBM.Cloud.SDK.Utilities; @@ -107,8 +108,8 @@ public partial class SpeechToTextService : BaseService private bool _streamMultipart = false; // If true sets `Transfer-Encoding` header of multipart request to `chunked`. private float _silenceDuration = 0.0f; private float _silenceCutoff = 1.0f; - - private Credentials _credentials = null; + + private Authenticator _authenticator = null; private string _url = "https://stream.watsonplatform.net/speech-to-text/api"; #endregion @@ -292,7 +293,7 @@ public bool StartListening(OnRecognize callback, OnRecognizeSpeaker speakerLabel return false; if (!CreateListenConnector()) return false; - + Dictionary customHeaders = new Dictionary(); foreach (KeyValuePair kvp in customRequestHeaders) { @@ -445,7 +446,8 @@ private bool CreateListenConnector() parsedParams += string.Format("&{0}={1}", kvp.Key, kvp.Value); } - _listenSocket = WSConnector.CreateConnector(Credentials, "/v1/recognize", "?model=" + UnityWebRequest.EscapeURL(_recognizeModel) + parsedParams); + _listenSocket = WSConnector.CreateConnector(Authenticator, "/v1/recognize", "?model=" + UnityWebRequest.EscapeURL(_recognizeModel) + parsedParams, serviceUrl); + Log.Debug("SpeechToText.CreateListenConnector()", "Created listen socket. Model: {0}, parsedParams: {1}", UnityWebRequest.EscapeURL(_recognizeModel), parsedParams); _listenSocket.DisableSslVerification = DisableSslVerification; if (_listenSocket == null) { @@ -557,7 +559,6 @@ private void OnListenMessage(WSConnector.Message msg) if (msg is WSConnector.TextMessage) { WSConnector.TextMessage tm = (WSConnector.TextMessage)msg; - IDictionary json = Json.Deserialize(tm.Text) as IDictionary; if (json != null) { diff --git a/Scripts/Services/TextToSpeech/V1/TextToSpeechService.cs b/Scripts/Services/TextToSpeech/V1/TextToSpeechService.cs index 053151fc7..14f2e1a4e 100644 --- a/Scripts/Services/TextToSpeech/V1/TextToSpeechService.cs +++ b/Scripts/Services/TextToSpeech/V1/TextToSpeechService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.TextToSpeech.V1.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.TextToSpeech.V1 public partial class TextToSpeechService : BaseService { private const string serviceId = "text_to_speech"; - private const string defaultUrl = "https://stream.watsonplatform.net/text-to-speech/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://stream.watsonplatform.net/text-to-speech/api"; #region VersionDate #endregion @@ -81,30 +53,20 @@ public bool DisableSslVerification /// TextToSpeechService constructor. /// - public TextToSpeechService() : base(serviceId) - { - - } + public TextToSpeechService() : this(ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// TextToSpeechService constructor. /// - /// The service credentials. - public TextToSpeechService(Credentials credentials) : base(credentials, serviceId) + /// The service authenticator. + public TextToSpeechService(Authenticator authenticator) : base(authenticator, serviceId) { - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; + Authenticator = authenticator; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the TextToSpeech service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -147,7 +109,7 @@ public bool ListVoices(Callback callback) req.OnResponse = OnListVoicesResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/voices"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/voices", GetServiceUrl()); if (connector == null) { return false; @@ -231,7 +193,7 @@ public bool GetVoice(Callback callback, string voice, string customizatio req.OnResponse = OnGetVoiceResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/voices/{0}", voice)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/voices/{0}", voice), GetServiceUrl()); if (connector == null) { return false; @@ -283,55 +245,33 @@ private void OnGetVoiceResponse(RESTConnector.Request req, RESTConnector.Respons /// 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. + /// 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`. /// /// Use the `Accept` header or the `accept` parameter to specify the requested format of the response audio. If /// you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec /// (`audio/ogg;codecs=opus`). The service always returns single-channel audio. - /// * `audio/basic` - /// - /// The service returns audio with a sampling rate of 8000 Hz. - /// * `audio/flac` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. - /// * `audio/l16` - /// - /// You must specify the `rate` of the audio. You can optionally specify the `endianness` of the audio. The - /// default endianness is `little-endian`. - /// * `audio/mp3` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. - /// * `audio/mpeg` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. - /// * `audio/mulaw` - /// - /// You must specify the `rate` of the audio. - /// * `audio/ogg` - /// - /// The service returns the audio in the `vorbis` codec. You can optionally specify the `rate` of the audio. - /// The default sampling rate is 22,050 Hz. - /// * `audio/ogg;codecs=opus` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. - /// * `audio/ogg;codecs=vorbis` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. - /// * `audio/wav` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. - /// * `audio/webm` - /// - /// The service returns the audio in the `opus` codec. The service returns audio with a sampling rate of - /// 48,000 Hz. - /// * `audio/webm;codecs=opus` - /// - /// The service returns audio with a sampling rate of 48,000 Hz. - /// * `audio/webm;codecs=vorbis` - /// - /// You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. + /// * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. + /// * `audio/flac` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. + /// * `audio/l16` - You must specify the `rate` of the audio. You can optionally specify the `endianness` of the + /// audio. The default endianness is `little-endian`. + /// * `audio/mp3` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. + /// * `audio/mpeg` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. + /// * `audio/mulaw` - You must specify the `rate` of the audio. + /// * `audio/ogg` - The service returns the audio in the `vorbis` codec. You can optionally specify the `rate` + /// of the audio. The default sampling rate is 22,050 Hz. + /// * `audio/ogg;codecs=opus` - You can optionally specify the `rate` of the audio. Only the following values + /// are valid sampling rates: `48000`, `24000`, `16000`, `12000`, or `8000`. If you specify a value other than + /// one of these, the service returns an error. The default sampling rate is 48,000 Hz. + /// * `audio/ogg;codecs=vorbis` - You can optionally specify the `rate` of the audio. The default sampling rate + /// is 22,050 Hz. + /// * `audio/wav` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. + /// * `audio/webm` - The service returns the audio in the `opus` codec. The service returns audio with a + /// sampling rate of 48,000 Hz. + /// * `audio/webm;codecs=opus` - The service returns audio with a sampling rate of 48,000 Hz. + /// * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. The default sampling rate + /// is 22,050 Hz. /// /// For more information about specifying an audio format, including additional details about some of the /// formats, see [Audio @@ -348,17 +288,17 @@ private void OnGetVoiceResponse(RESTConnector.Request req, RESTConnector.Respons /// /// The callback function that is invoked when the operation completes. /// The text to synthesize. + /// The requested format (MIME type) of the audio. You can use the `Accept` header or the + /// `accept` parameter to specify the audio format. For more information about specifying an audio format, see + /// **Audio formats (accept types)** in the method description. (optional, default to + /// audio/ogg;codecs=opus) /// The voice to use for synthesis. (optional, default to en-US_MichaelVoice) /// The customization ID (GUID) of a custom voice model to use for the synthesis. /// If a custom voice model is specified, it is guaranteed to work only if it matches the language of the /// indicated voice. You must make the request with credentials for the instance of the service that owns the /// custom model. Omit the parameter to use the specified voice with no customization. (optional) - /// The requested format (MIME type) of the audio. You can use the `Accept` header or the - /// `accept` parameter to specify the audio format. For more information about specifying an audio format, see - /// **Audio formats (accept types)** in the method description. (optional, default to - /// audio/ogg;codecs=opus) /// byte[] - public bool Synthesize(Callback callback, string text, string voice = null, string customizationId = null, string accept = null) + public bool Synthesize(Callback callback, string text, string accept = null, string voice = null, string customizationId = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Synthesize`"); @@ -407,7 +347,7 @@ public bool Synthesize(Callback callback, string text, string voice = nu req.OnResponse = OnSynthesizeResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/synthesize"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/synthesize", GetServiceUrl()); if (connector == null) { return false; @@ -501,7 +441,7 @@ public bool GetPronunciation(Callback callback, string text, stri req.OnResponse = OnGetPronunciationResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/pronunciation"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/pronunciation", GetServiceUrl()); if (connector == null) { return false; @@ -593,7 +533,7 @@ public bool CreateVoiceModel(Callback callback, string name, string req.OnResponse = OnCreateVoiceModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/customizations"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/customizations", GetServiceUrl()); if (connector == null) { return false; @@ -675,7 +615,7 @@ public bool ListVoiceModels(Callback callback, string language = nu req.OnResponse = OnListVoiceModelsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/customizations"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/customizations", GetServiceUrl()); if (connector == null) { return false; @@ -787,7 +727,7 @@ public bool UpdateVoiceModel(Callback callback, string customizationId, req.OnResponse = OnUpdateVoiceModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -865,7 +805,7 @@ public bool GetVoiceModel(Callback callback, string customizationId) req.OnResponse = OnGetVoiceModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -942,7 +882,7 @@ public bool DeleteVoiceModel(Callback callback, string customizationId) req.OnResponse = OnDeleteVoiceModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -1052,7 +992,7 @@ public bool AddWords(Callback callback, string customizationId, List callback, string customizationId) req.OnResponse = OnListWordsResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words", customizationId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words", customizationId), GetServiceUrl()); if (connector == null) { return false; @@ -1247,7 +1187,7 @@ public bool AddWord(Callback callback, string customizationId, string wo req.OnResponse = OnAddWordResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words/{1}", customizationId, word)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words/{1}", customizationId, word), GetServiceUrl()); if (connector == null) { return false; @@ -1328,7 +1268,7 @@ public bool GetWord(Callback callback, string customizationId, stri req.OnResponse = OnGetWordResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words/{1}", customizationId, word)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words/{1}", customizationId, word), GetServiceUrl()); if (connector == null) { return false; @@ -1408,7 +1348,7 @@ public bool DeleteWord(Callback callback, string customizationId, string req.OnResponse = OnDeleteWordResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v1/customizations/{0}/words/{1}", customizationId, word)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v1/customizations/{0}/words/{1}", customizationId, word), GetServiceUrl()); if (connector == null) { return false; @@ -1491,7 +1431,7 @@ public bool DeleteUserData(Callback callback, string customerId) req.OnResponse = OnDeleteUserDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v1/user_data"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v1/user_data", GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/ToneAnalyzer/V3/ToneAnalyzerService.cs b/Scripts/Services/ToneAnalyzer/V3/ToneAnalyzerService.cs index 78c3fab42..e1a4f41e4 100644 --- a/Scripts/Services/ToneAnalyzer/V3/ToneAnalyzerService.cs +++ b/Scripts/Services/ToneAnalyzer/V3/ToneAnalyzerService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.ToneAnalyzer.V3.Model; @@ -31,36 +32,7 @@ namespace IBM.Watson.ToneAnalyzer.V3 public partial class ToneAnalyzerService : BaseService { private const string serviceId = "tone_analyzer"; - private const string defaultUrl = "https://gateway.watsonplatform.net/tone-analyzer/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/tone-analyzer/api"; #region VersionDate private string versionDate; @@ -90,18 +62,16 @@ public bool DisableSslVerification /// ToneAnalyzerService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public ToneAnalyzerService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public ToneAnalyzerService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// ToneAnalyzerService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public ToneAnalyzerService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public ToneAnalyzerService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of ToneAnalyzerService"); @@ -111,18 +81,10 @@ public ToneAnalyzerService(string versionDate, Credentials credentials) : base(v VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the ToneAnalyzer service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -149,6 +111,8 @@ public ToneAnalyzerService(string versionDate, Credentials credentials) : base(v /// The callback function that is invoked when the operation completes. /// JSON, plain text, or HTML input that contains the content to be analyzed. For JSON /// input, provide an object of type `ToneInput`. + /// The type of the input. A character encoding can be specified by including a + /// `charset` parameter. For example, 'text/plain;charset=utf-8'. (optional) /// Indicates whether the service is to return an analysis of each individual sentence /// in addition to its analysis of the full document. If `true` (the default), the service returns results for /// each sentence. (optional, default to true) @@ -168,10 +132,8 @@ public ToneAnalyzerService(string versionDate, Credentials credentials) : base(v /// The desired language of the response. For two-character arguments, regional /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can use /// different languages for **Content-Language** and **Accept-Language**. (optional, default to en) - /// The type of the input. A character encoding can be specified by including a - /// `charset` parameter. For example, 'text/plain;charset=utf-8'. (optional) /// ToneAnalysis - public bool Tone(Callback callback, ToneInput toneInput, bool? sentences = null, List tones = null, string contentLanguage = null, string acceptLanguage = null, string contentType = null) + public bool Tone(Callback callback, ToneInput toneInput, string contentType = null, bool? sentences = null, List tones = null, string contentLanguage = null, string acceptLanguage = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Tone`"); @@ -208,6 +170,11 @@ public bool Tone(Callback callback, ToneInput toneInput, bool? sen } req.Headers["Accept"] = "application/json"; + if (!string.IsNullOrEmpty(contentType)) + { + req.Headers["Content-Type"] = contentType; + } + if (!string.IsNullOrEmpty(contentLanguage)) { req.Headers["Content-Language"] = contentLanguage; @@ -217,16 +184,11 @@ public bool Tone(Callback callback, ToneInput toneInput, bool? sen { req.Headers["Accept-Language"] = acceptLanguage; } - - if (!string.IsNullOrEmpty(contentType)) - { - req.Headers["Content-Type"] = contentType; - } req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(toneInput)); req.OnResponse = OnToneResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/tone"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/tone", GetServiceUrl()); if (connector == null) { return false; @@ -335,7 +297,7 @@ public bool ToneChat(Callback callback, List utter req.OnResponse = OnToneChatResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/tone_chat"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/tone_chat", GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/VisualRecognition/V3/Model/ClassResult.cs b/Scripts/Services/VisualRecognition/V3/Model/ClassResult.cs index 43c657afc..d9279203e 100644 --- a/Scripts/Services/VisualRecognition/V3/Model/ClassResult.cs +++ b/Scripts/Services/VisualRecognition/V3/Model/ClassResult.cs @@ -33,7 +33,7 @@ public class ClassResult /// or when there is no translation for the class name. /// [JsonProperty("class", NullValueHandling = NullValueHandling.Ignore)] - public string ClassName { get; set; } + public string _Class { get; set; } /// /// Confidence score for the property in the range of 0 to 1. A higher score indicates greater likelihood that /// the class is depicted in the image. The default threshold for returning scores from a classifier is 0.5. diff --git a/Scripts/Services/VisualRecognition/V3/Model/FaceGender.cs b/Scripts/Services/VisualRecognition/V3/Model/FaceGender.cs index 4dc9dbd57..5f70d42c2 100644 --- a/Scripts/Services/VisualRecognition/V3/Model/FaceGender.cs +++ b/Scripts/Services/VisualRecognition/V3/Model/FaceGender.cs @@ -30,7 +30,7 @@ public class FaceGender [JsonProperty("gender", NullValueHandling = NullValueHandling.Ignore)] public string Gender { get; set; } /// - /// The word for \"male\" or \"female\" in the language defined by the **Accept-Language** request header. + /// The word for "male" or "female" in the language defined by the **Accept-Language** request header. /// [JsonProperty("gender_label", NullValueHandling = NullValueHandling.Ignore)] public string GenderLabel { get; set; } diff --git a/Scripts/Services/VisualRecognition/V3/Model/ModelClass.cs b/Scripts/Services/VisualRecognition/V3/Model/ModelClass.cs index 18e91f0f8..40c00d40c 100644 --- a/Scripts/Services/VisualRecognition/V3/Model/ModelClass.cs +++ b/Scripts/Services/VisualRecognition/V3/Model/ModelClass.cs @@ -28,6 +28,6 @@ public class ModelClass /// The name of the class. /// [JsonProperty("class", NullValueHandling = NullValueHandling.Ignore)] - public string ClassName { get; set; } + public string _Class { get; set; } } } diff --git a/Scripts/Services/VisualRecognition/V3/VisualRecognitionService.cs b/Scripts/Services/VisualRecognition/V3/VisualRecognitionService.cs index e7d77f02a..5a0bfa4b2 100644 --- a/Scripts/Services/VisualRecognition/V3/VisualRecognitionService.cs +++ b/Scripts/Services/VisualRecognition/V3/VisualRecognitionService.cs @@ -18,6 +18,7 @@ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.VisualRecognition.V3.Model; @@ -30,36 +31,7 @@ namespace IBM.Watson.VisualRecognition.V3 public partial class VisualRecognitionService : BaseService { private const string serviceId = "visual_recognition"; - private const string defaultUrl = "https://gateway.watsonplatform.net/visual-recognition/api"; - - #region Credentials - /// - /// Gets and sets the credentials of the service. Replace the default endpoint if endpoint is defined. - /// - public Credentials Credentials - { - get { return credentials; } - set - { - credentials = value; - if (!string.IsNullOrEmpty(credentials.Url)) - { - Url = credentials.Url; - } - } - } - #endregion - - #region Url - /// - /// Gets and sets the endpoint URL for the service. - /// - public string Url - { - get { return url; } - set { url = value; } - } - #endregion + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/visual-recognition/api"; #region VersionDate private string versionDate; @@ -89,18 +61,16 @@ public bool DisableSslVerification /// VisualRecognitionService constructor. /// /// The service version date in `yyyy-mm-dd` format. - public VisualRecognitionService(string versionDate) : base(versionDate, serviceId) - { - VersionDate = versionDate; - } + public VisualRecognitionService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} /// /// VisualRecognitionService constructor. /// /// The service version date in `yyyy-mm-dd` format. - /// The service credentials. - public VisualRecognitionService(string versionDate, Credentials credentials) : base(versionDate, credentials, serviceId) + /// The service authenticator. + public VisualRecognitionService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) { + Authenticator = authenticator; if (string.IsNullOrEmpty(versionDate)) { throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of VisualRecognitionService"); @@ -110,18 +80,10 @@ public VisualRecognitionService(string versionDate, Credentials credentials) : b VersionDate = versionDate; } - if (credentials.HasCredentials() || credentials.HasTokenData()) - { - Credentials = credentials; - if (string.IsNullOrEmpty(credentials.Url)) - { - credentials.Url = defaultUrl; - } - } - else + if (string.IsNullOrEmpty(GetServiceUrl())) { - throw new IBMException("Please provide a username and password or authorization token to use the VisualRecognition service. For more information, see https://github.com/watson-developer-cloud/unity-sdk/#configuring-your-service-credentials"); + SetServiceUrl(defaultServiceUrl); } } @@ -213,7 +175,7 @@ public bool Classify(Callback callback, System.IO.MemoryStream req.OnResponse = OnClassifyResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/classify"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/classify", GetServiceUrl()); if (connector == null) { return false; @@ -247,118 +209,19 @@ private void OnClassifyResponse(RESTConnector.Request req, RESTConnector.Respons ((RequestObject)req).Callback(response, resp.Error); } /// - /// Detect faces in images. - /// - /// **Important:** On April 2, 2018, the identity information in the response to calls to the Face model was - /// removed. The identity information refers to the `name` of the person, `score`, and `type_hierarchy` - /// knowledge graph. For details about the enhanced Face model, see the [Release - /// notes](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-release-notes#2april2018). - /// - /// Analyze and get data about faces in images. Responses can include estimated age and gender. This feature - /// uses a built-in model, so no training is necessary. The **Detect faces** method does not support general - /// biometric facial recognition. - /// - /// Supported image formats include .gif, .jpg, .png, and .tif. The maximum image size is 10 MB. The minimum - /// recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at - /// least 224 x 224 pixels. - /// - /// The callback function that is invoked when the operation completes. - /// An image file (gif, .jpg, .png, .tif.) or .zip file with images. Limit the .zip - /// file to 100 MB. You can include a maximum of 15 images in a request. - /// - /// Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes - /// UTF-8 encoding if it encounters non-ASCII characters. - /// - /// You can also include an image with the **url** parameter. (optional) - /// The filename for imagesFile. (optional) - /// The content type of imagesFile. (optional) - /// The URL of an image to analyze. Must be in .gif, .jpg, .png, or .tif format. The minimum - /// recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at - /// least 224 x 224 pixels. The maximum image size is 10 MB. Redirects are followed, so you can use a shortened - /// URL. - /// - /// You can also include images with the **images_file** parameter. (optional) - /// The desired language of parts of the response. See the response for details. - /// (optional, default to en) - /// DetectedFaces - public bool DetectFaces(Callback callback, System.IO.MemoryStream imagesFile = null, string imagesFilename = null, string imagesFileContentType = null, string url = null, string acceptLanguage = null) - { - if (callback == null) - throw new ArgumentNullException("`callback` is required for `DetectFaces`"); - - RequestObject req = new RequestObject - { - Callback = callback, - HttpMethod = UnityWebRequest.kHttpVerbPOST, - DisableSslVerification = DisableSslVerification - }; - - foreach (KeyValuePair kvp in customRequestHeaders) - { - req.Headers.Add(kvp.Key, kvp.Value); - } - - ClearCustomRequestHeaders(); - - foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V3", "DetectFaces")) - { - req.Headers.Add(kvp.Key, kvp.Value); - } - - req.Parameters["version"] = VersionDate; - req.Forms = new Dictionary(); - if (imagesFile != null) - { - req.Forms["images_file"] = new RESTConnector.Form(imagesFile, imagesFilename, imagesFileContentType); - } - if (!string.IsNullOrEmpty(url)) - { - req.Forms["url"] = new RESTConnector.Form(url); - } - - req.OnResponse = OnDetectFacesResponse; - - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/detect_faces"); - if (connector == null) - { - return false; - } - - return connector.Send(req); - } - - private void OnDetectFacesResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - DetailedResponse response = new DetailedResponse(); - foreach (KeyValuePair kvp in resp.Headers) - { - response.Headers.Add(kvp.Key, kvp.Value); - } - response.StatusCode = resp.HttpResponseCode; - - try - { - string json = Encoding.UTF8.GetString(resp.Data); - response.Result = JsonConvert.DeserializeObject(json); - response.Response = json; - } - catch (Exception e) - { - Log.Error("VisualRecognitionService.OnDetectFacesResponse()", "Exception: {0}", e.ToString()); - resp.Success = false; - } - - if (((RequestObject)req).Callback != null) - ((RequestObject)req).Callback(response, resp.Error); - } - /// /// Create a classifier. /// /// Train a new multi-faceted classifier on the uploaded image data. Create your custom classifier with positive - /// or negative examples. Include at least two sets of examples, either two positive example files or one - /// positive and one negative file. You can upload a maximum of 256 MB per call. + /// or negative example training images. Include at least two sets of examples, either two positive example + /// files or one positive and one negative file. You can upload a maximum of 256 MB per call. /// - /// Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier + /// **Tips when creating:** + /// + /// - If you set the **X-Watson-Learning-Opt-Out** header parameter to `true` when you create a classifier, the + /// example training images are not stored. Save your training images locally. For more information, see [Data + /// collection](#data-collection). + /// + /// - Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. /// /// The callback function that is invoked when the operation completes. @@ -431,7 +294,7 @@ public bool CreateClassifier(Callback callback, string name, Diction req.OnResponse = OnCreateClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/classifiers"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/classifiers", GetServiceUrl()); if (connector == null) { return false; @@ -503,7 +366,7 @@ public bool ListClassifiers(Callback callback, bool? verbose = null req.OnResponse = OnListClassifiersResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/classifiers"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/classifiers", GetServiceUrl()); if (connector == null) { return false; @@ -574,7 +437,7 @@ public bool GetClassifier(Callback callback, string classifierId) req.OnResponse = OnGetClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/classifiers/{0}", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/classifiers/{0}", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -618,9 +481,15 @@ private void OnGetClassifierResponse(RESTConnector.Request req, RESTConnector.Re /// Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier /// and class names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. /// - /// **Tip:** Don't make retraining calls on a classifier until the status is ready. When you submit retraining - /// requests in parallel, the last request overwrites the previous requests. The retrained property shows the - /// last time the classifier retraining finished. + /// **Tips about retraining:** + /// + /// - You can't update the classifier if the **X-Watson-Learning-Opt-Out** header parameter was set to `true` + /// when the classifier was created. Training images are not stored in that case. Instead, create another + /// classifier. For more information, see [Data collection](#data-collection). + /// + /// - Don't make retraining calls on a classifier until the status is ready. When you submit retraining requests + /// in parallel, the last request overwrites the previous requests. The `retrained` property shows the last time + /// the classifier retraining finished. /// /// The callback function that is invoked when the operation completes. /// The ID of the classifier. @@ -684,7 +553,7 @@ public bool UpdateClassifier(Callback callback, string classifierId, req.OnResponse = OnUpdateClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/classifiers/{0}", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/classifiers/{0}", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -753,7 +622,7 @@ public bool DeleteClassifier(Callback callback, string classifierId) req.OnResponse = OnDeleteClassifierResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/classifiers/{0}", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/classifiers/{0}", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -825,7 +694,7 @@ public bool GetCoreMlModel(Callback callback, string classifierId) req.OnResponse = OnGetCoreMlModelResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, string.Format("/v3/classifiers/{0}/core_ml_model", classifierId)); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v3/classifiers/{0}/core_ml_model", classifierId), GetServiceUrl()); if (connector == null) { return false; @@ -895,7 +764,7 @@ public bool DeleteUserData(Callback callback, string customerId) req.OnResponse = OnDeleteUserDataResponse; - RESTConnector connector = RESTConnector.GetConnector(Credentials, "/v3/user_data"); + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v3/user_data", GetServiceUrl()); if (connector == null) { return false; diff --git a/Scripts/Services/VisualRecognition/V4.meta b/Scripts/Services/VisualRecognition/V4.meta new file mode 100644 index 000000000..6eaae9942 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 97f2602322ffe41c79fc4d582ea3c20e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model.meta b/Scripts/Services/VisualRecognition/V4/Model.meta new file mode 100644 index 000000000..69ac7260f --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9c303c62f8964486da67eaaf010014f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/AnalyzeResponse.cs b/Scripts/Services/VisualRecognition/V4/Model/AnalyzeResponse.cs new file mode 100644 index 000000000..87c8546c6 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/AnalyzeResponse.cs @@ -0,0 +1,44 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Results for all images. + /// + public class AnalyzeResponse + { + /// + /// Analyzed images. + /// + [JsonProperty("images", NullValueHandling = NullValueHandling.Ignore)] + public List Images { get; set; } + /// + /// Information about what might cause less than optimal output. + /// + [JsonProperty("warnings", NullValueHandling = NullValueHandling.Ignore)] + public List Warnings { get; set; } + /// + /// A unique identifier of the request. Included only when an error or warning is returned. + /// + [JsonProperty("trace", NullValueHandling = NullValueHandling.Ignore)] + public string Trace { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/AnalyzeResponse.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/AnalyzeResponse.cs.meta new file mode 100644 index 000000000..c28d30cad --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/AnalyzeResponse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0dd805cb47c9433fac0c285480a96e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/Collection.cs b/Scripts/Services/VisualRecognition/V4/Model/Collection.cs new file mode 100644 index 000000000..75db0427e --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Collection.cs @@ -0,0 +1,64 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; +using System; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about a collection. + /// + public class Collection + { + /// + /// The identifier of the collection. + /// + [JsonProperty("collection_id", NullValueHandling = NullValueHandling.Ignore)] + public virtual string CollectionId { get; private set; } + /// + /// The name of the collection. + /// + [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] + public string Name { get; set; } + /// + /// The description of the collection. + /// + [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] + public string Description { get; set; } + /// + /// Date and time in Coordinated Universal Time (UTC) that the collection was created. + /// + [JsonProperty("created", NullValueHandling = NullValueHandling.Ignore)] + public virtual DateTime? Created { get; private set; } + /// + /// Date and time in Coordinated Universal Time (UTC) that the collection was most recently updated. + /// + [JsonProperty("updated", NullValueHandling = NullValueHandling.Ignore)] + public virtual DateTime? Updated { get; private set; } + /// + /// Number of images in the collection. + /// + [JsonProperty("image_count", NullValueHandling = NullValueHandling.Ignore)] + public virtual long? ImageCount { get; private set; } + /// + /// Training status information for the collection. + /// + [JsonProperty("training_status", NullValueHandling = NullValueHandling.Ignore)] + public virtual TrainingStatus TrainingStatus { get; private set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/Collection.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/Collection.cs.meta new file mode 100644 index 000000000..a6aa5feba --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Collection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d472723c9b5842ac8aad273020cf81b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/CollectionObjects.cs b/Scripts/Services/VisualRecognition/V4/Model/CollectionObjects.cs new file mode 100644 index 000000000..f5299bf6a --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/CollectionObjects.cs @@ -0,0 +1,39 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// The objects in a collection that are detected in an image. + /// + public class CollectionObjects + { + /// + /// The identifier of the collection. + /// + [JsonProperty("collection_id", NullValueHandling = NullValueHandling.Ignore)] + public string CollectionId { get; set; } + /// + /// The identified objects in a collection. + /// + [JsonProperty("objects", NullValueHandling = NullValueHandling.Ignore)] + public List Objects { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/CollectionObjects.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/CollectionObjects.cs.meta new file mode 100644 index 000000000..8463d7ba4 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/CollectionObjects.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 59805e22915c24058a103a1e2721e4d7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/CollectionsList.cs b/Scripts/Services/VisualRecognition/V4/Model/CollectionsList.cs new file mode 100644 index 000000000..8e25a6a1e --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/CollectionsList.cs @@ -0,0 +1,34 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// A container for the list of collections. + /// + public class CollectionsList + { + /// + /// The collections in this service instance. + /// + [JsonProperty("collections", NullValueHandling = NullValueHandling.Ignore)] + public List Collections { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/CollectionsList.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/CollectionsList.cs.meta new file mode 100644 index 000000000..4990a01db --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/CollectionsList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c21cc1fccd7744d148210633549ba786 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/DetectedObjects.cs b/Scripts/Services/VisualRecognition/V4/Model/DetectedObjects.cs new file mode 100644 index 000000000..d17bbf38c --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/DetectedObjects.cs @@ -0,0 +1,34 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Container for the list of collections that have objects detected in an image. + /// + public class DetectedObjects + { + /// + /// The collections with identified objects. + /// + [JsonProperty("collections", NullValueHandling = NullValueHandling.Ignore)] + public List Collections { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/DetectedObjects.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/DetectedObjects.cs.meta new file mode 100644 index 000000000..4c20aed3e --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/DetectedObjects.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d556e5a9f023476b9cee4e4b7f9c288 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/Error.cs b/Scripts/Services/VisualRecognition/V4/Model/Error.cs new file mode 100644 index 000000000..9d375127a --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Error.cs @@ -0,0 +1,77 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about an error. + /// + public class Error + { + /// + /// Identifier of the problem. + /// + public class CodeValue + { + /// + /// Constant INVALID_FIELD for invalid_field + /// + public const string INVALID_FIELD = "invalid_field"; + /// + /// Constant INVALID_HEADER for invalid_header + /// + public const string INVALID_HEADER = "invalid_header"; + /// + /// Constant INVALID_METHOD for invalid_method + /// + public const string INVALID_METHOD = "invalid_method"; + /// + /// Constant MISSING_FIELD for missing_field + /// + public const string MISSING_FIELD = "missing_field"; + /// + /// Constant SERVER_ERROR for server_error + /// + public const string SERVER_ERROR = "server_error"; + + } + + /// + /// Identifier of the problem. + /// Constants for possible values can be found using Error.CodeValue + /// + [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)] + public string Code { get; set; } + /// + /// An explanation of the problem with possible solutions. + /// + [JsonProperty("message", NullValueHandling = NullValueHandling.Ignore)] + public string Message { get; set; } + /// + /// A URL for more information about the solution. + /// + [JsonProperty("more_info", NullValueHandling = NullValueHandling.Ignore)] + public string MoreInfo { get; set; } + /// + /// Details about the specific area of the problem. + /// + [JsonProperty("target", NullValueHandling = NullValueHandling.Ignore)] + public ErrorTarget Target { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/Error.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/Error.cs.meta new file mode 100644 index 000000000..b4de75e7a --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Error.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 261d3650a0e04405c949c2e588e2f3ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ErrorTarget.cs b/Scripts/Services/VisualRecognition/V4/Model/ErrorTarget.cs new file mode 100644 index 000000000..8799c67be --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ErrorTarget.cs @@ -0,0 +1,59 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about the specific area of the problem. + /// + public class ErrorTarget + { + /// + /// The parameter or property that is the focus of the problem. + /// + public class TypeValue + { + /// + /// Constant FIELD for field + /// + public const string FIELD = "field"; + /// + /// Constant PARAMETER for parameter + /// + public const string PARAMETER = "parameter"; + /// + /// Constant HEADER for header + /// + public const string HEADER = "header"; + + } + + /// + /// The parameter or property that is the focus of the problem. + /// Constants for possible values can be found using ErrorTarget.TypeValue + /// + [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] + public string Type { get; set; } + /// + /// The property that is identified with the problem. + /// + [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)] + public string Name { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ErrorTarget.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ErrorTarget.cs.meta new file mode 100644 index 000000000..7317db9db --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ErrorTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81127a959e3784f1a8ab8d4b925333ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/Image.cs b/Scripts/Services/VisualRecognition/V4/Model/Image.cs new file mode 100644 index 000000000..4134b802f --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Image.cs @@ -0,0 +1,48 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about an image. + /// + public class Image + { + /// + /// The source type of the image. + /// + [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] + public ImageSource Source { get; set; } + /// + /// Height and width of an image. + /// + [JsonProperty("dimensions", NullValueHandling = NullValueHandling.Ignore)] + public ImageDimensions Dimensions { get; set; } + /// + /// Container for the list of collections that have objects detected in an image. + /// + [JsonProperty("objects", NullValueHandling = NullValueHandling.Ignore)] + public DetectedObjects Objects { get; set; } + /// + /// Details about an error. + /// + [JsonProperty("errors", NullValueHandling = NullValueHandling.Ignore)] + public Error Errors { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/Image.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/Image.cs.meta new file mode 100644 index 000000000..eecfcae49 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Image.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7224026db8ed14b638b9c96176828c9a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageDetails.cs b/Scripts/Services/VisualRecognition/V4/Model/ImageDetails.cs new file mode 100644 index 000000000..50eadc445 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageDetails.cs @@ -0,0 +1,64 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; +using System; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about an image. + /// + public class ImageDetails + { + /// + /// The identifier of the image. + /// + [JsonProperty("image_id", NullValueHandling = NullValueHandling.Ignore)] + public string ImageId { get; set; } + /// + /// Date and time in Coordinated Universal Time (UTC) that the image was most recently updated. + /// + [JsonProperty("updated", NullValueHandling = NullValueHandling.Ignore)] + public DateTime? Updated { get; set; } + /// + /// Date and time in Coordinated Universal Time (UTC) that the image was created. + /// + [JsonProperty("created", NullValueHandling = NullValueHandling.Ignore)] + public DateTime? Created { get; set; } + /// + /// The source type of the image. + /// + [JsonProperty("source", NullValueHandling = NullValueHandling.Ignore)] + public ImageSource Source { get; set; } + /// + /// Height and width of an image. + /// + [JsonProperty("dimensions", NullValueHandling = NullValueHandling.Ignore)] + public ImageDimensions Dimensions { get; set; } + /// + /// Details about an error. + /// + [JsonProperty("errors", NullValueHandling = NullValueHandling.Ignore)] + public Error Errors { get; set; } + /// + /// Training data for all objects. + /// + [JsonProperty("training_data", NullValueHandling = NullValueHandling.Ignore)] + public TrainingDataObjects TrainingData { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageDetails.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ImageDetails.cs.meta new file mode 100644 index 000000000..b895f03aa --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageDetails.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d81711964681b45c5ad982d24e6b615b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageDetailsList.cs b/Scripts/Services/VisualRecognition/V4/Model/ImageDetailsList.cs new file mode 100644 index 000000000..eaf4afd09 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageDetailsList.cs @@ -0,0 +1,44 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// List of information about the images. + /// + public class ImageDetailsList + { + /// + /// The images in the collection. + /// + [JsonProperty("images", NullValueHandling = NullValueHandling.Ignore)] + public List Images { get; set; } + /// + /// Information about what might cause less than optimal output. + /// + [JsonProperty("warnings", NullValueHandling = NullValueHandling.Ignore)] + public List Warnings { get; set; } + /// + /// A unique identifier of the request. Included only when an error or warning is returned. + /// + [JsonProperty("trace", NullValueHandling = NullValueHandling.Ignore)] + public string Trace { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageDetailsList.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ImageDetailsList.cs.meta new file mode 100644 index 000000000..250fcf934 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageDetailsList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c525f04f1b8114aa8a3fa75a372ea19b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageDimensions.cs b/Scripts/Services/VisualRecognition/V4/Model/ImageDimensions.cs new file mode 100644 index 000000000..ca498669a --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageDimensions.cs @@ -0,0 +1,38 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Height and width of an image. + /// + public class ImageDimensions + { + /// + /// Height in pixels of the image. + /// + [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)] + public long? Height { get; set; } + /// + /// Width in pixels of the image. + /// + [JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)] + public long? Width { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageDimensions.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ImageDimensions.cs.meta new file mode 100644 index 000000000..7464e56a2 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageDimensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bdc0da5fb04694f78b5a955e17bba56a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageSource.cs b/Scripts/Services/VisualRecognition/V4/Model/ImageSource.cs new file mode 100644 index 000000000..6325743e8 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageSource.cs @@ -0,0 +1,70 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// The source type of the image. + /// + public class ImageSource + { + /// + /// The source type of the image. + /// + public class TypeValue + { + /// + /// Constant FILE for file + /// + public const string FILE = "file"; + /// + /// Constant URL for url + /// + public const string URL = "url"; + + } + + /// + /// The source type of the image. + /// Constants for possible values can be found using ImageSource.TypeValue + /// + [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)] + public string Type { get; set; } + /// + /// Name of the image file if uploaded. Not returned when the image is passed by URL. + /// + [JsonProperty("filename", NullValueHandling = NullValueHandling.Ignore)] + public string Filename { get; set; } + /// + /// Name of the .zip file of images if uploaded. Not returned when the image is passed directly or by URL. + /// + [JsonProperty("archive_filename", NullValueHandling = NullValueHandling.Ignore)] + public string ArchiveFilename { get; set; } + /// + /// Source of the image before any redirects. Not returned when the image is uploaded. + /// + [JsonProperty("source_url", NullValueHandling = NullValueHandling.Ignore)] + public string SourceUrl { get; set; } + /// + /// Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded. + /// + [JsonProperty("resolved_url", NullValueHandling = NullValueHandling.Ignore)] + public string ResolvedUrl { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageSource.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ImageSource.cs.meta new file mode 100644 index 000000000..038fe3d57 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageSource.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: db7b988a33c2f422c9f6ff262466b0a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageSummary.cs b/Scripts/Services/VisualRecognition/V4/Model/ImageSummary.cs new file mode 100644 index 000000000..236868405 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageSummary.cs @@ -0,0 +1,39 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; +using System; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Basic information about an image. + /// + public class ImageSummary + { + /// + /// The identifier of the image. + /// + [JsonProperty("image_id", NullValueHandling = NullValueHandling.Ignore)] + public string ImageId { get; set; } + /// + /// Date and time in Coordinated Universal Time (UTC) that the image was most recently updated. + /// + [JsonProperty("updated", NullValueHandling = NullValueHandling.Ignore)] + public DateTime? Updated { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageSummary.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ImageSummary.cs.meta new file mode 100644 index 000000000..67e6b63af --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageSummary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ab5436c1f6dcc4e89a3362a8486c1df7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageSummaryList.cs b/Scripts/Services/VisualRecognition/V4/Model/ImageSummaryList.cs new file mode 100644 index 000000000..a33cc4544 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageSummaryList.cs @@ -0,0 +1,34 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// List of images. + /// + public class ImageSummaryList + { + /// + /// The images in the collection. + /// + [JsonProperty("images", NullValueHandling = NullValueHandling.Ignore)] + public List Images { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ImageSummaryList.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ImageSummaryList.cs.meta new file mode 100644 index 000000000..5ce208f03 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ImageSummaryList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2e1fdce12e5ff4249994bc0d78f31855 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/Location.cs b/Scripts/Services/VisualRecognition/V4/Model/Location.cs new file mode 100644 index 000000000..ce8701984 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Location.cs @@ -0,0 +1,48 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Defines the location of the bounding box around the object. + /// + public class Location + { + /// + /// Y-position of top-left pixel of the bounding box. + /// + [JsonProperty("top", NullValueHandling = NullValueHandling.Ignore)] + public long? Top { get; set; } + /// + /// X-position of top-left pixel of the bounding box. + /// + [JsonProperty("left", NullValueHandling = NullValueHandling.Ignore)] + public long? Left { get; set; } + /// + /// Width in pixels of of the bounding box. + /// + [JsonProperty("width", NullValueHandling = NullValueHandling.Ignore)] + public long? Width { get; set; } + /// + /// Height in pixels of the bounding box. + /// + [JsonProperty("height", NullValueHandling = NullValueHandling.Ignore)] + public long? Height { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/Location.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/Location.cs.meta new file mode 100644 index 000000000..f2128b9de --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Location.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dd9cc9d49797c470999029e6d8de113e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ObjectDetail.cs b/Scripts/Services/VisualRecognition/V4/Model/ObjectDetail.cs new file mode 100644 index 000000000..c1974e9cb --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ObjectDetail.cs @@ -0,0 +1,44 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about an object in the collection. + /// + public class ObjectDetail + { + /// + /// The label for the object. + /// + [JsonProperty("object", NullValueHandling = NullValueHandling.Ignore)] + public string _Object { get; set; } + /// + /// Defines the location of the bounding box around the object. + /// + [JsonProperty("location", NullValueHandling = NullValueHandling.Ignore)] + public Location Location { get; set; } + /// + /// Confidence score for the object in the range of 0 to 1. A higher score indicates greater likelihood that the + /// object is depicted at this location in the image. + /// + [JsonProperty("score", NullValueHandling = NullValueHandling.Ignore)] + public float? Score { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ObjectDetail.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ObjectDetail.cs.meta new file mode 100644 index 000000000..a25b6006e --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ObjectDetail.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de067b2d9c60c40039d1772c6c76fcaf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/ObjectTrainingStatus.cs b/Scripts/Services/VisualRecognition/V4/Model/ObjectTrainingStatus.cs new file mode 100644 index 000000000..53755c563 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ObjectTrainingStatus.cs @@ -0,0 +1,54 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Training status for the objects in the collection. + /// + public class ObjectTrainingStatus + { + /// + /// Whether you can analyze images in the collection with the **objects** feature. + /// + [JsonProperty("ready", NullValueHandling = NullValueHandling.Ignore)] + public bool? Ready { get; set; } + /// + /// Whether training is in progress. + /// + [JsonProperty("in_progress", NullValueHandling = NullValueHandling.Ignore)] + public bool? InProgress { get; set; } + /// + /// Whether there are changes to the training data since the most recent training. + /// + [JsonProperty("data_changed", NullValueHandling = NullValueHandling.Ignore)] + public bool? DataChanged { get; set; } + /// + /// Whether the most recent training failed. + /// + [JsonProperty("latest_failed", NullValueHandling = NullValueHandling.Ignore)] + public bool? LatestFailed { get; set; } + /// + /// Details about the training. If training is in progress, includes information about the status. If training + /// is not in progress, includes a success message or information about why training failed. + /// + [JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)] + public string Description { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/ObjectTrainingStatus.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/ObjectTrainingStatus.cs.meta new file mode 100644 index 000000000..203a96aa0 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/ObjectTrainingStatus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a56739a4771c7451cab83fce02146016 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObject.cs b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObject.cs new file mode 100644 index 000000000..9c8896180 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObject.cs @@ -0,0 +1,38 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about the training data. + /// + public class TrainingDataObject + { + /// + /// The name of the object. + /// + [JsonProperty("object", NullValueHandling = NullValueHandling.Ignore)] + public string _Object { get; set; } + /// + /// Defines the location of the bounding box around the object. + /// + [JsonProperty("location", NullValueHandling = NullValueHandling.Ignore)] + public Location Location { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObject.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObject.cs.meta new file mode 100644 index 000000000..7512c8705 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ca4b62cf8c6a24bb99c9c1363e9ef287 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObjects.cs b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObjects.cs new file mode 100644 index 000000000..045c62cb7 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObjects.cs @@ -0,0 +1,34 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Training data for all objects. + /// + public class TrainingDataObjects + { + /// + /// Training data for specific objects. + /// + [JsonProperty("objects", NullValueHandling = NullValueHandling.Ignore)] + public List Objects { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObjects.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObjects.cs.meta new file mode 100644 index 000000000..1fc50cd1e --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/TrainingDataObjects.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c001910da99744443b8ae12b45bfca20 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/TrainingStatus.cs b/Scripts/Services/VisualRecognition/V4/Model/TrainingStatus.cs new file mode 100644 index 000000000..ab2fbecb3 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/TrainingStatus.cs @@ -0,0 +1,33 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Training status information for the collection. + /// + public class TrainingStatus + { + /// + /// Training status for the objects in the collection. + /// + [JsonProperty("objects", NullValueHandling = NullValueHandling.Ignore)] + public ObjectTrainingStatus Objects { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/TrainingStatus.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/TrainingStatus.cs.meta new file mode 100644 index 000000000..9ef40098d --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/TrainingStatus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ccb5d0e420a7446ad9aaab7917238bb9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/Model/Warning.cs b/Scripts/Services/VisualRecognition/V4/Model/Warning.cs new file mode 100644 index 000000000..fb3014415 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Warning.cs @@ -0,0 +1,72 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using Newtonsoft.Json; + +namespace IBM.Watson.VisualRecognition.V4.Model +{ + /// + /// Details about a problem. + /// + public class Warning + { + /// + /// Identifier of the problem. + /// + public class CodeValue + { + /// + /// Constant INVALID_FIELD for invalid_field + /// + public const string INVALID_FIELD = "invalid_field"; + /// + /// Constant INVALID_HEADER for invalid_header + /// + public const string INVALID_HEADER = "invalid_header"; + /// + /// Constant INVALID_METHOD for invalid_method + /// + public const string INVALID_METHOD = "invalid_method"; + /// + /// Constant MISSING_FIELD for missing_field + /// + public const string MISSING_FIELD = "missing_field"; + /// + /// Constant SERVER_ERROR for server_error + /// + public const string SERVER_ERROR = "server_error"; + + } + + /// + /// Identifier of the problem. + /// Constants for possible values can be found using Warning.CodeValue + /// + [JsonProperty("code", NullValueHandling = NullValueHandling.Ignore)] + public string Code { get; set; } + /// + /// An explanation of the problem with possible solutions. + /// + [JsonProperty("message", NullValueHandling = NullValueHandling.Ignore)] + public string Message { get; set; } + /// + /// A URL for more information about the solution. + /// + [JsonProperty("more_info", NullValueHandling = NullValueHandling.Ignore)] + public string MoreInfo { get; set; } + } +} diff --git a/Scripts/Services/VisualRecognition/V4/Model/Warning.cs.meta b/Scripts/Services/VisualRecognition/V4/Model/Warning.cs.meta new file mode 100644 index 000000000..8a2b710bb --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/Model/Warning.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8510c565e381e40b4aaa9d90040c5c78 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/VisualRecognition/V4/VisualRecognitionService.cs b/Scripts/Services/VisualRecognition/V4/VisualRecognitionService.cs new file mode 100644 index 000000000..80b1b2e79 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/VisualRecognitionService.cs @@ -0,0 +1,1238 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System.Collections.Generic; +using System.IO; +using System.Text; +using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Connection; +using IBM.Cloud.SDK.Model; +using IBM.Cloud.SDK.Utilities; +using IBM.Watson.VisualRecognition.V4.Model; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using UnityEngine.Networking; + +namespace IBM.Watson.VisualRecognition.V4 +{ + public partial class VisualRecognitionService : BaseService + { + private const string serviceId = "visual_recognition"; + private const string defaultServiceUrl = "https://gateway.watsonplatform.net/visual-recognition/api"; + + #region VersionDate + private string versionDate; + /// + /// Gets and sets the versionDate of the service. + /// + public string VersionDate + { + get { return versionDate; } + set { versionDate = value; } + } + #endregion + + #region DisableSslVerification + private bool disableSslVerification = false; + /// + /// Gets and sets the option to disable ssl verification + /// + public bool DisableSslVerification + { + get { return disableSslVerification; } + set { disableSslVerification = value; } + } + #endregion + + /// + /// VisualRecognitionService constructor. + /// + /// The service version date in `yyyy-mm-dd` format. + public VisualRecognitionService(string versionDate) : this(versionDate, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceId)) {} + + /// + /// VisualRecognitionService constructor. + /// + /// The service version date in `yyyy-mm-dd` format. + /// The service authenticator. + public VisualRecognitionService(string versionDate, Authenticator authenticator) : base(versionDate, authenticator, serviceId) + { + Authenticator = authenticator; + if (string.IsNullOrEmpty(versionDate)) + { + throw new ArgumentNullException("A versionDate (format `yyyy-mm-dd`) is required to create an instance of VisualRecognitionService"); + } + else + { + VersionDate = versionDate; + } + + + if (string.IsNullOrEmpty(GetServiceUrl())) + { + SetServiceUrl(defaultServiceUrl); + } + } + + /// + /// Analyze images. + /// + /// Analyze images by URL, by file, or both against your own collection. Make sure that + /// **training_status.objects.ready** is `true` for the feature before you use a collection to analyze images. + /// + /// Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes + /// UTF-8 encoding if it encounters non-ASCII characters. + /// + /// The callback function that is invoked when the operation completes. + /// The IDs of the collections to analyze. + /// The features to analyze. + /// An array of image files (.jpg or .png) or .zip files with images. + /// - Include a maximum of 20 images in a request. + /// - Limit the .zip file to 100 MB. + /// - Limit each image file to 10 MB. + /// + /// You can also include an image with the **image_url** parameter. (optional) + /// An array of URLs of image files (.jpg or .png). + /// - Include a maximum of 20 images in a request. + /// - Limit each image file to 10 MB. + /// - Minimum width and height is 30 pixels, but the service tends to perform better with images that are at + /// least 300 x 300 pixels. Maximum is 5400 pixels for either height or width. + /// + /// You can also include images with the **images_file** parameter. (optional) + /// The minimum score a feature must have to be returned. (optional) + /// AnalyzeResponse + public bool Analyze(Callback callback, List collectionIds, List features, List imagesFile = null, List imageUrl = null, float? threshold = null) + { + if (collectionIds == null || collectionIds.Count == 0) + { + throw new ArgumentNullException("`collectionIds` is required for `Analyze`"); + } + if (features == null || features.Count == 0) + { + throw new ArgumentNullException("`features` is required for `Analyze`"); + } + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbPOST, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "Analyze")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + req.Forms = new Dictionary(); + if (collectionIds != null) + { + req.Forms["collection_ids"] = new RESTConnector.Form(string.Join(",", collectionIds.ToArray())); + } + if (features != null) + { + req.Forms["features"] = new RESTConnector.Form(string.Join(",", features.ToArray())); + } + if (imagesFile != null) + { + foreach (FileWithMetadata item in imagesFile) + { + req.Forms["images_file"] = new RESTConnector.Form(item.Data, item.Filename, item.ContentType); + } + } + if (imageUrl != null) + { + foreach (string item in imageUrl) + { + req.Forms["image_url"] = new RESTConnector.Form(item); + } + } + if (threshold != null) + { + req.Forms["threshold"] = new RESTConnector.Form(threshold.ToString()); + } + + req.OnResponse = OnAnalyzeResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v4/analyze", GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnAnalyzeResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnAnalyzeResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Create a collection. + /// + /// Create a collection that can be used to store images. + /// + /// To create a collection without specifying a name and description, include an empty JSON object in the + /// request body. + /// + /// Encode the name and description in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 + /// encoding if it encounters non-ASCII characters. + /// + /// The callback function that is invoked when the operation completes. + /// The name of the collection. The name can contain alphanumeric, underscore, hyphen, and + /// dot characters. It cannot begin with the reserved prefix `sys-`. (optional) + /// The description of the collection. (optional) + /// Collection + public bool CreateCollection(Callback callback, string name = null, string description = null) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `CreateCollection`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbPOST, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "CreateCollection")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + + JObject bodyObject = new JObject(); + if (!string.IsNullOrEmpty(name)) + bodyObject["name"] = name; + if (!string.IsNullOrEmpty(description)) + bodyObject["description"] = description; + req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); + + req.OnResponse = OnCreateCollectionResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v4/collections", GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnCreateCollectionResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnCreateCollectionResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// List collections. + /// + /// Retrieves a list of collections for the service instance. + /// + /// The callback function that is invoked when the operation completes. + /// CollectionsList + public bool ListCollections(Callback callback) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `ListCollections`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbGET, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "ListCollections")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnListCollectionsResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v4/collections", GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnListCollectionsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnListCollectionsResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Get collection details. + /// + /// Get details of one collection. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// Collection + public bool GetCollection(Callback callback, string collectionId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `GetCollection`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `GetCollection`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbGET, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "GetCollection")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnGetCollectionResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}", collectionId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnGetCollectionResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnGetCollectionResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Update a collection. + /// + /// Update the name or description of a collection. + /// + /// Encode the name and description in UTF-8 if they contain non-ASCII characters. The service assumes UTF-8 + /// encoding if it encounters non-ASCII characters. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// The name of the collection. The name can contain alphanumeric, underscore, hyphen, and + /// dot characters. It cannot begin with the reserved prefix `sys-`. (optional) + /// The description of the collection. (optional) + /// Collection + public bool UpdateCollection(Callback callback, string collectionId, string name = null, string description = null) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `UpdateCollection`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `UpdateCollection`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbPOST, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "UpdateCollection")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + + JObject bodyObject = new JObject(); + if (!string.IsNullOrEmpty(name)) + bodyObject["name"] = name; + if (!string.IsNullOrEmpty(description)) + bodyObject["description"] = description; + req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); + + req.OnResponse = OnUpdateCollectionResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}", collectionId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnUpdateCollectionResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnUpdateCollectionResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Delete a collection. + /// + /// Delete a collection from the service instance. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// object + public bool DeleteCollection(Callback callback, string collectionId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `DeleteCollection`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `DeleteCollection`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbDELETE, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "DeleteCollection")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnDeleteCollectionResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}", collectionId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnDeleteCollectionResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnDeleteCollectionResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Add images. + /// + /// Add images to a collection by URL, by file, or both. + /// + /// Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service assumes + /// UTF-8 encoding if it encounters non-ASCII characters. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// An array of image files (.jpg or .png) or .zip files with images. + /// - Include a maximum of 20 images in a request. + /// - Limit the .zip file to 100 MB. + /// - Limit each image file to 10 MB. + /// + /// You can also include an image with the **image_url** parameter. (optional) + /// The array of URLs of image files (.jpg or .png). + /// - Include a maximum of 20 images in a request. + /// - Limit each image file to 10 MB. + /// - Minimum width and height is 30 pixels, but the service tends to perform better with images that are at + /// least 300 x 300 pixels. Maximum is 5400 pixels for either height or width. + /// + /// You can also include images with the **images_file** parameter. (optional) + /// Training data for a single image. Include training data only if you add one image + /// with the request. + /// + /// The `object` property can contain alphanumeric, underscore, hyphen, space, and dot characters. It cannot + /// begin with the reserved prefix `sys-` and must be no longer than 32 characters. (optional) + /// ImageDetailsList + public bool AddImages(Callback callback, string collectionId, List imagesFile = null, List imageUrl = null, string trainingData = null) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `AddImages`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `AddImages`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbPOST, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "AddImages")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + req.Forms = new Dictionary(); + if (imagesFile != null) + { + foreach (FileWithMetadata item in imagesFile) + { + req.Forms["images_file"] = new RESTConnector.Form(item.Data, item.Filename, item.ContentType); + } + } + if (imageUrl != null) + { + foreach (string item in imageUrl) + { + req.Forms["image_url"] = new RESTConnector.Form(item); + } + } + if (!string.IsNullOrEmpty(trainingData)) + { + req.Forms["training_data"] = new RESTConnector.Form(trainingData); + } + + req.OnResponse = OnAddImagesResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/images", collectionId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnAddImagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnAddImagesResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// List images. + /// + /// Retrieves a list of images in a collection. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// ImageSummaryList + public bool ListImages(Callback callback, string collectionId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `ListImages`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `ListImages`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbGET, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "ListImages")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnListImagesResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/images", collectionId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnListImagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnListImagesResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Get image details. + /// + /// Get the details of an image in a collection. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// The identifier of the image. + /// ImageDetails + public bool GetImageDetails(Callback callback, string collectionId, string imageId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `GetImageDetails`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `GetImageDetails`"); + if (string.IsNullOrEmpty(imageId)) + throw new ArgumentNullException("`imageId` is required for `GetImageDetails`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbGET, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "GetImageDetails")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnGetImageDetailsResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/images/{1}", collectionId, imageId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnGetImageDetailsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnGetImageDetailsResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Delete an image. + /// + /// Delete one image from a collection. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// The identifier of the image. + /// object + public bool DeleteImage(Callback callback, string collectionId, string imageId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `DeleteImage`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `DeleteImage`"); + if (string.IsNullOrEmpty(imageId)) + throw new ArgumentNullException("`imageId` is required for `DeleteImage`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbDELETE, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "DeleteImage")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnDeleteImageResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/images/{1}", collectionId, imageId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnDeleteImageResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnDeleteImageResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Get a JPEG file of an image. + /// + /// Download a JPEG representation of an image. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// The identifier of the image. + /// Specify the image size. (optional, default to full) + /// byte[] + public bool GetJpegImage(Callback callback, string collectionId, string imageId, string size = null) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `GetJpegImage`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `GetJpegImage`"); + if (string.IsNullOrEmpty(imageId)) + throw new ArgumentNullException("`imageId` is required for `GetJpegImage`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbGET, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "GetJpegImage")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + if (!string.IsNullOrEmpty(size)) + { + req.Parameters["size"] = size; + } + + req.OnResponse = OnGetJpegImageResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/images/{1}/jpeg", collectionId, imageId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnGetJpegImageResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + response.Result = resp.Data; + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Train a collection. + /// + /// Start training on images in a collection. The collection must have enough training data and untrained data + /// (the **training_status.objects.data_changed** is `true`). If training is in progress, the request queues the + /// next training job. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// Collection + public bool Train(Callback callback, string collectionId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `Train`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `Train`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbPOST, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "Train")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + + req.OnResponse = OnTrainResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/train", collectionId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnTrainResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnTrainResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Add training data to an image. + /// + /// Add, update, or delete training data for an image. Encode the object name in UTF-8 if it contains non-ASCII + /// characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. + /// + /// Elements in the request replace the existing elements. + /// + /// - To update the training data, provide both the unchanged and the new or changed values. + /// + /// - To delete the training data, provide an empty value for the training data. + /// + /// The callback function that is invoked when the operation completes. + /// The identifier of the collection. + /// The identifier of the image. + /// Training data for specific objects. (optional) + /// TrainingDataObjects + public bool AddImageTrainingData(Callback callback, string collectionId, string imageId, List objects = null) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `AddImageTrainingData`"); + if (string.IsNullOrEmpty(collectionId)) + throw new ArgumentNullException("`collectionId` is required for `AddImageTrainingData`"); + if (string.IsNullOrEmpty(imageId)) + throw new ArgumentNullException("`imageId` is required for `AddImageTrainingData`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbPOST, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "AddImageTrainingData")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + + JObject bodyObject = new JObject(); + if (objects != null && objects.Count > 0) + bodyObject["objects"] = JToken.FromObject(objects); + req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject)); + + req.OnResponse = OnAddImageTrainingDataResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, string.Format("/v4/collections/{0}/images/{1}/training_data", collectionId, imageId), GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnAddImageTrainingDataResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnAddImageTrainingDataResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + /// + /// Delete labeled data. + /// + /// Deletes all data associated with a specified customer ID. The method has no effect if no data is associated + /// with the customer ID. + /// + /// You associate a customer ID with data by passing the `X-Watson-Metadata` header with a request that passes + /// data. For more information about personal data and customer IDs, see [Information + /// security](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-information-security). + /// + /// The callback function that is invoked when the operation completes. + /// The customer ID for which all data is to be deleted. + /// object + public bool DeleteUserData(Callback callback, string customerId) + { + if (callback == null) + throw new ArgumentNullException("`callback` is required for `DeleteUserData`"); + if (string.IsNullOrEmpty(customerId)) + throw new ArgumentNullException("`customerId` is required for `DeleteUserData`"); + + RequestObject req = new RequestObject + { + Callback = callback, + HttpMethod = UnityWebRequest.kHttpVerbDELETE, + DisableSslVerification = DisableSslVerification + }; + + foreach (KeyValuePair kvp in customRequestHeaders) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + ClearCustomRequestHeaders(); + + foreach (KeyValuePair kvp in Common.GetSdkHeaders("watson_vision_combined", "V4", "DeleteUserData")) + { + req.Headers.Add(kvp.Key, kvp.Value); + } + + req.Parameters["version"] = VersionDate; + if (!string.IsNullOrEmpty(customerId)) + { + req.Parameters["customer_id"] = customerId; + } + + req.OnResponse = OnDeleteUserDataResponse; + + RESTConnector connector = RESTConnector.GetConnector(Authenticator, "/v4/user_data", GetServiceUrl()); + if (connector == null) + { + return false; + } + + return connector.Send(req); + } + + private void OnDeleteUserDataResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DetailedResponse response = new DetailedResponse(); + foreach (KeyValuePair kvp in resp.Headers) + { + response.Headers.Add(kvp.Key, kvp.Value); + } + response.StatusCode = resp.HttpResponseCode; + + try + { + string json = Encoding.UTF8.GetString(resp.Data); + response.Result = JsonConvert.DeserializeObject(json); + response.Response = json; + } + catch (Exception e) + { + Log.Error("VisualRecognitionService.OnDeleteUserDataResponse()", "Exception: {0}", e.ToString()); + resp.Success = false; + } + + if (((RequestObject)req).Callback != null) + ((RequestObject)req).Callback(response, resp.Error); + } + } +} \ No newline at end of file diff --git a/Scripts/Services/VisualRecognition/V4/VisualRecognitionService.cs.meta b/Scripts/Services/VisualRecognition/V4/VisualRecognitionService.cs.meta new file mode 100644 index 000000000..d0636fa17 --- /dev/null +++ b/Scripts/Services/VisualRecognition/V4/VisualRecognitionService.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f9f1210dce7014f06af4dd2cc5a97739 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/AssistantV1IntegrationTests.cs b/Tests/AssistantV1IntegrationTests.cs index baacde9b2..1ad73531e 100644 --- a/Tests/AssistantV1IntegrationTests.cs +++ b/Tests/AssistantV1IntegrationTests.cs @@ -19,6 +19,8 @@ using System.Collections; using System.Collections.Generic; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Authentication.Iam; using IBM.Watson.Assistant.V1; using IBM.Watson.Assistant.V1.Model; using Newtonsoft.Json.Linq; @@ -72,7 +74,7 @@ public IEnumerator UnityTestSetup() service = new AssistantService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -86,17 +88,17 @@ public void TestSetup() public IEnumerator TestMessage() { workspaceId = Environment.GetEnvironmentVariable("ASSISTANT_WORKSPACE_ID"); - JToken context = null; + Context context = null; MessageResponse messageResponse = null; - JToken conversationId = null; - Log.Debug("AssistantV1IntegrationTests", "Attempting to Message..."); + string conversationId = null; + Log.Debug("AssistantV1IntegrationTests", "Attempting to Message...{0}...", workspaceId); service.Message( callback: (DetailedResponse response, IBMError error) => { messageResponse = response.Result; context = messageResponse.Context; - Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output["generic"][0]["text"]); - (context as JObject).TryGetValue("conversation_id", out conversationId); + Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output.Generic[0].Text); + conversationId = context.ConversationId; Assert.IsNotNull(context); Assert.IsNotNull(conversationId); Assert.IsNull(error); @@ -111,26 +113,30 @@ public IEnumerator TestMessage() service.WithHeader("X-Watson-Test", "1"); messageResponse = null; - JObject input = new JObject(); - JToken conversationId1 = null; + MessageInput input = new MessageInput(); + string conversationId1 = null; + context.Add("name", "watson"); input.Add("text", "Are you open on Christmas?"); + Log.Debug("AssistantV1IntegrationTests", "Attempting to Message...Are you open on Christmas?"); service.Message( callback: (DetailedResponse response, IBMError error) => { + Context context1 = null; messageResponse = response.Result; - context = messageResponse.Context; - Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output["generic"][0]["text"]); - (context as JObject).TryGetValue("conversation_id", out conversationId1); + context1 = messageResponse.Context; + Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output.Generic[0].Text); + conversationId1 = context1.ConversationId; + Assert.AreEqual(context1.Get("name"), context.Get("name")); Assert.IsNotNull(context); Assert.IsNotNull(conversationId1); - Assert.IsTrue(conversationId1.ToString() == conversationId.ToString()); + Assert.IsTrue(conversationId1 == conversationId); Assert.IsNull(error); }, workspaceId: workspaceId, input: input, - context: context as JObject, + context: context, nodesVisitedDetails: true ); @@ -140,8 +146,8 @@ public IEnumerator TestMessage() service.WithHeader("X-Watson-Test", "1"); messageResponse = null; - input = new JObject(); - JToken conversationId2 = null; + input = new MessageInput(); + string conversationId2 = null; input.Add("text", "What are your hours?"); Log.Debug("AssistantV1IntegrationTests", "Attempting to Message...What are your hours?"); service.Message( @@ -149,8 +155,8 @@ public IEnumerator TestMessage() { messageResponse = response.Result; context = messageResponse.Context; - Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output["generic"][0]["text"]); - (context as JObject).TryGetValue("conversation_id", out conversationId2); + Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output.Generic[0].Text); + conversationId2 = context.ConversationId; Assert.IsNotNull(context); Assert.IsNotNull(conversationId2); @@ -159,7 +165,7 @@ public IEnumerator TestMessage() }, workspaceId: workspaceId, input: input, - context: context as JObject, + context: context, nodesVisitedDetails: true ); @@ -169,8 +175,8 @@ public IEnumerator TestMessage() service.WithHeader("X-Watson-Test", "1"); messageResponse = null; - input = new JObject(); - JToken conversationId3 = null; + input = new MessageInput(); + string conversationId3 = null; input.Add("text", "I'd like to make an appointment for 12pm."); Log.Debug("AssistantV1IntegrationTests", "Attempting to Message...I'd like to make an appointment for 12pm."); service.Message( @@ -178,8 +184,8 @@ public IEnumerator TestMessage() { messageResponse = response.Result; context = messageResponse.Context; - Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output["generic"][0]["text"]); - (context as JObject).TryGetValue("conversation_id", out conversationId3); + Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output.Generic[0].Text); + conversationId3 = context.ConversationId; Assert.IsNotNull(context); Assert.IsNotNull(conversationId3); @@ -188,7 +194,7 @@ public IEnumerator TestMessage() }, workspaceId: workspaceId, input: input, - context: context as JObject, + context: context, nodesVisitedDetails: true ); @@ -198,8 +204,8 @@ public IEnumerator TestMessage() service.WithHeader("X-Watson-Test", "1"); messageResponse = null; - input = new JObject(); - JToken conversationId4 = null; + input = new MessageInput(); + string conversationId4 = null; input.Add("text", "On Friday please."); Log.Debug("AssistantV1IntegrationTests", "Attempting to Message...On Friday please."); service.Message( @@ -207,8 +213,8 @@ public IEnumerator TestMessage() { messageResponse = response.Result; context = messageResponse.Context; - Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output["generic"][0]["text"]); - (context as JObject).TryGetValue("conversation_id", out conversationId4); + Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output.Generic[0].Text); + conversationId4 = context.ConversationId; Assert.IsNotNull(context); Assert.IsNotNull(conversationId4); @@ -217,7 +223,7 @@ public IEnumerator TestMessage() }, workspaceId: workspaceId, input: input, - context: context as JObject, + context: context, nodesVisitedDetails: true ); @@ -227,8 +233,8 @@ public IEnumerator TestMessage() service.WithHeader("X-Watson-Test", "1"); messageResponse = null; - input = new JObject(); - JToken conversationId5 = null; + input = new MessageInput(); + string conversationId5 = null; input.Add("text", "Yes."); Log.Debug("AssistantV1IntegrationTests", "Attempting to Message...Yes."); service.Message( @@ -236,8 +242,8 @@ public IEnumerator TestMessage() { messageResponse = response.Result; context = messageResponse.Context; - Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output["generic"][0]["text"]); - (context as JObject).TryGetValue("conversation_id", out conversationId5); + Log.Debug("AssistantV1IntegrationTests", "result: {0}", messageResponse.Output.Generic[0].Text); + conversationId5 = context.ConversationId; Assert.IsNotNull(context); Assert.IsNotNull(conversationId5); @@ -246,7 +252,7 @@ public IEnumerator TestMessage() }, workspaceId: workspaceId, input: input, - context: context as JObject, + context: context, nodesVisitedDetails: true ); @@ -325,7 +331,6 @@ public IEnumerator TestListWorkspaces() Assert.IsNull(error); }, pageLimit: 1, - includeCount: true, sort: "-name", includeAudit: true ); @@ -428,7 +433,6 @@ public IEnumerator TestListIntents() workspaceId: workspaceId, export: true, pageLimit: 1, - includeCount: true, sort: "-name", includeAudit: true ); @@ -527,7 +531,6 @@ public IEnumerator TestListExamples() workspaceId: workspaceId, intent: updatedIntentName, pageLimit: 1, - includeCount: true, sort: "-text", includeAudit: true ); @@ -622,7 +625,6 @@ public IEnumerator TestListCounterexamples() }, workspaceId: workspaceId, pageLimit: 1, - includeCount: true, sort: "-text", includeAudit: true ); @@ -722,7 +724,6 @@ public IEnumerator TestListEntities() workspaceId: workspaceId, export: true, pageLimit: 1, - includeCount: true, sort: "-entity", includeAudit: true ); @@ -848,7 +849,6 @@ public IEnumerator TestListValues() entity: updatedEntityName, export: true, pageLimit: 1, - includeCount: true, sort: "-value", includeAudit: true ); @@ -949,7 +949,6 @@ public IEnumerator TestListSynonyms() entity: updatedEntityName, value: updatedValueText, pageLimit: 1, - includeCount: true, sort: "-synonym", includeAudit: true ); @@ -1048,7 +1047,6 @@ public IEnumerator TestListDialogNodes() }, workspaceId: workspaceId, pageLimit: 1, - includeCount: true, sort: "-dialog_node", includeAudit: true ); diff --git a/Tests/AssistantV2IntegrationTests.cs b/Tests/AssistantV2IntegrationTests.cs index 83da83db9..d223de004 100644 --- a/Tests/AssistantV2IntegrationTests.cs +++ b/Tests/AssistantV2IntegrationTests.cs @@ -16,6 +16,7 @@ */ using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Watson.Assistant.V2; using IBM.Watson.Assistant.V2.Model; using NUnit.Framework; @@ -44,7 +45,7 @@ public IEnumerator TestMessage() { service = new AssistantService(versionDate); - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; assistantId = Environment.GetEnvironmentVariable("ASSISTANT_ASSISTANT_ID"); diff --git a/Tests/CompareComplyV1IntegrationTests.cs b/Tests/CompareComplyV1IntegrationTests.cs index fb124e178..40bc4cb38 100644 --- a/Tests/CompareComplyV1IntegrationTests.cs +++ b/Tests/CompareComplyV1IntegrationTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.IO; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Utilities; using IBM.Watson.CompareComply.V1; using IBM.Watson.CompareComply.V1.Model; @@ -63,7 +64,7 @@ public IEnumerator UnityTestSetup() service = new CompareComplyService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -94,7 +95,6 @@ public IEnumerator TestConvertToHtml() Assert.IsNull(error); }, file: ms, - filename: "contract_A.pdf", model: "contracts", fileContentType: Utility.GetMimeType(Path.GetExtension(contractAFilepath)) ); diff --git a/Tests/CoreTests.cs b/Tests/CoreTests.cs index 4e821304b..9e802f149 100644 --- a/Tests/CoreTests.cs +++ b/Tests/CoreTests.cs @@ -18,6 +18,7 @@ using System.Collections; using System.Collections.Generic; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Watson.Assistant.V1; using IBM.Watson.Assistant.V1.Model; using NUnit.Framework; @@ -53,7 +54,7 @@ public IEnumerator TestSetHeaders() service = new AssistantService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; WorkspaceCollection listWorkspacesResponse = null; diff --git a/Tests/DiscoveryV1IntegrationTests.cs b/Tests/DiscoveryV1IntegrationTests.cs index d8abf2117..8cc74b31d 100644 --- a/Tests/DiscoveryV1IntegrationTests.cs +++ b/Tests/DiscoveryV1IntegrationTests.cs @@ -21,6 +21,7 @@ using System.IO; using System.Text; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Utilities; using IBM.Watson.Discovery.V1; using IBM.Watson.Discovery.V1.Model; @@ -89,7 +90,7 @@ public IEnumerator UnityTestSetup() service = new DiscoveryService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -328,41 +329,6 @@ public IEnumerator TestUpdateConfiguration() } #endregion - #region TestConfigurationInEnvironment - [UnityTest, Order(8)] - public IEnumerator TestTestConfigurationInEnvironment() - { - Log.Debug("DiscoveryServiceV1IntegrationTests", "Attempting to TestConfigurationInEnvironment..."); - TestDocument testConfigurationInEnvironmentResponse = null; - using (FileStream fs = File.OpenRead(watsonBeatsJeopardyHtmlFilePath)) - { - using (MemoryStream ms = new MemoryStream()) - { - fs.CopyTo(ms); - service.TestConfigurationInEnvironment( - callback: (DetailedResponse response, IBMError error) => - { - Log.Debug("DiscoveryServiceV1IntegrationTests", "TestConfigurationInEnvironment result: {0}", response.Response); - testConfigurationInEnvironmentResponse = response.Result; - Assert.IsNotNull(testConfigurationInEnvironmentResponse); - Assert.IsNotNull(testConfigurationInEnvironmentResponse.Status); - Assert.IsNotNull(testConfigurationInEnvironmentResponse.Snapshots); - Assert.IsNull(error); - }, - environmentId: environmentId, - configurationId: createdConfigurationId, - file: ms, - fileContentType: Utility.GetMimeType(Path.GetExtension(watsonBeatsJeopardyHtmlFilePath)), - filename: Path.GetFileName(watsonBeatsJeopardyHtmlFilePath) - ); - - while (testConfigurationInEnvironmentResponse == null) - yield return null; - } - } - } - #endregion - #region CreateCollection [UnityTest, Order(9)] public IEnumerator TestCreateCollection() @@ -884,12 +850,11 @@ public IEnumerator TestFederatedQuery() Assert.IsNull(error); }, environmentId: environmentId, - naturalLanguageQuery: "When did Watson win Jeopardy", collectionIds: collectionId, + naturalLanguageQuery: "When did Watson win Jeopardy", passages: true, count: 10, - highlight: true, - loggingOptOut: true + highlight: true ); while (federatedQueryResponse == null) @@ -952,37 +917,6 @@ public IEnumerator TestQuery() } #endregion - #region QueryEntities - //[UnityTest, Order(28)] - public IEnumerator TestQueryEntities() - { - Log.Debug("DiscoveryServiceV1IntegrationTests", "Attempting to QueryEntities..."); - QueryEntitiesResponse queryEntitiesResponse = null; - QueryEntitiesEntity entity = new QueryEntitiesEntity() - { - Text = "Jeopardy" - }; - - service.QueryEntities( - callback: (DetailedResponse response, IBMError error) => - { - Log.Debug("DiscoveryServiceV1IntegrationTests", "QueryEntities result: {0}", response.Response); - queryEntitiesResponse = response.Result; - Assert.IsNotNull(queryEntitiesResponse); - Assert.IsNull(error); - }, - environmentId: environmentId, - collectionId: collectionId, - entity: entity, - feature: "disambiguate", - count: 10 - ); - - while (queryEntitiesResponse == null) - yield return null; - } - #endregion - #region QueryNotices [UnityTest, Order(29)] public IEnumerator TestQueryNotices() @@ -1010,38 +944,6 @@ public IEnumerator TestQueryNotices() } #endregion - #region QueryRelations - //[UnityTest, Order(30)] - public IEnumerator TestQueryRelations() - { - Log.Debug("DiscoveryServiceV1IntegrationTests", "Attempting to QueryRelations..."); - QueryRelationsResponse queryRelationsResponse = null; - List entities = new List() - { - new QueryRelationsEntity() - { - Text = "Jeopardy" - } - }; - service.QueryRelations( - callback: (DetailedResponse response, IBMError error) => - { - Log.Debug("DiscoveryServiceV1IntegrationTests", "QueryRelations result: {0}", response.Response); - queryRelationsResponse = response.Result; - Assert.IsNotNull(queryRelationsResponse); - Assert.IsNull(error); - }, - environmentId: environmentId, - collectionId: collectionId, - entities: entities, - count: 10 - ); - - while (queryRelationsResponse == null) - yield return null; - } - #endregion - #region AddTrainingData [UnityTest, Order(31)] public IEnumerator TestAddTrainingData() @@ -1408,9 +1310,9 @@ public IEnumerator TestQueryLog() } #endregion - #region CreateCredentials + #region CreateAuthenticator [UnityTest, Order(45)] - public IEnumerator TestCreateCredentials() + public IEnumerator TestCreateAuthenticator() { Log.Debug("DiscoveryServiceV1IntegrationTests", "Attempting to CreateCredentials..."); ModelCredentials createCredentialsResponse = null; diff --git a/Tests/LanguageTranslatorV3IntegrationTests.cs b/Tests/LanguageTranslatorV3IntegrationTests.cs index 12d035f5a..5a2aa3190 100644 --- a/Tests/LanguageTranslatorV3IntegrationTests.cs +++ b/Tests/LanguageTranslatorV3IntegrationTests.cs @@ -57,7 +57,7 @@ public IEnumerator UnityTestSetup() service = new LanguageTranslatorService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -81,7 +81,7 @@ public IEnumerator TestTranslate() Assert.IsNotNull(translateResponse); Assert.IsNotNull(translateResponse.Translations); Assert.IsTrue(translateResponse.Translations.Count > 0); - Assert.IsTrue(translateResponse.Translations[0].TranslationOutput == spanishText); + Assert.IsTrue(translateResponse.Translations[0]._Translation == spanishText); Assert.IsNull(error); }, text: new List() { englishText }, @@ -219,8 +219,7 @@ public IEnumerator TestListModels() Assert.IsNull(error); }, source: "en", - target: "fr", - defaultModels: true + target: "fr" ); while (listModelsResponse == null) diff --git a/Tests/NaturalLanguageClassifierV1IntegrationTests.cs b/Tests/NaturalLanguageClassifierV1IntegrationTests.cs index 91ff136cd..f6cb9edbc 100644 --- a/Tests/NaturalLanguageClassifierV1IntegrationTests.cs +++ b/Tests/NaturalLanguageClassifierV1IntegrationTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.IO; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Watson.NaturalLanguageClassifier.V1; using IBM.Watson.NaturalLanguageClassifier.V1.Model; using NUnit.Framework; @@ -53,7 +54,7 @@ public IEnumerator UnityTestSetup() service = new NaturalLanguageClassifierService(); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -181,7 +182,7 @@ public IEnumerator TestCreateClassifier() Assert.IsTrue(createClassifierResponse.Language == "en"); Assert.IsNull(error); }, - metadata: ms0, + trainingMetadata: ms0, trainingData: ms1 ); diff --git a/Tests/NaturalLanguageUnderstandingV1IntegrationTests.cs b/Tests/NaturalLanguageUnderstandingV1IntegrationTests.cs index 74d5d0e26..cc3684942 100644 --- a/Tests/NaturalLanguageUnderstandingV1IntegrationTests.cs +++ b/Tests/NaturalLanguageUnderstandingV1IntegrationTests.cs @@ -18,6 +18,7 @@ using System.Collections; using System.Collections.Generic; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Watson.NaturalLanguageUnderstanding.V1; using IBM.Watson.NaturalLanguageUnderstanding.V1.Model; using NUnit.Framework; @@ -46,7 +47,7 @@ public IEnumerator UnityTestSetup() service = new NaturalLanguageUnderstandingService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } diff --git a/Tests/PersonalityInsightsV3IntegrationTests.cs b/Tests/PersonalityInsightsV3IntegrationTests.cs index e1b3ba53e..c1104314b 100644 --- a/Tests/PersonalityInsightsV3IntegrationTests.cs +++ b/Tests/PersonalityInsightsV3IntegrationTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.IO; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Watson.PersonalityInsights.V3; using IBM.Watson.PersonalityInsights.V3.Model; using NUnit.Framework; @@ -47,7 +48,7 @@ public IEnumerator UnityTestSetup() service = new PersonalityInsightsService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } diff --git a/Tests/SpeechToTextV1IntegrationTests.cs b/Tests/SpeechToTextV1IntegrationTests.cs index 30bd4032c..18cc29910 100644 --- a/Tests/SpeechToTextV1IntegrationTests.cs +++ b/Tests/SpeechToTextV1IntegrationTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.IO; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Utilities; using IBM.Watson.SpeechToText.V1; using IBM.Watson.SpeechToText.V1.Model; @@ -79,7 +80,7 @@ public IEnumerator UnityTestSetup() service = new SpeechToTextService(); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -461,7 +462,7 @@ public IEnumerator TestTrainLanguageModel() Log.Debug("SpeechToTextServiceV1IntegrationTests", "Attempting to TrainLanguageModel..."); object trainLanguageModelResponse = null; service.TrainLanguageModel( - callback: (DetailedResponse response, IBMError error) => + callback: (DetailedResponse response, IBMError error) => { Log.Debug("SpeechToTextServiceV1IntegrationTests", "TrainLanguageModel result: {0}", response.Response); trainLanguageModelResponse = response.Result; @@ -639,7 +640,7 @@ public IEnumerator TestTrainLanguageModel2() Log.Debug("SpeechToTextServiceV1IntegrationTests", "Attempting to TrainLanguageModel2..."); object trainLanguageModelResponse = null; service.TrainLanguageModel( - callback: (DetailedResponse response, IBMError error) => + callback: (DetailedResponse response, IBMError error) => { Log.Debug("SpeechToTextServiceV1IntegrationTests", "TrainLanguageModel result: {0}", response.Response); trainLanguageModelResponse = response.Result; @@ -763,7 +764,7 @@ public IEnumerator TestTrainLanguageModel3() Log.Debug("SpeechToTextServiceV1IntegrationTests", "Attempting to TrainLanguageModel3..."); object trainLanguageModelResponse = null; service.TrainLanguageModel( - callback: (DetailedResponse response, IBMError error) => + callback: (DetailedResponse response, IBMError error) => { Log.Debug("SpeechToTextServiceV1IntegrationTests", "TrainLanguageModel result: {0}", response.Response); trainLanguageModelResponse = response.Result; @@ -1012,7 +1013,7 @@ public IEnumerator TestTrainAcousticModel() Log.Debug("SpeechToTextServiceV1IntegrationTests", "Attempting to TrainAcousticModel..."); bool isComplete = false; service.TrainAcousticModel( - callback: (DetailedResponse response, IBMError error) => + callback: (DetailedResponse response, IBMError error) => { Log.Debug("SpeechToTextServiceV1IntegrationTests", "TrainAcousticModel result: {0}", response.Response); Assert.IsTrue(response.StatusCode == 200); diff --git a/Tests/TextToSpeechIntegrationTests.cs b/Tests/TextToSpeechIntegrationTests.cs index bdaf96470..714163dff 100644 --- a/Tests/TextToSpeechIntegrationTests.cs +++ b/Tests/TextToSpeechIntegrationTests.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Text.RegularExpressions; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Utilities; using IBM.Watson.TextToSpeech.V1; using IBM.Watson.TextToSpeech.V1.Model; @@ -57,7 +58,7 @@ public IEnumerator UnityTestSetup() service = new TextToSpeechService(); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } diff --git a/Tests/ToneAnalyzerV3IntegrationTests.cs b/Tests/ToneAnalyzerV3IntegrationTests.cs index 6c9045396..6787f271d 100644 --- a/Tests/ToneAnalyzerV3IntegrationTests.cs +++ b/Tests/ToneAnalyzerV3IntegrationTests.cs @@ -18,6 +18,7 @@ using System.Collections; using System.Collections.Generic; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Watson.ToneAnalyzer.V3; using IBM.Watson.ToneAnalyzer.V3.Model; using NUnit.Framework; @@ -46,7 +47,7 @@ public IEnumerator UnityTestSetup() service = new ToneAnalyzerService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } diff --git a/Tests/VisualRecognitionV3IntegrationTests.cs b/Tests/VisualRecognitionV3IntegrationTests.cs index 27a42ee8a..269ca6d2f 100644 --- a/Tests/VisualRecognitionV3IntegrationTests.cs +++ b/Tests/VisualRecognitionV3IntegrationTests.cs @@ -20,6 +20,7 @@ using System.Collections.Generic; using System.IO; using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Utilities; using IBM.Watson.VisualRecognition.V3; using IBM.Watson.VisualRecognition.V3.Model; @@ -40,7 +41,6 @@ public class VisualRecognitionV3IntegrationTests private string turtleImageFilepath; private string turtleImageContentType = "image/jpeg"; private string obamaImageFilepath; - private string obamaImageContentType = "image/jpeg"; private string imageMetadataFilepath; private string classifierName = "unity-sdk-classifier-safe-to-delete"; private string classifierId; @@ -68,7 +68,7 @@ public IEnumerator UnityTestSetup() service = new VisualRecognitionService(versionDate); } - while (!service.Credentials.HasIamTokenData()) + while (!service.Authenticator.CanAuthenticate()) yield return null; } @@ -107,7 +107,7 @@ public IEnumerator TestCreateClassifier() Assert.IsTrue(createClassifierResponse.Name == classifierName); Assert.IsNotNull(createClassifierResponse.Classes); Assert.IsTrue(createClassifierResponse.Classes.Count > 0); - Assert.IsTrue(createClassifierResponse.Classes[0].ClassName == "giraffe"); + Assert.IsTrue(createClassifierResponse.Classes[0]._Class == "giraffe"); Assert.IsNull(error); }, name: classifierName, @@ -160,41 +160,6 @@ public IEnumerator TestClassify() } #endregion - #region DetectFaces - [UnityTest, Order(2)] - public IEnumerator TestDetectFaces() - { - Log.Debug("VisualRecognitionServiceV3IntegrationTests", "Attempting to DetectFaces..."); - DetectedFaces detectFacesResponse = null; - using (FileStream fs = File.OpenRead(obamaImageFilepath)) - { - using (MemoryStream ms = new MemoryStream()) - { - fs.CopyTo(ms); - service.DetectFaces( - callback: (DetailedResponse response, IBMError error) => - { - Log.Debug("VisualRecognitionServiceV3IntegrationTests", "DetectFaces result: {0}", response.Response); - detectFacesResponse = response.Result; - Assert.IsNotNull(detectFacesResponse); - Assert.IsNotNull(detectFacesResponse.Images); - Assert.IsTrue(detectFacesResponse.Images.Count > 0); - Assert.IsNotNull(detectFacesResponse.Images[0].Faces); - Assert.IsTrue(detectFacesResponse.Images[0].Faces.Count > 0); - Assert.IsNull(error); - }, - imagesFile: ms, - imagesFileContentType: obamaImageContentType, - imagesFilename: Path.GetFileName(obamaImageFilepath) - ); - - while (detectFacesResponse == null) - yield return null; - } - } - } - #endregion - #region GetClassifier //[UnityTest, Order(3)] public IEnumerator TestGetClassifier() diff --git a/Tests/VisualRecognitionV4IntegrationTests.cs b/Tests/VisualRecognitionV4IntegrationTests.cs new file mode 100644 index 000000000..a9f46f619 --- /dev/null +++ b/Tests/VisualRecognitionV4IntegrationTests.cs @@ -0,0 +1,433 @@ +/** +* Copyright 2018, 2019 IBM Corp. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using IBM.Cloud.SDK; +using IBM.Cloud.SDK.Authentication; +using IBM.Cloud.SDK.Utilities; +using IBM.Cloud.SDK.Model; +using IBM.Watson.VisualRecognition.V4; +using IBM.Watson.VisualRecognition.V4.Model; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.TestTools; + +namespace IBM.Watson.Tests +{ + public class VisualRecognitionV4IntegrationTests + { + private VisualRecognitionService service; + private string versionDate = "2019-02-13"; + private string negativeExamplesFilepath; + private string giraffeImageFilepath; + private string turtleImageFilepath; + private string imageMetadataFilepath; + private string giraffeCollectionId = "d31d6534-3458-40c4-b6de-2185a5f3cbe4"; + private string giraffeClassname = "giraffe"; + private string turtleCollectionId = "760c8625-a456-4b73-b71d-d1619a6daf84"; + private string collectionId; + private string imageId; + + [OneTimeSetUp] + public void OneTimeSetup() + { + LogSystem.InstallDefaultReactors(); + + negativeExamplesFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/negative_examples.zip"; + giraffeImageFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/giraffe_to_classify.jpg"; + turtleImageFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/turtle_to_classify.jpg"; + imageMetadataFilepath = Application.dataPath + "/Watson/Tests/TestData/VisualRecognitionV3/imageMetadata.json"; + } + + [UnitySetUp] + public IEnumerator UnityTestSetup() + { + if (service == null) + { + service = new VisualRecognitionService(versionDate); + } + + while (!service.Authenticator.CanAuthenticate()) + yield return null; + } + + [SetUp] + public void TestSetup() + { + service.WithHeader("X-Watson-Test", "1"); + } + + #region Analyze + [UnityTest, Order(1)] + public IEnumerator TestAnalyze() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Analyze..."); + AnalyzeResponse analyzeResponse = null; + List imagesFile = new List(); + using (FileStream fs1 = File.OpenRead(giraffeImageFilepath), fs2 = File.OpenRead(turtleImageFilepath)) + { + using (MemoryStream ms1 = new MemoryStream(), ms2 = new MemoryStream()) + { + fs1.CopyTo(ms1); + fs2.CopyTo(ms2); + FileWithMetadata fileWithMetadata = new FileWithMetadata() + { + Data = ms1, + ContentType = "image/jpeg", + Filename = Path.GetFileName(giraffeImageFilepath) + }; + imagesFile.Add(fileWithMetadata); + + FileWithMetadata fileWithMetadata2 = new FileWithMetadata() + { + Data = ms2, + ContentType = "image/jpeg", + Filename = Path.GetFileName(turtleImageFilepath) + }; + imagesFile.Add(fileWithMetadata2); + + service.Analyze( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Analyze result: {0}", response.Response); + analyzeResponse = response.Result; + Assert.IsNotNull(analyzeResponse); + Assert.IsNotNull(analyzeResponse.Images); + Assert.IsTrue(analyzeResponse.Images.Count > 0); + Assert.IsNotNull(analyzeResponse.Images[0].Objects.Collections); + Assert.IsTrue(analyzeResponse.Images[0].Objects.Collections.Count > 0); + Assert.IsNull(error); + }, + collectionIds: new List() { giraffeCollectionId, turtleCollectionId }, + features: new List() { "objects" }, + imagesFile: imagesFile + ); + + while (analyzeResponse == null) + yield return null; + } + } + } + #endregion + + #region Collections + [UnityTest, Order(2)] + public IEnumerator TestListCollections() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to List Collections..."); + CollectionsList collectionsList = null; + service.ListCollections( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "List Collections result: {0}", response.Response); + collectionsList = response.Result; + Assert.IsNotNull(collectionsList.Collections); + Assert.IsTrue(collectionsList.Collections.Count > 0); + Assert.IsNull(error); + } + ); + + while (collectionsList == null) + yield return null; + } + + [UnityTest, Order(3)] + public IEnumerator TestGetCollection() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get Collection..."); + Collection collection = null; + service.GetCollection( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetCollection result: {0}", response.Response); + collection = response.Result; + Assert.IsNotNull(collection.CollectionId); + Assert.IsTrue(collection.CollectionId == giraffeCollectionId); + Assert.IsNull(error); + }, + collectionId: giraffeCollectionId + ); + + while (collection == null) + yield return null; + } + + [UnityTest, Order(4)] + public IEnumerator TestCreateCollection() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Create Collection..."); + Collection collection = null; + service.CreateCollection( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "CreateCollection result: {0}", response.Response); + collection = response.Result; + Assert.IsNotNull(collection.CollectionId); + Assert.IsNull(error); + collectionId = collection.CollectionId; + } + ); + + while (collection == null) + yield return null; + } + + [UnityTest, Order(5)] + public IEnumerator TestUpdateCollection() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Update Collection..."); + Collection collection = null; + string updatedTestCollectionName = "newTestCollection"; + byte[] updatedTestCollectionNameUtf8Bytes = System.Text.Encoding.UTF8.GetBytes(updatedTestCollectionName); + service.UpdateCollection( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "UpdateCollection result: {0}", response.Response); + collection = response.Result; + Assert.IsNotNull(collection.CollectionId); + Assert.IsTrue(collection.CollectionId == collectionId); + Assert.IsNull(error); + }, + collectionId: collectionId, + name: System.Text.Encoding.UTF8.GetString(updatedTestCollectionNameUtf8Bytes) + ); + + while (collection == null) + yield return null; + } + + [UnityTest, Order(99)] + public IEnumerator TestDeleteCollection() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Delete Collection..."); + bool isComplete = false; + service.DeleteCollection( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "DeleteCollection result: {0}", response.Response); + Assert.IsNotNull(response.Result); + Assert.IsTrue(response.StatusCode == 200); + isComplete = true; + }, + collectionId: collectionId + ); + + while (isComplete == true) + yield return null; + } + #endregion + + #region Images + [UnityTest, Order(6)] + public IEnumerator TestAddImage() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Add Images..."); + ImageDetailsList imageDetailsList = null; + List imagesFile = new List(); + using (FileStream fs1 = File.OpenRead(giraffeImageFilepath), fs2 = File.OpenRead(turtleImageFilepath)) + { + using (MemoryStream ms1 = new MemoryStream(), ms2 = new MemoryStream()) + { + fs1.CopyTo(ms1); + fs2.CopyTo(ms2); + FileWithMetadata fileWithMetadata = new FileWithMetadata() + { + Data = ms1, + ContentType = "image/jpeg", + Filename = Path.GetFileName(giraffeImageFilepath) + }; + imagesFile.Add(fileWithMetadata); + + FileWithMetadata fileWithMetadata2 = new FileWithMetadata() + { + Data = ms2, + ContentType = "image/jpeg", + Filename = Path.GetFileName(turtleImageFilepath) + }; + imagesFile.Add(fileWithMetadata2); + + service.AddImages( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "AddImages result: {0}", response.Response); + imageDetailsList = response.Result; + Assert.IsNotNull(imageDetailsList.Images); + Assert.IsTrue(imageDetailsList.Images.Count > 0); + Assert.IsNull(error); + imageId = imageDetailsList.Images[0].ImageId; + }, + collectionId: collectionId, + imagesFile: imagesFile + ); + + while (imageDetailsList == null) + yield return null; + } + } + } + [UnityTest, Order(7)] + public IEnumerator TestListImages() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to List Images..."); + ImageSummaryList imagesList = null; + service.ListImages( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "ListImages result: {0}", response.Response); + imagesList = response.Result; + Assert.IsNotNull(imagesList.Images); + Assert.IsTrue(imagesList.Images.Count > 0); + Assert.IsNull(error); + }, + collectionId: collectionId + ); + + while (imagesList == null) + yield return null; + } + + [UnityTest, Order(8)] + public IEnumerator TestGetImage() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get Image..."); + ImageDetails imageDetails = null; + service.GetImageDetails( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetImage result: {0}", response.Response); + imageDetails = response.Result; + Assert.IsNotNull(imageDetails); + Assert.IsTrue(imageDetails.ImageId == imageId); + Assert.IsNull(error); + }, + collectionId: collectionId, + imageId: imageId + ); + + while (imageDetails == null) + yield return null; + } + + [UnityTest, Order(9)] + public IEnumerator TestGetJpegImage() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Get Image..."); + bool isComplete = false; + service.GetJpegImage( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "GetImage result: {0}", response.Response); + Assert.IsNotNull(response.Result); + isComplete = true; + }, + collectionId: collectionId, + imageId: imageId + ); + + while (isComplete == true) + yield return null; + } + + [UnityTest, Order(98)] + public IEnumerator TestDeleteImage() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Delete Image..."); + bool isComplete = false; + service.DeleteImage( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "DeleteImage result: {0}", response.Response); + Assert.IsNotNull(response.Result); + Assert.IsTrue(response.StatusCode == 200); + isComplete = true; + }, + collectionId: collectionId, + imageId: imageId + ); + + while (isComplete == true) + yield return null; + } + #endregion + + #region Training Data + [UnityTest, Order(10)] + public IEnumerator TestAddImageTrainingData() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Add Image Training Data..."); + TrainingDataObjects trainingDataObjects = null; + var objectName = giraffeClassname; + List objects = new List() + { + new TrainingDataObject() + { + _Object = objectName, + Location = new Location() + { + Left = 27, + Top = 64, + Width = 75, + Height = 78 + } + + } + }; + service.AddImageTrainingData( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "AddImageTrainingData result: {0}", response.Response); + trainingDataObjects = response.Result; + Assert.IsNotNull(trainingDataObjects); + Assert.IsTrue(trainingDataObjects.Objects.Count > 0); + Assert.IsNull(error); + }, + collectionId: collectionId, + imageId: imageId, + objects: objects + ); + + while (trainingDataObjects == null) + yield return null; + } + + [UnityTest, Order(11)] + public IEnumerator TestTrain() + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Attempting to Train..."); + Collection collection = null; + service.Train( + callback: (DetailedResponse response, IBMError error) => + { + Log.Debug("VisualRecognitionServiceV4IntegrationTests", "Train result: {0}", response.Response); + collection = response.Result; + Assert.IsNotNull(collection); + Assert.IsTrue(collection.TrainingStatus.Objects.InProgress == true); + Assert.IsNull(error); + }, + collectionId: collectionId + ); + + while (collection == null) + yield return null; + } + #endregion + } +} diff --git a/Tests/VisualRecognitionV4IntegrationTests.cs.meta b/Tests/VisualRecognitionV4IntegrationTests.cs.meta new file mode 100644 index 000000000..56709d89d --- /dev/null +++ b/Tests/VisualRecognitionV4IntegrationTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1942de15e39b34bc8b5f8705c9b95a1a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: