From b5f3506fd408b9df46e3153bc8ca2860768978b0 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Wed, 7 Sep 2016 18:29:48 -0500 Subject: [PATCH 01/28] added mimetype to train and update classifier --- .../VisualRecognition/VisualRecognition.cs | 60 ++++++++++++++----- 1 file changed, 46 insertions(+), 14 deletions(-) diff --git a/Scripts/Services/VisualRecognition/VisualRecognition.cs b/Scripts/Services/VisualRecognition/VisualRecognition.cs index f35a24a1d..35a6ccb28 100755 --- a/Scripts/Services/VisualRecognition/VisualRecognition.cs +++ b/Scripts/Services/VisualRecognition/VisualRecognition.cs @@ -815,7 +815,7 @@ private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Respon /// Classifier name. /// Dictionary of class name and positive example paths. /// Negative example file path. - public bool TrainClassifier(OnTrainClassifier callback, string classifierName, Dictionary positiveExamples, string negativeExamplesPath = default(string), string customData = default(string)) + public bool TrainClassifier(OnTrainClassifier callback, string classifierName, Dictionary positiveExamples, string negativeExamplesPath = default(string), string mimeType = "application/zip", string customData = default(string)) { if (string.IsNullOrEmpty(mp_ApiKey)) mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID); @@ -851,7 +851,7 @@ private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Respon if (positiveExamplesData.Count == 0 || negativeExamplesData == null) Log.Error("VisualRecognition", "Failed to upload positive or negative examples!"); - return TrainClassifier(callback, classifierName, positiveExamplesData, negativeExamplesData, customData); + return TrainClassifier(callback, classifierName, positiveExamplesData, negativeExamplesData, mimeType, customData); } /// @@ -862,7 +862,7 @@ private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Respon /// Dictionary of class name and class training zip byte data. /// Negative examples zip byte data. /// - public bool TrainClassifier(OnTrainClassifier callback, string classifierName, Dictionary positiveExamplesData, byte[] negativeExamplesData = null, string customData = default(string)) + public bool TrainClassifier(OnTrainClassifier callback, string classifierName, Dictionary positiveExamplesData, byte[] negativeExamplesData = null, string mimeType = "application/zip", string customData = default(string)) { if (string.IsNullOrEmpty(mp_ApiKey)) mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID); @@ -887,10 +887,11 @@ private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Respon req.Parameters["version"] = VisualRecognitionVersion.Version; req.Forms = new Dictionary(); req.Forms["name"] = new RESTConnector.Form(classifierName); + foreach (KeyValuePair kv in positiveExamplesData) - req.Forms[kv.Key + "_positive_examples"] = new RESTConnector.Form(kv.Value, kv.Key + "_positive_examples.zip", "application/zip"); + req.Forms[kv.Key + "_positive_examples"] = new RESTConnector.Form(kv.Value, kv.Key + "_positive_examples" + GetExtension(mimeType), mimeType); if(negativeExamplesData != null) - req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamplesData, "negative_examples.zip", "application/zip"); + req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamplesData, "negative_examples" + GetExtension(mimeType), mimeType); return connector.Send(req); } @@ -905,6 +906,10 @@ public class TrainClassifierReq : RESTConnector.Request /// public string Data { get; set; } /// + /// Are the training files zip files or image files + /// + public bool IsZip { get; set; } + /// /// The OnTrainClassifier callback delegate. /// public OnTrainClassifier Callback { get; set; } @@ -949,7 +954,8 @@ private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Resp /// Classifier name. /// Dictionary of class name and positive example paths. /// Negative example file path. - public bool UpdateClassifier(OnTrainClassifier callback, string classifierID, string classifierName, Dictionary positiveExamples, string negativeExamplesPath = default(string), string customData = default(string)) + /// Mimetype of the file. Use GetMimeType to get Mimetype from filename. + public bool UpdateClassifier(OnTrainClassifier callback, string classifierID, string classifierName, Dictionary positiveExamples, string negativeExamplesPath = default(string), string mimeType = "application/zip", string customData = default(string)) { if (string.IsNullOrEmpty(mp_ApiKey)) mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID); @@ -987,7 +993,7 @@ private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Resp if (positiveExamplesData.Count == 0 && negativeExamplesData == null) Log.Error("VisualRecognition", "Failed to upload positive or negative examples!"); - return UpdateClassifier(callback, classifierID, classifierName, positiveExamplesData, negativeExamplesData, customData); + return UpdateClassifier(callback, classifierID, classifierName, positiveExamplesData, negativeExamplesData, mimeType, customData); } /// @@ -998,8 +1004,9 @@ private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Resp /// Classifier name. /// Dictionary of class name and class training zip byte data. /// Negative examples zip byte data. + /// Mimetype of the file. Use GetMimeType to get Mimetype from filename. /// - public bool UpdateClassifier(OnTrainClassifier callback, string classifierID, string classifierName, Dictionary positiveExamplesData, byte[] negativeExamplesData = null, string customData = default(string)) + public bool UpdateClassifier(OnTrainClassifier callback, string classifierID, string classifierName, Dictionary positiveExamplesData, byte[] negativeExamplesData = null, string mimeType = "application/zip", string customData = default(string)) { if (string.IsNullOrEmpty(mp_ApiKey)) mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID); @@ -1024,10 +1031,11 @@ private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Resp req.Parameters["version"] = VisualRecognitionVersion.Version; req.Forms = new Dictionary(); req.Forms["name"] = new RESTConnector.Form(classifierName); + foreach (KeyValuePair kv in positiveExamplesData) - req.Forms[kv.Key + "_positive_examples"] = new RESTConnector.Form(kv.Value, kv.Key + "_positive_examples.zip", "application/zip"); + req.Forms[kv.Key + "_positive_examples"] = new RESTConnector.Form(kv.Value, kv.Key + "_positive_examples" + GetExtension(mimeType), mimeType); if (negativeExamplesData != null) - req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamplesData, "negative_examples.zip", "application/zip"); + req.Forms["negative_examples"] = new RESTConnector.Form(negativeExamplesData, "negative_examples" + GetExtension(mimeType), mimeType); return connector.Send(req); } @@ -1112,11 +1120,35 @@ private string GetMimeType(string imagePath) return mimeType; } - #endregion - #region IWatsonService implementation - /// - public string GetServiceID() + private string GetExtension(string mimeType) + { + string extension = ""; + switch (mimeType) + { + case "image/jpeg": + extension = ".jpg"; + break; + case "image/png": + extension = ".png"; + break; + case "image/gif": + extension = ".gif"; + break; + case "application/zip": + extension = ".zip"; + break; + default: + throw new WatsonException("Cannot classify unsupported mime type " + mimeType); + } + + return extension; + } + #endregion + + #region IWatsonService implementation + /// + public string GetServiceID() { return SERVICE_ID; } From 843f5114511a016440568ad91817431864a6db5a Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Thu, 8 Sep 2016 09:30:13 -0500 Subject: [PATCH 02/28] updaetd inline documentation to account for mimetype --- .../VisualRecognition/VisualRecognition.cs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/Scripts/Services/VisualRecognition/VisualRecognition.cs b/Scripts/Services/VisualRecognition/VisualRecognition.cs index 35a6ccb28..97dab7240 100755 --- a/Scripts/Services/VisualRecognition/VisualRecognition.cs +++ b/Scripts/Services/VisualRecognition/VisualRecognition.cs @@ -815,6 +815,7 @@ private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Respon /// Classifier name. /// Dictionary of class name and positive example paths. /// Negative example file path. + /// Mime type of the positive examples and negative examples data. Use GetMimeType to get Mimetype from filename. public bool TrainClassifier(OnTrainClassifier callback, string classifierName, Dictionary positiveExamples, string negativeExamplesPath = default(string), string mimeType = "application/zip", string customData = default(string)) { if (string.IsNullOrEmpty(mp_ApiKey)) @@ -859,8 +860,9 @@ private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Respon /// /// Callback. /// Classifier name. - /// Dictionary of class name and class training zip byte data. - /// Negative examples zip byte data. + /// Dictionary of class name and class training zip or image byte data. + /// Negative examples zip or image byte data. + /// Mime type of the positive examples and negative examples data. /// public bool TrainClassifier(OnTrainClassifier callback, string classifierName, Dictionary positiveExamplesData, byte[] negativeExamplesData = null, string mimeType = "application/zip", string customData = default(string)) { @@ -906,10 +908,6 @@ public class TrainClassifierReq : RESTConnector.Request /// public string Data { get; set; } /// - /// Are the training files zip files or image files - /// - public bool IsZip { get; set; } - /// /// The OnTrainClassifier callback delegate. /// public OnTrainClassifier Callback { get; set; } @@ -1002,8 +1000,8 @@ private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Resp /// Callback. /// Classifier identifier. /// Classifier name. - /// Dictionary of class name and class training zip byte data. - /// Negative examples zip byte data. + /// Dictionary of class name and class training zip or image byte data. + /// Negative examples zip or image byte data. /// Mimetype of the file. Use GetMimeType to get Mimetype from filename. /// public bool UpdateClassifier(OnTrainClassifier callback, string classifierID, string classifierName, Dictionary positiveExamplesData, byte[] negativeExamplesData = null, string mimeType = "application/zip", string customData = default(string)) From b8e48dffd578d92a4cb7374bda1cd0c85339933d Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Fri, 9 Sep 2016 10:42:59 -0500 Subject: [PATCH 03/28] callback on null classifiers in service status check in visual recognition --- Scripts/Services/VisualRecognition/VisualRecognition.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Scripts/Services/VisualRecognition/VisualRecognition.cs b/Scripts/Services/VisualRecognition/VisualRecognition.cs index 97dab7240..1e5221d10 100755 --- a/Scripts/Services/VisualRecognition/VisualRecognition.cs +++ b/Scripts/Services/VisualRecognition/VisualRecognition.cs @@ -1215,6 +1215,10 @@ private void OnCheckServices(GetClassifiersTopLevelBrief classifiers, string cus else { Log.Debug("VisualRecognition", "Classifiers in null!"); + if (m_Callback != null && m_Callback.Target != null) + { + m_Callback(SERVICE_ID, false); + } } } else From 5a1886be5a9d0484a64e7bf1288c4bbc84b25b95 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Fri, 9 Sep 2016 15:19:33 -0500 Subject: [PATCH 04/28] access of ConfigLaded, public static function to clear APIKey from VR --- Scripts/Services/VisualRecognition/VisualRecognition.cs | 7 +++++++ Scripts/Utilities/Config.cs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) mode change 100644 => 100755 Scripts/Utilities/Config.cs diff --git a/Scripts/Services/VisualRecognition/VisualRecognition.cs b/Scripts/Services/VisualRecognition/VisualRecognition.cs index 1e5221d10..2b1ceb570 100755 --- a/Scripts/Services/VisualRecognition/VisualRecognition.cs +++ b/Scripts/Services/VisualRecognition/VisualRecognition.cs @@ -100,6 +100,13 @@ public class VisualRecognition : IWatsonService private const float REQUEST_TIMEOUT = 10.0f * 60.0f; #endregion + #region Public Functions + public static void ClearApiKey() + { + mp_ApiKey = default(string); + } + #endregion + #region Classify Image /// /// Classifies image specified by URL. diff --git a/Scripts/Utilities/Config.cs b/Scripts/Utilities/Config.cs old mode 100644 new mode 100755 index 3282d5dc3..b4f8db653 --- a/Scripts/Utilities/Config.cs +++ b/Scripts/Utilities/Config.cs @@ -174,7 +174,7 @@ public bool HasAPIKey() /// Returns true if the configuration is loaded or not. /// [fsIgnore] - public bool ConfigLoaded { get; private set; } + public bool ConfigLoaded { get; set; } /// /// Returns the singleton instance. /// From 28cdabe308889e959bad083150e3e424056ce886 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Mon, 12 Sep 2016 11:36:20 -0500 Subject: [PATCH 05/28] expose setting RequestedWidth, RequestedHeight and RequestedFPS in the WebCamWidget. --- Scripts/Widgets/WebCamWidget.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Scripts/Widgets/WebCamWidget.cs b/Scripts/Widgets/WebCamWidget.cs index caa5f2e34..47d9e3e59 100755 --- a/Scripts/Widgets/WebCamWidget.cs +++ b/Scripts/Widgets/WebCamWidget.cs @@ -139,6 +139,7 @@ public WebCamTexture WebCamTexture public int RequestedWidth { get { return m_RequestedWidth; } + set { m_RequestedWidth = value; } } /// /// The requested height of the WebCamTexture. @@ -146,6 +147,7 @@ public int RequestedWidth public int RequestedHeight { get { return m_RequestedHeight; } + set { m_RequestedHeight = value; } } /// @@ -154,6 +156,7 @@ public int RequestedHeight public int RequestedFPS { get { return m_RequestedFPS; } + set { m_RequestedFPS = value; } } #endregion From 9b6f20b03d2ab235ca4a25767b686fc279044ee8 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 13 Sep 2016 23:11:18 -0500 Subject: [PATCH 06/28] Exposed set RawImage in WebCamDisplayWidget --- Scripts/Widgets/WebCamDisplayWidget.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Scripts/Widgets/WebCamDisplayWidget.cs b/Scripts/Widgets/WebCamDisplayWidget.cs index 1fb22e777..d9e855730 100755 --- a/Scripts/Widgets/WebCamDisplayWidget.cs +++ b/Scripts/Widgets/WebCamDisplayWidget.cs @@ -60,6 +60,7 @@ public class WebCamDisplayWidget : Widget public RawImage RawImage { get { return m_RawImage; } + set { m_RawImage = RawImage; } } /// /// The Material displaying the WebCam stream on Geometry. From cbcbf0e6ac7cd4fadbdcafefcd93bc3eca8705f9 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 13 Sep 2016 23:12:14 -0500 Subject: [PATCH 07/28] fixed mistake on last commit --- Scripts/Widgets/WebCamDisplayWidget.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Scripts/Widgets/WebCamDisplayWidget.cs b/Scripts/Widgets/WebCamDisplayWidget.cs index d9e855730..069e6ef8e 100755 --- a/Scripts/Widgets/WebCamDisplayWidget.cs +++ b/Scripts/Widgets/WebCamDisplayWidget.cs @@ -60,7 +60,7 @@ public class WebCamDisplayWidget : Widget public RawImage RawImage { get { return m_RawImage; } - set { m_RawImage = RawImage; } + set { m_RawImage = value; } } /// /// The Material displaying the WebCam stream on Geometry. From 91d53b64031b696d899a5a6947cfa04c3dd4aa2d Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Mon, 24 Oct 2016 15:10:02 -0500 Subject: [PATCH 08/28] example of stt streaming --- .../ServiceExamples/ExampleStreaming.unity | 282 ++++++++++++++++++ .../ExampleStreaming.unity.meta | 8 + .../Scripts/ExampleStreaming.cs | 168 +++++++++++ .../Scripts/ExampleStreaming.cs.meta | 12 + 4 files changed, 470 insertions(+) create mode 100755 Examples/ServiceExamples/ExampleStreaming.unity create mode 100755 Examples/ServiceExamples/ExampleStreaming.unity.meta create mode 100755 Examples/ServiceExamples/Scripts/ExampleStreaming.cs create mode 100755 Examples/ServiceExamples/Scripts/ExampleStreaming.cs.meta diff --git a/Examples/ServiceExamples/ExampleStreaming.unity b/Examples/ServiceExamples/ExampleStreaming.unity new file mode 100755 index 000000000..2d5d7cffd --- /dev/null +++ b/Examples/ServiceExamples/ExampleStreaming.unity @@ -0,0 +1,282 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +SceneSettings: + m_ObjectHideFlags: 0 + m_PVSData: + m_PVSObjectsArray: [] + m_PVSPortalsArray: [] + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 7 + 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_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.4469244, g: 0.4967847, b: 0.575083, a: 1} +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 7 + m_GIWorkflowMode: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_TemporalCoherenceThreshold: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 1 + m_LightmapEditorSettings: + serializedVersion: 4 + m_Resolution: 2 + m_BakeResolution: 40 + m_TextureWidth: 1024 + m_TextureHeight: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_DirectLightInLightProbes: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_LightingDataAsset: {fileID: 0} + m_RuntimeCPUUsage: 25 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + accuratePlacement: 0 + minRegionArea: 2 + cellSize: 0.16666667 + manualCellSize: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &1159842907 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 1159842909} + - 108: {fileID: 1159842908} + m_Layer: 0 + m_Name: Directional Light + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!108 &1159842908 +Light: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1159842907} + m_Enabled: 1 + serializedVersion: 7 + 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_CookieSize: 10 + m_Shadows: + m_Type: 2 + m_Resolution: -1 + m_CustomResolution: -1 + m_Strength: 1 + m_Bias: 0.05 + m_NormalBias: 0.4 + m_NearPlane: 0.2 + m_Cookie: {fileID: 0} + m_DrawHalo: 0 + m_Flare: {fileID: 0} + m_RenderMode: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_Lightmapping: 4 + m_AreaSize: {x: 1, y: 1} + m_BounceIntensity: 1 + m_ShadowRadius: 0 + m_ShadowAngle: 0 +--- !u!4 &1159842909 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1159842907} + m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261} + m_LocalPosition: {x: 0, y: 3, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_LocalEulerAnglesHint: {x: 50, y: -30, z: 0} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 1 +--- !u!1 &1391086061 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 1391086066} + - 20: {fileID: 1391086065} + - 92: {fileID: 1391086064} + - 124: {fileID: 1391086063} + - 81: {fileID: 1391086062} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &1391086062 +AudioListener: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1391086061} + m_Enabled: 1 +--- !u!124 &1391086063 +Behaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1391086061} + m_Enabled: 1 +--- !u!92 &1391086064 +Behaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1391086061} + m_Enabled: 1 +--- !u!20 &1391086065 +Camera: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1391086061} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 1 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 + m_StereoMirrorMode: 0 +--- !u!4 &1391086066 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1391086061} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 1, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 +--- !u!1 &1646685149 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 1646685151} + - 114: {fileID: 1646685150} + m_Layer: 0 + m_Name: ExampleStreaming + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1646685150 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1646685149} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 6c5299c1c838a8c44b49ecc9254704e0, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &1646685151 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 1646685149} + 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 diff --git a/Examples/ServiceExamples/ExampleStreaming.unity.meta b/Examples/ServiceExamples/ExampleStreaming.unity.meta new file mode 100755 index 000000000..7873c0333 --- /dev/null +++ b/Examples/ServiceExamples/ExampleStreaming.unity.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 57c7b454bb032a34fa0f938231dba758 +timeCreated: 1477325083 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ServiceExamples/Scripts/ExampleStreaming.cs b/Examples/ServiceExamples/Scripts/ExampleStreaming.cs new file mode 100755 index 000000000..4ba1e19e6 --- /dev/null +++ b/Examples/ServiceExamples/Scripts/ExampleStreaming.cs @@ -0,0 +1,168 @@ +/** +* Copyright 2015 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 UnityEngine; +using System.Collections; +using IBM.Watson.DeveloperCloud.Logging; +using IBM.Watson.DeveloperCloud.Services.SpeechToText.v1; +using IBM.Watson.DeveloperCloud.Utilities; +using IBM.Watson.DeveloperCloud.DataTypes; + +public class ExampleStreaming : MonoBehaviour +{ + private int m_RecordingRoutine = 0; + + + private string m_MicrophoneID = null; + private AudioClip m_Recording = null; + private int m_RecordingBufferSize = 2; + private int m_RecordingHZ = 22050; + + + private SpeechToText m_SpeechToText = new SpeechToText(); + + void Start() + { + LogSystem.InstallDefaultReactors(); + Log.Debug("ExampleStreaming", "Start();"); + + Active = true; + + StartRecording(); + } + + public bool Active + { + get { return m_SpeechToText.IsListening; } + set { + if ( value && !m_SpeechToText.IsListening ) + { + m_SpeechToText.DetectSilence = true; + m_SpeechToText.EnableWordConfidence = false; + m_SpeechToText.EnableTimestamps = false; + m_SpeechToText.SilenceThreshold = 0.03f; + m_SpeechToText.MaxAlternatives = 1; + m_SpeechToText.EnableContinousRecognition = true; + m_SpeechToText.EnableInterimResults = true; + m_SpeechToText.OnError = OnError; + m_SpeechToText.StartListening( OnRecognize ); + } + else if ( !value && m_SpeechToText.IsListening ) + { + m_SpeechToText.StopListening(); + } + } + } + + private void StartRecording() + { + if (m_RecordingRoutine == 0) + { + UnityObjectUtil.StartDestroyQueue(); + m_RecordingRoutine = Runnable.Run(RecordingHandler()); + } + } + + private void StopRecording() + { + if (m_RecordingRoutine != 0) + { + Microphone.End(m_MicrophoneID); + Runnable.Stop(m_RecordingRoutine); + m_RecordingRoutine = 0; + } + } + + private void OnError( string error ) + { + Active = false; + + Log.Debug("ExampleStreaming", "Error! {0}", error); + } + + private IEnumerator RecordingHandler() + { + m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ); + yield return null; // let m_RecordingRoutine get set.. + + if (m_Recording == null) + { + StopRecording(); + yield break; + } + + bool bFirstBlock = true; + int midPoint = m_Recording.samples / 2; + float[] samples = null; + + while (m_RecordingRoutine != 0 && m_Recording != null) + { + int writePos = Microphone.GetPosition(m_MicrophoneID); + if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID)) + { + Log.Error("MicrophoneWidget", "Microphone disconnected."); + + StopRecording(); + yield break; + } + + if ((bFirstBlock && writePos >= midPoint) + || (!bFirstBlock && writePos < midPoint)) + { + // front block is recorded, make a RecordClip and pass it onto our callback. + samples = new float[midPoint]; + m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint); + + AudioData record = new AudioData(); + record.MaxLevel = Mathf.Max(samples); + record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false); + record.Clip.SetData(samples, 0); + + m_SpeechToText.OnListen(record); + + bFirstBlock = !bFirstBlock; + } + else + { + // calculate the number of samples remaining until we ready for a block of audio, + // and wait that amount of time it will take to record. + int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos); + float timeRemaining = (float)remaining / (float)m_RecordingHZ; + + yield return new WaitForSeconds(timeRemaining); + } + + } + + yield break; + } + + private void OnRecognize(SpeechRecognitionEvent result) + { + if (result != null && result.results.Length > 0) + { + foreach (var res in result.results) + { + foreach (var alt in res.alternatives) + { + string text = alt.transcript; + Log.Debug("ExampleStreaming", string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); + } + } + } + } +} \ No newline at end of file diff --git a/Examples/ServiceExamples/Scripts/ExampleStreaming.cs.meta b/Examples/ServiceExamples/Scripts/ExampleStreaming.cs.meta new file mode 100755 index 000000000..a7a574279 --- /dev/null +++ b/Examples/ServiceExamples/Scripts/ExampleStreaming.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6c5299c1c838a8c44b49ecc9254704e0 +timeCreated: 1477325099 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 7ea8f3b6a4885589c1d5bed70c99ce27eec32157 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Mon, 24 Oct 2016 16:15:50 -0500 Subject: [PATCH 09/28] split personality insights directory to v2 and v3. v3 data models --- Scripts/Services/PersonalityInsights.meta | 4 +- Scripts/Services/PersonalityInsights/v2.meta | 9 + .../{ => v2}/DataModels.cs | 0 .../{ => v2}/DataModels.cs.meta | 0 .../{ => v2}/PersonalityInsights.cs | 0 .../{ => v2}/PersonalityInsights.cs.meta | 0 Scripts/Services/PersonalityInsights/v3.meta | 9 + .../PersonalityInsights/v3/DataModels.cs | 217 ++++++++++++++++++ .../PersonalityInsights/v3/DataModels.cs.meta | 12 + 9 files changed, 249 insertions(+), 2 deletions(-) mode change 100644 => 100755 Scripts/Services/PersonalityInsights.meta create mode 100755 Scripts/Services/PersonalityInsights/v2.meta rename Scripts/Services/PersonalityInsights/{ => v2}/DataModels.cs (100%) rename Scripts/Services/PersonalityInsights/{ => v2}/DataModels.cs.meta (100%) rename Scripts/Services/PersonalityInsights/{ => v2}/PersonalityInsights.cs (100%) rename Scripts/Services/PersonalityInsights/{ => v2}/PersonalityInsights.cs.meta (100%) create mode 100755 Scripts/Services/PersonalityInsights/v3.meta create mode 100755 Scripts/Services/PersonalityInsights/v3/DataModels.cs create mode 100755 Scripts/Services/PersonalityInsights/v3/DataModels.cs.meta diff --git a/Scripts/Services/PersonalityInsights.meta b/Scripts/Services/PersonalityInsights.meta old mode 100644 new mode 100755 index 1cb0df67c..e0bf9a66e --- a/Scripts/Services/PersonalityInsights.meta +++ b/Scripts/Services/PersonalityInsights.meta @@ -1,7 +1,7 @@ fileFormatVersion: 2 -guid: 242af859faf584a358c9b61be5e6bec9 +guid: 0fa8368d9623dd540a2b4335cd54f1f2 folderAsset: yes -timeCreated: 1466518852 +timeCreated: 1477341989 licenseType: Pro DefaultImporter: userData: diff --git a/Scripts/Services/PersonalityInsights/v2.meta b/Scripts/Services/PersonalityInsights/v2.meta new file mode 100755 index 000000000..2385f7904 --- /dev/null +++ b/Scripts/Services/PersonalityInsights/v2.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: eab5726e71362cb4781cf8adc03abd4c +folderAsset: yes +timeCreated: 1477342154 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/PersonalityInsights/DataModels.cs b/Scripts/Services/PersonalityInsights/v2/DataModels.cs similarity index 100% rename from Scripts/Services/PersonalityInsights/DataModels.cs rename to Scripts/Services/PersonalityInsights/v2/DataModels.cs diff --git a/Scripts/Services/PersonalityInsights/DataModels.cs.meta b/Scripts/Services/PersonalityInsights/v2/DataModels.cs.meta similarity index 100% rename from Scripts/Services/PersonalityInsights/DataModels.cs.meta rename to Scripts/Services/PersonalityInsights/v2/DataModels.cs.meta diff --git a/Scripts/Services/PersonalityInsights/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs similarity index 100% rename from Scripts/Services/PersonalityInsights/PersonalityInsights.cs rename to Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs diff --git a/Scripts/Services/PersonalityInsights/PersonalityInsights.cs.meta b/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs.meta similarity index 100% rename from Scripts/Services/PersonalityInsights/PersonalityInsights.cs.meta rename to Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs.meta diff --git a/Scripts/Services/PersonalityInsights/v3.meta b/Scripts/Services/PersonalityInsights/v3.meta new file mode 100755 index 000000000..10012734a --- /dev/null +++ b/Scripts/Services/PersonalityInsights/v3.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: d57285b561f6fb24d8e367fcb5f4ef79 +folderAsset: yes +timeCreated: 1477342161 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/Services/PersonalityInsights/v3/DataModels.cs b/Scripts/Services/PersonalityInsights/v3/DataModels.cs new file mode 100755 index 000000000..6d1ee9226 --- /dev/null +++ b/Scripts/Services/PersonalityInsights/v3/DataModels.cs @@ -0,0 +1,217 @@ +/** +* Copyright 2015 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 UnityEngine; +using System.Collections; + +namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3 +{ + /// + /// The Profile object. + /// + [SerializeField] + public class Profile + { + /// + /// The language model that was used to process the input; for example, en. + /// + public string processed_language { get; set; } + /// + /// The number of words that were found in the input. + /// + public int word_count { get; set; } + /// + /// When guidance is appropriate, a string that provides a message that indicates + /// the number of words found and where that value falls in the range of required + /// or suggested number of words. + /// + public string word_count_message { get; set; } + /// + /// Detailed results for the Big Five personality characteristics (dimensions and + /// facets) inferred from the input text. + /// + public TraitTreeNode[] personality { get; set; } + /// + /// Detailed results for the Needs characteristics inferred from the input text. + /// + public TraitTreeNode[] values { get; set; } + /// + /// Detailed results for the Values characteristics inferred from the input text. + /// + public TraitTreeNode[] needs { get; set; } + /// + /// For JSON content that is timestamped, detailed results about the social behavior + /// disclosed by the input in terms of temporal characteristics. The results include + /// information about the distribution of the content over the days of the week and + /// the hours of the day. + /// + public TraitTreeNode[] behavior { get; set; } + /// + /// If the consumption_preferences query parameter is true, detailed results for + /// each category of `consumption preferences`. Each element of the array provides + /// information inferred from the input text for the individual preferences of that + /// category. + /// + public ConsumptionPreferencesCategoryNode[] consumption_preferences { get; set; } + /// + /// Warning messages associated with the input text submitted with the request. The + /// array is empty if the input generated no warnings. + /// + public Warning[] warning { get; set; } + } + + /// + /// The Trait Tree Node object. + /// + [SerializeField] + public class TraitTreeNode + { + /// + /// The unique identifier of the characteristic to which the results pertain. IDs + /// have the form `big5_` for Big Five personality characteristics, `need_` for Needs, + /// or `value_` for Values. + /// + public string trait_id { get; set; } + /// + /// The user-visible name of the characteristic. + /// + public string name { get; set; } + /// + /// The category of the characteristic: personality for Big Five `personality` + /// characteristics, `needs` for Needs, or `values` for Values. + /// + public string category { get; set; } + /// + /// The normalized percentile score for the characteristic. The range is 0 to 1. For + /// example, if the percentage for Openness is 0.60, the author scored in the 60th + /// percentile; the author is more open than 59 percent of the population and less open + /// than 39 percent of the population. + /// + public double percentile { get; set; } + /// + /// The raw score for the characteristic. A positive or negative score indicates more + /// or less of the characteristic; zero indicates neutrality or no evidence for a + /// score. The raw score is computed based on the input and the service model; it is + /// not normalized or compared with a sample population. The raw score enables + /// comparison of the results against a different sampling population and with a custom + /// normalization approach. + /// + public double raw_score { get; set; } + /// + /// For `personality` (Big Five) dimensions, more detailed results for the facets of + /// each dimension as inferred from the input text. + /// + public TraitTreeNode[] children { get; set; } + } + + /// + /// The Behavior Node object. + /// + [SerializeField] + public class BehaviorNode + { + /// + /// The unique identifier of the characteristic to which the results pertain. IDs have + /// the form `behavior_`. + /// + public string trait_id { get; set; } + /// + /// The user-visible name of the characteristic. + /// + public string name { get; set; } + /// + /// The category of the characteristic: behavior for temporal data. + /// + public string category { get; set; } + /// + /// For JSON content that is timestamped, the percentage of timestamped input data + /// that occurred during that day of the week or hour of the day. The range is 0 to 1. + /// + public double percentage { get; set; } + } + + /// + /// The Consumption Preferences Category Node object. + /// + [SerializeField] + public class ConsumptionPreferencesCategoryNode + { + /// + /// The unique identifier of the consumption preferences category to which the results + /// pertain. IDs have the form `consumption_preferences_`. + /// + public string consumption_preference_category_id { get; set; } + /// + /// The user-visible name of the consumption preferences category. + /// + public string name { get; set; } + /// + /// Detailed results inferred from the input text for the individual preferences of + /// the category. + /// + public ConsumptionPreferencesCategoryNode[] consumption_preferences { get; set; } + } + + /// + /// The Warning Object. + /// + [SerializeField] + public class Warning + { + /// + /// The identifier of the warning message, one of `WORD_COUNT_MESSAGE`, `JSON_AS_TEXT`, + /// or `PARTIAL_TEXT_USED`. + /// + public string warning_id { get; set; } + /// + /// The message associated with the `warning_id`. For `WORD_COUNT_MESSAGE`, "There were + /// words in the input. We need a minimum of 600, preferably 1,200 or more, to + /// compute statistically significant estimates."; for `JSON_AS_TEXT`, "Request input + /// was processed as text/plain as indicated, however detected a JSON input. Did you + /// mean application/json?"; and for `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." The `PARTIAL_TEXT_USED` + /// warning applies only when Arabic input text exceeds a threshold at which additional + /// words do not contribute to the accuracy of the profile. + /// + public string message { get; set; } + } + + /// + /// The Consumption Preferences Node object. + /// + [SerializeField] + public class ConsumptionPreferencesNode + { + /// + /// The unique identifier of the consumption preference to which the results pertain. + /// IDs have the form `consumption_preferences_`. + /// + public string consumption_preference_id { get; set; } + /// + /// The user-visible name of the consumption preference. + /// + public string name { get; set; } + /// + /// The score for the consumption preference: `0.0` indicates unlikely, `0.5` indicates + /// neutrality, and `1.0` indicates likely. The scores for some preferences are binary and + /// do not allow a neutral value. The score is an indication of preference based on the + /// results inferred from the input text, not a normalized percentile. + /// + public double score { get; set; } + } +} diff --git a/Scripts/Services/PersonalityInsights/v3/DataModels.cs.meta b/Scripts/Services/PersonalityInsights/v3/DataModels.cs.meta new file mode 100755 index 000000000..c6794e4c0 --- /dev/null +++ b/Scripts/Services/PersonalityInsights/v3/DataModels.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4b008bf955ac4074f8bdd08d46ecd0c7 +timeCreated: 1477342206 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 6e266e9a73fa10c90e9b5604b9345047e15f6254 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 11:43:34 -0500 Subject: [PATCH 10/28] personality insights v3 GetProfile and UnitTest --- Scripts/Editor/ConfigEditor.cs | 8 +- .../v2/PersonalityInsights.cs | 1 - .../PersonalityInsights/v3/DataModels.cs | 59 +++++- .../v3/PersonalityInsights.cs | 179 ++++++++++++++++ .../v3/PersonalityInsights.cs.meta | 12 ++ ...sights.cs => TestPersonalityInsightsV2.cs} | 40 ++-- ...meta => TestPersonalityInsightsV2.cs.meta} | 0 .../UnitTests/TestPersonalityInsightsV3.cs | 197 ++++++++++++++++++ .../TestPersonalityInsightsV3.cs.meta | 12 ++ 9 files changed, 482 insertions(+), 26 deletions(-) create mode 100644 Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs create mode 100644 Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs.meta rename Scripts/UnitTests/{TestPersonalityInsights.cs => TestPersonalityInsightsV2.cs} (85%) rename Scripts/UnitTests/{TestPersonalityInsights.cs.meta => TestPersonalityInsightsV2.cs.meta} (100%) create mode 100644 Scripts/UnitTests/TestPersonalityInsightsV3.cs create mode 100644 Scripts/UnitTests/TestPersonalityInsightsV3.cs.meta diff --git a/Scripts/Editor/ConfigEditor.cs b/Scripts/Editor/ConfigEditor.cs index 3cf935136..831f25853 100755 --- a/Scripts/Editor/ConfigEditor.cs +++ b/Scripts/Editor/ConfigEditor.cs @@ -57,14 +57,16 @@ private class ServiceSetup //new ServiceSetup() { ServiceName = "Language Translator", ServiceAPI = "language-translator/api", // URL ="https://console.ng.bluemix.net/catalog/services/language-translator/", ServiceID="LanguageTranslatorV1" }, new ServiceSetup() { ServiceName = "Natural Language Classifier", ServiceAPI = "natural-language-classifier/api", - URL ="https://console.ng.bluemix.net/catalog/natural-language-classifier/", ServiceID="NaturalLanguageClassifierV1" }, + URL ="https://console.ng.bluemix.net/catalog/natural-language-classifier/", ServiceID="NaturalLanguageClassifierV1" }, new ServiceSetup() { ServiceName = "Tone Analyzer", ServiceAPI = "tone-analyzer/api", URL ="https://console.ng.bluemix.net/catalog/services/tone-analyzer/", ServiceID="ToneAnalyzerV3" }, new ServiceSetup() { ServiceName = "Tradeoff Analytics", ServiceAPI = "tradeoff-analytics/api", URL ="https://console.ng.bluemix.net/catalog/services/tradeoff-analytics/", ServiceID="TradeoffAnalyticsV1" }, - new ServiceSetup() { ServiceName = "Personality Insights", ServiceAPI = "personality-insights/api", + new ServiceSetup() { ServiceName = "Personality Insights V2", ServiceAPI = "personality-insights/api", URL ="https://console.ng.bluemix.net/catalog/services/personality-insights/", ServiceID="PersonalityInsightsV2" }, - new ServiceSetup() { ServiceName = "Conversation", ServiceAPI = "conversation/api", + new ServiceSetup() { ServiceName = "Personality Insights V3", ServiceAPI = "personality-insights/api", + URL ="https://console.ng.bluemix.net/catalog/services/personality-insights/", ServiceID="PersonalityInsightsV3" }, + new ServiceSetup() { ServiceName = "Conversation", ServiceAPI = "conversation/api", URL ="https://console.ng.bluemix.net/catalog/services/conversation/", ServiceID="ConversationV1" }, new ServiceSetup() { ServiceName = "RetrieveAndRank", ServiceAPI = "retrieve-and-rank/api", URL ="https://console.ng.bluemix.net/catalog/services/retrieve-and-rank/", ServiceID="RetrieveAndRankV1" }, diff --git a/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs index 2ee6c8370..48b477c9a 100755 --- a/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs +++ b/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs @@ -20,7 +20,6 @@ using System.Text; using IBM.Watson.DeveloperCloud.Utilities; using UnityEngine; -using System.Collections; using System; using IBM.Watson.DeveloperCloud.Logging; using System.IO; diff --git a/Scripts/Services/PersonalityInsights/v3/DataModels.cs b/Scripts/Services/PersonalityInsights/v3/DataModels.cs index 6d1ee9226..b397426b9 100755 --- a/Scripts/Services/PersonalityInsights/v3/DataModels.cs +++ b/Scripts/Services/PersonalityInsights/v3/DataModels.cs @@ -59,7 +59,7 @@ public class Profile /// information about the distribution of the content over the days of the week and /// the hours of the day. /// - public TraitTreeNode[] behavior { get; set; } + public BehaviorNode[] behavior { get; set; } /// /// If the consumption_preferences query parameter is true, detailed results for /// each category of `consumption preferences`. Each element of the array provides @@ -163,7 +163,7 @@ public class ConsumptionPreferencesCategoryNode /// Detailed results inferred from the input text for the individual preferences of /// the category. /// - public ConsumptionPreferencesCategoryNode[] consumption_preferences { get; set; } + public ConsumptionPreferencesNode[] consumption_preferences { get; set; } } /// @@ -214,4 +214,59 @@ public class ConsumptionPreferencesNode /// public double score { get; set; } } + + /// + /// The content type. Either text, html or json. + /// + public class ContentType + { + /// + /// Mime type for plain text. + /// + public const string TEXT_PLAIN = "text/plain"; + + /// + /// Mime type for HTML. + /// + public const string TEXT_HTML = "text/html"; + + /// + /// Mime type for json. + /// + public const string APPLICATION_JSON = "application/json"; + } + + /// + /// The content language. Either English, Arabic, Spanish or Japanese. + /// + public class Language + { + /// + /// English. + /// + public const string ENGLISH = "en"; + /// + /// Arabic. + /// + public const string ARABIC = "ar"; + /// + /// Spanish. + /// + public const string SPANISH = "es"; + /// + /// Japanese + /// + public const string JAPANESE = "ja"; + } + + /// + /// The Personality Insights version. + /// + public class PersonalityInsightsVersion + { + /// + /// The version. + /// + public const string Version = "2016-10-20"; + } } diff --git a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs new file mode 100644 index 000000000..cfdef36b9 --- /dev/null +++ b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs @@ -0,0 +1,179 @@ +/** +* Copyright 2015 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 FullSerializer; +using IBM.Watson.DeveloperCloud.Connection; +using IBM.Watson.DeveloperCloud.Logging; +using IBM.Watson.DeveloperCloud.Utilities; +using System; +using System.IO; +using System.Text; +using UnityEngine; + +namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3 +{ + /// + /// This class wraps the Personality Insights service. + /// Personality Insights Service + /// + public class PersonalityInsights : IWatsonService + { + #region Private Data + private const string SERVICE_ID = "PersonalityInsightsV3"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Profile + private const string SERVICE_GET_PROFILE = "/v3/profile"; + + public delegate void OnGetProfile(Profile profile, string data); + + public bool GetProfile(OnGetProfile callback, string source, + string contentType = ContentType.TEXT_PLAIN, + string contentLanguage = Language.ENGLISH, + string accept = ContentType.APPLICATION_JSON, + string acceptLanguage = Language.ENGLISH, + bool raw_scores = false, + bool csv_headers = false, + bool consumption_preferences = false, + string version = PersonalityInsightsVersion.Version, + string data = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new ArgumentNullException("A JSON or Text source is required for GetProfile!"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_PROFILE); + if (connector == null) + return false; + + GetProfileRequest req = new GetProfileRequest(); + req.Source = source; + req.Callback = callback; + req.Data = data; + req.OnResponse = GetProfileResponse; + + req.Parameters["raw_scores"] = raw_scores.ToString(); + req.Parameters["csv_headers"] = csv_headers.ToString(); + req.Parameters["consumption_preferences"] = consumption_preferences.ToString(); + req.Parameters["version"] = version; + + req.Headers["Content-Type"] = contentType; + req.Headers["Content-Language"] = contentLanguage; + req.Headers["Accept"] = accept; + req.Headers["Accept-Language"] = acceptLanguage; + + if (source.StartsWith(Application.dataPath)) + { + string jsonData = default(string); + jsonData = File.ReadAllText(source); + req.Send = System.Text.Encoding.UTF8.GetBytes(jsonData); + } + else + { + req.Send = System.Text.Encoding.UTF8.GetBytes(source); + } + + return connector.Send(req); + } + + /// + /// Get profile request. + /// + public class GetProfileRequest : RESTConnector.Request + { + /// + /// The source string. + /// + public string Source { get; set; } + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetProfile Callback { get; set; } + } + + private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Profile response = new Profile(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetProfileRequest)req).Callback != null) + ((GetProfileRequest)req).Callback(resp.Success ? response : null, ((GetProfileRequest)req).Data); + } + #endregion + + #region IWatsonService implementation + public string GetServiceID() + { + return SERVICE_ID; + } + + public void GetServiceStatus(ServiceStatus callback) + { + if (Utilities.Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + private class CheckServiceStatus + { + private PersonalityInsights m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(PersonalityInsights service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + if (!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, Language.ENGLISH)) + m_Callback(SERVICE_ID, false); + } + + private void OnGetProfile(Profile resp, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, resp != null); + } + } + #endregion + } +} \ No newline at end of file diff --git a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs.meta b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs.meta new file mode 100644 index 000000000..342fc5f5c --- /dev/null +++ b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f3362ea0537127044a68045b63ebc260 +timeCreated: 1477407311 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Scripts/UnitTests/TestPersonalityInsights.cs b/Scripts/UnitTests/TestPersonalityInsightsV2.cs similarity index 85% rename from Scripts/UnitTests/TestPersonalityInsights.cs rename to Scripts/UnitTests/TestPersonalityInsightsV2.cs index c965a805f..3f53293f2 100644 --- a/Scripts/UnitTests/TestPersonalityInsights.cs +++ b/Scripts/UnitTests/TestPersonalityInsightsV2.cs @@ -23,7 +23,7 @@ namespace IBM.Watson.DeveloperCloud.UnitTests { - public class TestPersonalityInsights : UnitTest { + public class TestPersonalityInsightsV2 : UnitTest { PersonalityInsights m_personalityInsights = new PersonalityInsights(); private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; @@ -38,12 +38,12 @@ public override IEnumerator RunTest() if ( Utilities.Config.Instance.FindCredentials( m_personalityInsights.GetServiceID() ) == null ) yield break; - Log.Debug("TestPersonalityInsights", "Attempting GetProfile using Text!"); + Log.Debug("TestPersonalityInsightsV2", "Attempting GetProfile using Text!"); m_personalityInsights.GetProfile(OnGetProfileText, testString); while(!m_GetProfileTextTested) yield return null; - Log.Debug("TestPersonalityInsights", "Attempting GetProfile using Json!"); + Log.Debug("TestPersonalityInsightsV2", "Attempting GetProfile using Json!"); m_personalityInsights.GetProfile(OnGetProfileJson, dataPath); while(!m_GetProfileJsonTested) yield return null; @@ -58,15 +58,15 @@ private void OnGetProfileText(Profile profile, string data) if(profile != null) { if(!string.IsNullOrEmpty(profile.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", profile.id); + Log.Debug("TestPersonalityInsightsV2", "id: {0}", profile.id); if(!string.IsNullOrEmpty(profile.source)) - Log.Debug("ExamplePersonalityInsights", "source: {0}", profile.source); + Log.Debug("TestPersonalityInsightsV2", "source: {0}", profile.source); if(!string.IsNullOrEmpty(profile.processed_lang)) - Log.Debug("ExamplePersonalityInsights", "proccessed_lang: {0}", profile.processed_lang); + Log.Debug("TestPersonalityInsightsV2", "proccessed_lang: {0}", profile.processed_lang); if(!string.IsNullOrEmpty(profile.word_count)) - Log.Debug("ExamplePersonalityInsights", "word_count: {0}", profile.word_count); + Log.Debug("TestPersonalityInsightsV2", "word_count: {0}", profile.word_count); if(!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("ExamplePersonalityInsights", "word_count_message: {0}", profile.word_count_message); + Log.Debug("TestPersonalityInsightsV2", "word_count_message: {0}", profile.word_count_message); if(profile.tree != null) { @@ -84,15 +84,15 @@ private void OnGetProfileJson(Profile profile, string data) if(profile != null) { if(!string.IsNullOrEmpty(profile.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", profile.id); + Log.Debug("TestPersonalityInsightsV2", "id: {0}", profile.id); if(!string.IsNullOrEmpty(profile.source)) - Log.Debug("ExamplePersonalityInsights", "source: {0}", profile.source); + Log.Debug("TestPersonalityInsightsV2", "source: {0}", profile.source); if(!string.IsNullOrEmpty(profile.processed_lang)) - Log.Debug("ExamplePersonalityInsights", "proccessed_lang: {0}", profile.processed_lang); + Log.Debug("TestPersonalityInsightsV2", "proccessed_lang: {0}", profile.processed_lang); if(!string.IsNullOrEmpty(profile.word_count)) - Log.Debug("ExamplePersonalityInsights", "word_count: {0}", profile.word_count); + Log.Debug("TestPersonalityInsightsV2", "word_count: {0}", profile.word_count); if(!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("ExamplePersonalityInsights", "word_count_message: {0}", profile.word_count_message); + Log.Debug("TestPersonalityInsightsV2", "word_count_message: {0}", profile.word_count_message); if(profile.tree != null) { @@ -106,19 +106,19 @@ private void OnGetProfileJson(Profile profile, string data) private void LogTraitTree(TraitTreeNode traitTreeNode) { if(!string.IsNullOrEmpty(traitTreeNode.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", traitTreeNode.id); + Log.Debug("TestPersonalityInsightsV2", "id: {0}", traitTreeNode.id); if(!string.IsNullOrEmpty(traitTreeNode.name)) - Log.Debug("ExamplePersonalityInsights", "name: {0}", traitTreeNode.name); + Log.Debug("TestPersonalityInsightsV2", "name: {0}", traitTreeNode.name); if(!string.IsNullOrEmpty(traitTreeNode.category)) - Log.Debug("ExamplePersonalityInsights", "category: {0}", traitTreeNode.category); + Log.Debug("TestPersonalityInsightsV2", "category: {0}", traitTreeNode.category); if(!string.IsNullOrEmpty(traitTreeNode.percentage)) - Log.Debug("ExamplePersonalityInsights", "percentage: {0}", traitTreeNode.percentage); + Log.Debug("TestPersonalityInsightsV2", "percentage: {0}", traitTreeNode.percentage); if(!string.IsNullOrEmpty(traitTreeNode.sampling_error)) - Log.Debug("ExamplePersonalityInsights", "sampling_error: {0}", traitTreeNode.sampling_error); + Log.Debug("TestPersonalityInsightsV2", "sampling_error: {0}", traitTreeNode.sampling_error); if(!string.IsNullOrEmpty(traitTreeNode.raw_score)) - Log.Debug("ExamplePersonalityInsights", "raw_score: {0}", traitTreeNode.raw_score); + Log.Debug("TestPersonalityInsightsV2", "raw_score: {0}", traitTreeNode.raw_score); if(!string.IsNullOrEmpty(traitTreeNode.raw_sampling_error)) - Log.Debug("ExamplePersonalityInsights", "raw_sampling_error: {0}", traitTreeNode.raw_sampling_error); + Log.Debug("TestPersonalityInsightsV2", "raw_sampling_error: {0}", traitTreeNode.raw_sampling_error); if(traitTreeNode.children != null && traitTreeNode.children.Length > 0) foreach(TraitTreeNode childNode in traitTreeNode.children) LogTraitTree(childNode); diff --git a/Scripts/UnitTests/TestPersonalityInsights.cs.meta b/Scripts/UnitTests/TestPersonalityInsightsV2.cs.meta similarity index 100% rename from Scripts/UnitTests/TestPersonalityInsights.cs.meta rename to Scripts/UnitTests/TestPersonalityInsightsV2.cs.meta diff --git a/Scripts/UnitTests/TestPersonalityInsightsV3.cs b/Scripts/UnitTests/TestPersonalityInsightsV3.cs new file mode 100644 index 000000000..5cc45cb21 --- /dev/null +++ b/Scripts/UnitTests/TestPersonalityInsightsV3.cs @@ -0,0 +1,197 @@ +/** +* Copyright 2015 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 UnityEngine; +using System.Collections; +using IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3; +using IBM.Watson.DeveloperCloud.Logging; + +namespace IBM.Watson.DeveloperCloud.UnitTests +{ + public class TestPersonalityInsightsV3 : UnitTest { + PersonalityInsights m_personalityInsights = new PersonalityInsights(); + private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; + + + bool m_GetProfileTextTested = false; + bool m_GetProfileJsonTested = false; + + public override IEnumerator RunTest() + { + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + + if ( Utilities.Config.Instance.FindCredentials( m_personalityInsights.GetServiceID() ) == null ) + yield break; + + Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Text!"); + m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true); + while(!m_GetProfileTextTested) + yield return null; + + Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Json!"); + m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true); + while(!m_GetProfileJsonTested) + yield return null; + + yield break; + } + + private void OnGetProfileText(Profile profile, string data) + { + Test(profile != null); + + if(profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if(profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach(BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + + m_GetProfileTextTested = true; + } + } + + private void OnGetProfileJson(Profile profile, string data) + { + Test(profile != null); + + if(profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + + m_GetProfileJsonTested = true; + } + } + + private void LogTraitTree(TraitTreeNode traitTreeNode) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", + string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, + string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, + string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, + string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), + string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); + + if(traitTreeNode.children != null && traitTreeNode.children.Length > 0) + foreach (TraitTreeNode childNode in traitTreeNode.children) + LogTraitTree(childNode); + } + + private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) + { + Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); + + foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) + Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", + string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, + string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, + string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); + } + } +} diff --git a/Scripts/UnitTests/TestPersonalityInsightsV3.cs.meta b/Scripts/UnitTests/TestPersonalityInsightsV3.cs.meta new file mode 100644 index 000000000..9acc1edf6 --- /dev/null +++ b/Scripts/UnitTests/TestPersonalityInsightsV3.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1a0853792d73c4947a77efa9a86c126b +timeCreated: 1477410596 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 5350afbcfd4d482d2e3810ab3bad5204d1aecd98 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 12:40:07 -0500 Subject: [PATCH 11/28] added example for personality insights v3 --- ...hts.cs => ExamplePersonalityInsightsV2.cs} | 4 +- ...a => ExamplePersonalityInsightsV2.cs.meta} | 0 .../Scripts/ExamplePersonalityInsightsV3.cs | 172 ++++++++++++++++++ .../ExamplePersonalityInsightsV3.cs.meta | 12 ++ .../ServiceExamples/ServiceExamples.unity | 52 +++++- 5 files changed, 232 insertions(+), 8 deletions(-) rename Examples/ServiceExamples/Scripts/{ExamplePersonalityInsights.cs => ExamplePersonalityInsightsV2.cs} (97%) mode change 100755 => 100644 rename Examples/ServiceExamples/Scripts/{ExamplePersonalityInsights.cs.meta => ExamplePersonalityInsightsV2.cs.meta} (100%) create mode 100644 Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs create mode 100644 Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs.meta diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsights.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs old mode 100755 new mode 100644 similarity index 97% rename from Examples/ServiceExamples/Scripts/ExamplePersonalityInsights.cs rename to Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs index ef83935b1..dbcca7b34 --- a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsights.cs +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs @@ -16,11 +16,11 @@ */ using UnityEngine; -using System.Collections; using IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v2; using IBM.Watson.DeveloperCloud.Logging; -public class ExamplePersonalityInsights : MonoBehaviour { +public class ExamplePersonalityInsightsV2 : MonoBehaviour +{ PersonalityInsights m_personalityInsights = new PersonalityInsights(); void Start () diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsights.cs.meta b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs.meta similarity index 100% rename from Examples/ServiceExamples/Scripts/ExamplePersonalityInsights.cs.meta rename to Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs.meta diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs new file mode 100644 index 000000000..ac0ae40e3 --- /dev/null +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs @@ -0,0 +1,172 @@ +/** +* Copyright 2015 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 UnityEngine; +using IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3; +using IBM.Watson.DeveloperCloud.Logging; + +public class ExamplePersonalityInsightsV3 : MonoBehaviour +{ + PersonalityInsights m_personalityInsights = new PersonalityInsights(); + private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; + + void Start () { + LogSystem.InstallDefaultReactors(); + + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + + if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); + + if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); + } + private void OnGetProfileText(Profile profile, string data) + { + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + } + } + + private void OnGetProfileJson(Profile profile, string data) + { + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + } + } + + private void LogTraitTree(TraitTreeNode traitTreeNode) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", + string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, + string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, + string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, + string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), + string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); + + if (traitTreeNode.children != null && traitTreeNode.children.Length > 0) + foreach (TraitTreeNode childNode in traitTreeNode.children) + LogTraitTree(childNode); + } + + private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) + { + Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); + + foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) + Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", + string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, + string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, + string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); + } +} diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs.meta b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs.meta new file mode 100644 index 000000000..129390801 --- /dev/null +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: cd2e3d3910ea1bd46b55eb5943a057f7 +timeCreated: 1477416788 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Examples/ServiceExamples/ServiceExamples.unity b/Examples/ServiceExamples/ServiceExamples.unity index 2b1a02976..1f3ae00de 100755 --- a/Examples/ServiceExamples/ServiceExamples.unity +++ b/Examples/ServiceExamples/ServiceExamples.unity @@ -37,7 +37,7 @@ RenderSettings: m_ReflectionIntensity: 1 m_CustomReflection: {fileID: 0} m_Sun: {fileID: 0} - m_IndirectSpecularColor: {r: 0.3735645, g: 0.38112062, b: 0.35887584, a: 1} + m_IndirectSpecularColor: {r: 0.3735644, g: 0.38112032, b: 0.35887682, a: 1} --- !u!157 &3 LightmapSettings: m_ObjectHideFlags: 0 @@ -209,7 +209,7 @@ Transform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 11 + m_RootOrder: 12 --- !u!1 &725710367 GameObject: m_ObjectHideFlags: 0 @@ -336,6 +336,46 @@ Transform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_Children: [] m_Father: {fileID: 0} + m_RootOrder: 11 +--- !u!1 &854511683 +GameObject: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + serializedVersion: 4 + m_Component: + - 4: {fileID: 854511685} + - 114: {fileID: 854511684} + m_Layer: 0 + m_Name: ExamplePersonalityInsightsV3 + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 0 +--- !u!114 &854511684 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 854511683} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: cd2e3d3910ea1bd46b55eb5943a057f7, type: 3} + m_Name: + m_EditorClassIdentifier: +--- !u!4 &854511685 +Transform: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_GameObject: {fileID: 854511683} + 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_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_Children: [] + m_Father: {fileID: 0} m_RootOrder: 10 --- !u!1 &859102722 GameObject: @@ -416,7 +456,7 @@ Transform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 12 + m_RootOrder: 13 --- !u!1 &1073418922 GameObject: m_ObjectHideFlags: 0 @@ -472,7 +512,7 @@ GameObject: m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 - m_IsActive: 1 + m_IsActive: 0 --- !u!114 &1160237479 MonoBehaviour: m_ObjectHideFlags: 0 @@ -577,7 +617,7 @@ Transform: m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} m_Children: [] m_Father: {fileID: 0} - m_RootOrder: 13 + m_RootOrder: 14 --- !u!1 &1713392457 GameObject: m_ObjectHideFlags: 0 @@ -668,7 +708,7 @@ GameObject: - 4: {fileID: 2004886373} - 114: {fileID: 2004886372} m_Layer: 0 - m_Name: ExamplePersonalityInsights + m_Name: ExamplePersonalityInsightsV2 m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 From 666df85bca4ba3ea9c2ef84a61932c0953b518e3 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 12:44:05 -0500 Subject: [PATCH 12/28] updated readme and changelog --- CHANGELOG.md | 5 ++ README.md | 192 +++++++++++++++++++++++++++++++++++++-------------- 2 files changed, 147 insertions(+), 50 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2dd1b8b9c..54fa143c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ Change Log ========== +## Version 0.12.0 +_2016_10_27_ +* New: Added streaming `SpeechToText` example. +* New: Abstraction for `Personality Insights V3` + ## Version 0.11.0 _2016_10_27_ * New: Abstracted `Speech to Text` customization methods. diff --git a/README.md b/README.md index 4b418dd80..736e22621 100644 --- a/README.md +++ b/README.md @@ -1563,61 +1563,153 @@ The IBM Watson™ [Personality Insights][personality_insights] service enables a ```cs PersonalityInsights m_personalityInsights = new PersonalityInsights(); + private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; -void Start () { - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + void Start () { + LogSystem.InstallDefaultReactors(); - if(!m_personalityInsights.GetProfile(OnGetProfile, dataPath, DataModels.ContentType.TEXT_PLAIN, DataModels.Language.ENGLISH)) - Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); -} + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; -private void OnGetProfile(DataModels.Profile profile, string data) -{ - Log.Debug("ExamplePersonalityInsights", "data: {0}", data); - if(profile != null) - { - if(!string.IsNullOrEmpty(profile.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", profile.id); - if(!string.IsNullOrEmpty(profile.source)) - Log.Debug("ExamplePersonalityInsights", "source: {0}", profile.source); - if(!string.IsNullOrEmpty(profile.processed_lang)) - Log.Debug("ExamplePersonalityInsights", "proccessed_lang: {0}", profile.processed_lang); - if(!string.IsNullOrEmpty(profile.word_count)) - Log.Debug("ExamplePersonalityInsights", "word_count: {0}", profile.word_count); - if(!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("ExamplePersonalityInsights", "word_count_message: {0}", profile.word_count_message); + if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - if(profile.tree != null) - { - LogTraitTree(profile.tree); - } - } - else - { - Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - } -} + if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); + } + private void OnGetProfileText(Profile profile, string data) + { + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); -private void LogTraitTree(DataModels.TraitTreeNode traitTreeNode) -{ - if(!string.IsNullOrEmpty(traitTreeNode.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", traitTreeNode.id); - if(!string.IsNullOrEmpty(traitTreeNode.name)) - Log.Debug("ExamplePersonalityInsights", "name: {0}", traitTreeNode.name); - if(!string.IsNullOrEmpty(traitTreeNode.category)) - Log.Debug("ExamplePersonalityInsights", "category: {0}", traitTreeNode.category); - if(!string.IsNullOrEmpty(traitTreeNode.percentage)) - Log.Debug("ExamplePersonalityInsights", "percentage: {0}", traitTreeNode.percentage); - if(!string.IsNullOrEmpty(traitTreeNode.sampling_error)) - Log.Debug("ExamplePersonalityInsights", "sampling_error: {0}", traitTreeNode.sampling_error); - if(!string.IsNullOrEmpty(traitTreeNode.raw_score)) - Log.Debug("ExamplePersonalityInsights", "raw_score: {0}", traitTreeNode.raw_score); - if(!string.IsNullOrEmpty(traitTreeNode.raw_sampling_error)) - Log.Debug("ExamplePersonalityInsights", "raw_sampling_error: {0}", traitTreeNode.raw_sampling_error); - if(traitTreeNode.children != null && traitTreeNode.children.Length > 0) - foreach(DataModels.TraitTreeNode childNode in traitTreeNode.children) - LogTraitTree(childNode); -} + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + } + } + + private void OnGetProfileJson(Profile profile, string data) + { + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + } + } + + private void LogTraitTree(TraitTreeNode traitTreeNode) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", + string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, + string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, + string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, + string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), + string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); + + if (traitTreeNode.children != null && traitTreeNode.children.Length > 0) + foreach (TraitTreeNode childNode in traitTreeNode.children) + LogTraitTree(childNode); + } + + private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) + { + Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); + + foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) + Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", + string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, + string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, + string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); + } ``` ### Document Conversion From 4cd9df521c4fe7448e308ee5e0ca1e44d738f130 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 16:52:57 -0500 Subject: [PATCH 13/28] removed long text string from readme and example, define dataPath and set the value in the start method --- .../ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs | 5 +++-- README.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs index ac0ae40e3..f3fcd634b 100644 --- a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs @@ -22,12 +22,13 @@ public class ExamplePersonalityInsightsV3 : MonoBehaviour { PersonalityInsights m_personalityInsights = new PersonalityInsights(); - private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; + private string testString = ""; + private string dataPath; void Start () { LogSystem.InstallDefaultReactors(); - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); diff --git a/README.md b/README.md index 736e22621..588914798 100644 --- a/README.md +++ b/README.md @@ -1563,7 +1563,7 @@ The IBM Watson™ [Personality Insights][personality_insights] service enables a ```cs PersonalityInsights m_personalityInsights = new PersonalityInsights(); - private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; + private string testString = ; void Start () { LogSystem.InstallDefaultReactors(); From dac9ead55ba59a62f6499ad480b6a0b1e55ba9da Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 16:54:42 -0500 Subject: [PATCH 14/28] revised string --- .../ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs index f3fcd634b..e4ddd7c0b 100644 --- a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs @@ -22,7 +22,7 @@ public class ExamplePersonalityInsightsV3 : MonoBehaviour { PersonalityInsights m_personalityInsights = new PersonalityInsights(); - private string testString = ""; + private string testString = ""; private string dataPath; void Start () { diff --git a/README.md b/README.md index 588914798..07f58d7c2 100644 --- a/README.md +++ b/README.md @@ -1563,7 +1563,7 @@ The IBM Watson™ [Personality Insights][personality_insights] service enables a ```cs PersonalityInsights m_personalityInsights = new PersonalityInsights(); - private string testString = ; + private string testString = """; void Start () { LogSystem.InstallDefaultReactors(); From 71229435d00c73f049452da627172fc0f77aaaf7 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 17:05:41 -0500 Subject: [PATCH 15/28] separating Content-Language from Accept-Language --- .../PersonalityInsights/v3/DataModels.cs | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/Scripts/Services/PersonalityInsights/v3/DataModels.cs b/Scripts/Services/PersonalityInsights/v3/DataModels.cs index b397426b9..5987ee790 100755 --- a/Scripts/Services/PersonalityInsights/v3/DataModels.cs +++ b/Scripts/Services/PersonalityInsights/v3/DataModels.cs @@ -239,7 +239,7 @@ public class ContentType /// /// The content language. Either English, Arabic, Spanish or Japanese. /// - public class Language + public class ContentLanguage { /// /// English. @@ -259,6 +259,57 @@ public class Language public const string JAPANESE = "ja"; } + /// + /// The content language. + /// + public class AcceptLanguage + { + /// + /// English. + /// + public const string ENGLISH = "en"; + /// + /// Arabic. + /// + public const string ARABIC = "ar"; + /// + /// Spanish. + /// + public const string SPANISH = "es"; + /// + /// Japanese. + /// + public const string JAPANESE = "ja"; + /// + /// German. + /// + public const string GERMAN = "de"; + /// + /// French. + /// + public const string FRENCH = "fr"; + /// + /// Italian. + /// + public const string ITALIAN = "it"; + /// + /// Korean. + /// + public const string KOREAN = "ko"; + /// + /// Brazilian Portuguese. + /// + public const string BRAZILIAN_PORTUGUESE = "pt-br"; + /// + /// Simplified Chinese. + /// + public const string SIMPLIFIED_CHINESE = "zh-cn"; + /// + /// Traditional Chinese. + /// + public const string TRADITIONAL_CHINESE = "zh-tw"; + } + /// /// The Personality Insights version. /// From 92091f7fa4c500acf7ac6afc12c62a25ef05aa15 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 17:09:06 -0500 Subject: [PATCH 16/28] fix language references --- .../Scripts/ExamplePersonalityInsightsV3.cs | 4 ++-- README.md | 7 ++++--- .../Services/PersonalityInsights/v3/PersonalityInsights.cs | 6 +++--- Scripts/UnitTests/TestPersonalityInsightsV3.cs | 4 ++-- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs index e4ddd7c0b..94740a7c9 100644 --- a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs @@ -30,10 +30,10 @@ void Start () { dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); } private void OnGetProfileText(Profile profile, string data) diff --git a/README.md b/README.md index 07f58d7c2..a6070c4a6 100644 --- a/README.md +++ b/README.md @@ -1564,16 +1564,17 @@ The IBM Watson™ [Personality Insights][personality_insights] service enables a ```cs PersonalityInsights m_personalityInsights = new PersonalityInsights(); private string testString = """; + private string dataPath; void Start () { LogSystem.InstallDefaultReactors(); - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true)) + if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); } private void OnGetProfileText(Profile profile, string data) diff --git a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs index cfdef36b9..30d0f108f 100644 --- a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs +++ b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs @@ -44,9 +44,9 @@ public class PersonalityInsights : IWatsonService public bool GetProfile(OnGetProfile callback, string source, string contentType = ContentType.TEXT_PLAIN, - string contentLanguage = Language.ENGLISH, + string contentLanguage = ContentLanguage.ENGLISH, string accept = ContentType.APPLICATION_JSON, - string acceptLanguage = Language.ENGLISH, + string acceptLanguage = AcceptLanguage.ENGLISH, bool raw_scores = false, bool csv_headers = false, bool consumption_preferences = false, @@ -164,7 +164,7 @@ public CheckServiceStatus(PersonalityInsights service, ServiceStatus callback) m_Service = service; m_Callback = callback; string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - if (!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, Language.ENGLISH)) + if (!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, ContentLanguage.ENGLISH)) m_Callback(SERVICE_ID, false); } diff --git a/Scripts/UnitTests/TestPersonalityInsightsV3.cs b/Scripts/UnitTests/TestPersonalityInsightsV3.cs index 5cc45cb21..d3b977811 100644 --- a/Scripts/UnitTests/TestPersonalityInsightsV3.cs +++ b/Scripts/UnitTests/TestPersonalityInsightsV3.cs @@ -39,12 +39,12 @@ public override IEnumerator RunTest() yield break; Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Text!"); - m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true); + m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true); while(!m_GetProfileTextTested) yield return null; Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Json!"); - m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, Language.ENGLISH, ContentType.APPLICATION_JSON, Language.ENGLISH, true, true, true); + m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true); while(!m_GetProfileJsonTested) yield return null; From 531840583b91d5eb15362e36674b65d8aaff104c Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 17:14:04 -0500 Subject: [PATCH 17/28] formatting --- .../Scripts/ExamplePersonalityInsightsV3.cs | 299 ++++----- .../PersonalityInsights/v3/DataModels.cs | 578 +++++++++--------- .../v3/PersonalityInsights.cs | 300 ++++----- .../UnitTests/TestPersonalityInsightsV3.cs | 301 ++++----- 4 files changed, 740 insertions(+), 738 deletions(-) diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs index 94740a7c9..1199f8069 100644 --- a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs @@ -21,153 +21,154 @@ public class ExamplePersonalityInsightsV3 : MonoBehaviour { - PersonalityInsights m_personalityInsights = new PersonalityInsights(); - private string testString = ""; - private string dataPath; - - void Start () { - LogSystem.InstallDefaultReactors(); - - dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - - if(!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) - Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - - if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) - Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - } - private void OnGetProfileText(Profile profile, string data) - { - if (profile != null) - { - if (!string.IsNullOrEmpty(profile.processed_language)) - Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); - - Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); - - if (!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); - - if (profile.personality != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); - foreach (TraitTreeNode node in profile.personality) - LogTraitTree(node); - } - - if (profile.values != null && profile.values.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); - foreach (TraitTreeNode node in profile.values) - LogTraitTree(node); - } - - if (profile.needs != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); - foreach (TraitTreeNode node in profile.needs) - LogTraitTree(node); - } - - if (profile.behavior != null && profile.behavior.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); - foreach (BehaviorNode behavior in profile.behavior) - { - Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); - Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); - Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); - Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); - Log.Debug("TestPersonalityInsightsV3", "----------------"); - } - } - - if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); - foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) - LogConsumptionPreferencesCategory(categoryNode); - } - } - } - - private void OnGetProfileJson(Profile profile, string data) - { - if (profile != null) - { - if (!string.IsNullOrEmpty(profile.processed_language)) - Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); - - Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); - - if (!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); - - if (profile.personality != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); - foreach (TraitTreeNode node in profile.personality) - LogTraitTree(node); - } - - if (profile.values != null && profile.values.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); - foreach (TraitTreeNode node in profile.values) - LogTraitTree(node); - } - - if (profile.needs != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); - foreach (TraitTreeNode node in profile.needs) - LogTraitTree(node); - } - - if (profile.behavior != null && profile.behavior.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); - foreach (BehaviorNode behavior in profile.behavior) - { - Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); - Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); - Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); - Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); - Log.Debug("TestPersonalityInsightsV3", "----------------"); - } - } - - if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); - foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) - LogConsumptionPreferencesCategory(categoryNode); - } - } - } - - private void LogTraitTree(TraitTreeNode traitTreeNode) - { - Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", - string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, - string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, - string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, - string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), - string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); - - if (traitTreeNode.children != null && traitTreeNode.children.Length > 0) - foreach (TraitTreeNode childNode in traitTreeNode.children) - LogTraitTree(childNode); - } - - private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) - { - Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); - - foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) - Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", - string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, - string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, - string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); - } + PersonalityInsights m_personalityInsights = new PersonalityInsights(); + private string testString = ""; + private string dataPath; + + void Start() + { + LogSystem.InstallDefaultReactors(); + + dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + + if (!m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); + + if (!m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); + } + private void OnGetProfileText(Profile profile, string data) + { + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + } + } + + private void OnGetProfileJson(Profile profile, string data) + { + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + } + } + + private void LogTraitTree(TraitTreeNode traitTreeNode) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", + string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, + string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, + string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, + string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), + string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); + + if (traitTreeNode.children != null && traitTreeNode.children.Length > 0) + foreach (TraitTreeNode childNode in traitTreeNode.children) + LogTraitTree(childNode); + } + + private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) + { + Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); + + foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) + Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", + string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, + string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, + string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); + } } diff --git a/Scripts/Services/PersonalityInsights/v3/DataModels.cs b/Scripts/Services/PersonalityInsights/v3/DataModels.cs index 5987ee790..7ad5a83a3 100755 --- a/Scripts/Services/PersonalityInsights/v3/DataModels.cs +++ b/Scripts/Services/PersonalityInsights/v3/DataModels.cs @@ -20,304 +20,304 @@ namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3 { - /// - /// The Profile object. - /// - [SerializeField] - public class Profile - { - /// - /// The language model that was used to process the input; for example, en. - /// - public string processed_language { get; set; } - /// - /// The number of words that were found in the input. - /// - public int word_count { get; set; } - /// - /// When guidance is appropriate, a string that provides a message that indicates - /// the number of words found and where that value falls in the range of required - /// or suggested number of words. - /// - public string word_count_message { get; set; } - /// - /// Detailed results for the Big Five personality characteristics (dimensions and - /// facets) inferred from the input text. - /// - public TraitTreeNode[] personality { get; set; } - /// - /// Detailed results for the Needs characteristics inferred from the input text. - /// - public TraitTreeNode[] values { get; set; } - /// - /// Detailed results for the Values characteristics inferred from the input text. - /// - public TraitTreeNode[] needs { get; set; } - /// - /// For JSON content that is timestamped, detailed results about the social behavior - /// disclosed by the input in terms of temporal characteristics. The results include - /// information about the distribution of the content over the days of the week and - /// the hours of the day. - /// - public BehaviorNode[] behavior { get; set; } - /// - /// If the consumption_preferences query parameter is true, detailed results for - /// each category of `consumption preferences`. Each element of the array provides - /// information inferred from the input text for the individual preferences of that - /// category. - /// - public ConsumptionPreferencesCategoryNode[] consumption_preferences { get; set; } - /// - /// Warning messages associated with the input text submitted with the request. The - /// array is empty if the input generated no warnings. - /// - public Warning[] warning { get; set; } - } + /// + /// The Profile object. + /// + [SerializeField] + public class Profile + { + /// + /// The language model that was used to process the input; for example, en. + /// + public string processed_language { get; set; } + /// + /// The number of words that were found in the input. + /// + public int word_count { get; set; } + /// + /// When guidance is appropriate, a string that provides a message that indicates + /// the number of words found and where that value falls in the range of required + /// or suggested number of words. + /// + public string word_count_message { get; set; } + /// + /// Detailed results for the Big Five personality characteristics (dimensions and + /// facets) inferred from the input text. + /// + public TraitTreeNode[] personality { get; set; } + /// + /// Detailed results for the Needs characteristics inferred from the input text. + /// + public TraitTreeNode[] values { get; set; } + /// + /// Detailed results for the Values characteristics inferred from the input text. + /// + public TraitTreeNode[] needs { get; set; } + /// + /// For JSON content that is timestamped, detailed results about the social behavior + /// disclosed by the input in terms of temporal characteristics. The results include + /// information about the distribution of the content over the days of the week and + /// the hours of the day. + /// + public BehaviorNode[] behavior { get; set; } + /// + /// If the consumption_preferences query parameter is true, detailed results for + /// each category of `consumption preferences`. Each element of the array provides + /// information inferred from the input text for the individual preferences of that + /// category. + /// + public ConsumptionPreferencesCategoryNode[] consumption_preferences { get; set; } + /// + /// Warning messages associated with the input text submitted with the request. The + /// array is empty if the input generated no warnings. + /// + public Warning[] warning { get; set; } + } - /// - /// The Trait Tree Node object. - /// - [SerializeField] - public class TraitTreeNode - { - /// - /// The unique identifier of the characteristic to which the results pertain. IDs - /// have the form `big5_` for Big Five personality characteristics, `need_` for Needs, - /// or `value_` for Values. - /// - public string trait_id { get; set; } - /// - /// The user-visible name of the characteristic. - /// - public string name { get; set; } - /// - /// The category of the characteristic: personality for Big Five `personality` - /// characteristics, `needs` for Needs, or `values` for Values. - /// - public string category { get; set; } - /// - /// The normalized percentile score for the characteristic. The range is 0 to 1. For - /// example, if the percentage for Openness is 0.60, the author scored in the 60th - /// percentile; the author is more open than 59 percent of the population and less open - /// than 39 percent of the population. - /// - public double percentile { get; set; } - /// - /// The raw score for the characteristic. A positive or negative score indicates more - /// or less of the characteristic; zero indicates neutrality or no evidence for a - /// score. The raw score is computed based on the input and the service model; it is - /// not normalized or compared with a sample population. The raw score enables - /// comparison of the results against a different sampling population and with a custom - /// normalization approach. - /// - public double raw_score { get; set; } - /// - /// For `personality` (Big Five) dimensions, more detailed results for the facets of - /// each dimension as inferred from the input text. - /// - public TraitTreeNode[] children { get; set; } - } + /// + /// The Trait Tree Node object. + /// + [SerializeField] + public class TraitTreeNode + { + /// + /// The unique identifier of the characteristic to which the results pertain. IDs + /// have the form `big5_` for Big Five personality characteristics, `need_` for Needs, + /// or `value_` for Values. + /// + public string trait_id { get; set; } + /// + /// The user-visible name of the characteristic. + /// + public string name { get; set; } + /// + /// The category of the characteristic: personality for Big Five `personality` + /// characteristics, `needs` for Needs, or `values` for Values. + /// + public string category { get; set; } + /// + /// The normalized percentile score for the characteristic. The range is 0 to 1. For + /// example, if the percentage for Openness is 0.60, the author scored in the 60th + /// percentile; the author is more open than 59 percent of the population and less open + /// than 39 percent of the population. + /// + public double percentile { get; set; } + /// + /// The raw score for the characteristic. A positive or negative score indicates more + /// or less of the characteristic; zero indicates neutrality or no evidence for a + /// score. The raw score is computed based on the input and the service model; it is + /// not normalized or compared with a sample population. The raw score enables + /// comparison of the results against a different sampling population and with a custom + /// normalization approach. + /// + public double raw_score { get; set; } + /// + /// For `personality` (Big Five) dimensions, more detailed results for the facets of + /// each dimension as inferred from the input text. + /// + public TraitTreeNode[] children { get; set; } + } - /// - /// The Behavior Node object. - /// - [SerializeField] - public class BehaviorNode - { - /// - /// The unique identifier of the characteristic to which the results pertain. IDs have - /// the form `behavior_`. - /// - public string trait_id { get; set; } - /// - /// The user-visible name of the characteristic. - /// - public string name { get; set; } - /// - /// The category of the characteristic: behavior for temporal data. - /// - public string category { get; set; } - /// - /// For JSON content that is timestamped, the percentage of timestamped input data - /// that occurred during that day of the week or hour of the day. The range is 0 to 1. - /// - public double percentage { get; set; } - } + /// + /// The Behavior Node object. + /// + [SerializeField] + public class BehaviorNode + { + /// + /// The unique identifier of the characteristic to which the results pertain. IDs have + /// the form `behavior_`. + /// + public string trait_id { get; set; } + /// + /// The user-visible name of the characteristic. + /// + public string name { get; set; } + /// + /// The category of the characteristic: behavior for temporal data. + /// + public string category { get; set; } + /// + /// For JSON content that is timestamped, the percentage of timestamped input data + /// that occurred during that day of the week or hour of the day. The range is 0 to 1. + /// + public double percentage { get; set; } + } - /// - /// The Consumption Preferences Category Node object. - /// - [SerializeField] - public class ConsumptionPreferencesCategoryNode - { - /// - /// The unique identifier of the consumption preferences category to which the results - /// pertain. IDs have the form `consumption_preferences_`. - /// - public string consumption_preference_category_id { get; set; } - /// - /// The user-visible name of the consumption preferences category. - /// - public string name { get; set; } - /// - /// Detailed results inferred from the input text for the individual preferences of - /// the category. - /// - public ConsumptionPreferencesNode[] consumption_preferences { get; set; } - } + /// + /// The Consumption Preferences Category Node object. + /// + [SerializeField] + public class ConsumptionPreferencesCategoryNode + { + /// + /// The unique identifier of the consumption preferences category to which the results + /// pertain. IDs have the form `consumption_preferences_`. + /// + public string consumption_preference_category_id { get; set; } + /// + /// The user-visible name of the consumption preferences category. + /// + public string name { get; set; } + /// + /// Detailed results inferred from the input text for the individual preferences of + /// the category. + /// + public ConsumptionPreferencesNode[] consumption_preferences { get; set; } + } - /// - /// The Warning Object. - /// - [SerializeField] - public class Warning - { - /// - /// The identifier of the warning message, one of `WORD_COUNT_MESSAGE`, `JSON_AS_TEXT`, - /// or `PARTIAL_TEXT_USED`. - /// - public string warning_id { get; set; } - /// - /// The message associated with the `warning_id`. For `WORD_COUNT_MESSAGE`, "There were - /// words in the input. We need a minimum of 600, preferably 1,200 or more, to - /// compute statistically significant estimates."; for `JSON_AS_TEXT`, "Request input - /// was processed as text/plain as indicated, however detected a JSON input. Did you - /// mean application/json?"; and for `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." The `PARTIAL_TEXT_USED` - /// warning applies only when Arabic input text exceeds a threshold at which additional - /// words do not contribute to the accuracy of the profile. - /// - public string message { get; set; } - } + /// + /// The Warning Object. + /// + [SerializeField] + public class Warning + { + /// + /// The identifier of the warning message, one of `WORD_COUNT_MESSAGE`, `JSON_AS_TEXT`, + /// or `PARTIAL_TEXT_USED`. + /// + public string warning_id { get; set; } + /// + /// The message associated with the `warning_id`. For `WORD_COUNT_MESSAGE`, "There were + /// words in the input. We need a minimum of 600, preferably 1,200 or more, to + /// compute statistically significant estimates."; for `JSON_AS_TEXT`, "Request input + /// was processed as text/plain as indicated, however detected a JSON input. Did you + /// mean application/json?"; and for `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." The `PARTIAL_TEXT_USED` + /// warning applies only when Arabic input text exceeds a threshold at which additional + /// words do not contribute to the accuracy of the profile. + /// + public string message { get; set; } + } - /// - /// The Consumption Preferences Node object. - /// - [SerializeField] - public class ConsumptionPreferencesNode - { - /// - /// The unique identifier of the consumption preference to which the results pertain. - /// IDs have the form `consumption_preferences_`. - /// - public string consumption_preference_id { get; set; } - /// - /// The user-visible name of the consumption preference. - /// - public string name { get; set; } - /// - /// The score for the consumption preference: `0.0` indicates unlikely, `0.5` indicates - /// neutrality, and `1.0` indicates likely. The scores for some preferences are binary and - /// do not allow a neutral value. The score is an indication of preference based on the - /// results inferred from the input text, not a normalized percentile. - /// - public double score { get; set; } - } + /// + /// The Consumption Preferences Node object. + /// + [SerializeField] + public class ConsumptionPreferencesNode + { + /// + /// The unique identifier of the consumption preference to which the results pertain. + /// IDs have the form `consumption_preferences_`. + /// + public string consumption_preference_id { get; set; } + /// + /// The user-visible name of the consumption preference. + /// + public string name { get; set; } + /// + /// The score for the consumption preference: `0.0` indicates unlikely, `0.5` indicates + /// neutrality, and `1.0` indicates likely. The scores for some preferences are binary and + /// do not allow a neutral value. The score is an indication of preference based on the + /// results inferred from the input text, not a normalized percentile. + /// + public double score { get; set; } + } - /// - /// The content type. Either text, html or json. - /// - public class ContentType - { - /// - /// Mime type for plain text. - /// - public const string TEXT_PLAIN = "text/plain"; + /// + /// The content type. Either text, html or json. + /// + public class ContentType + { + /// + /// Mime type for plain text. + /// + public const string TEXT_PLAIN = "text/plain"; - /// - /// Mime type for HTML. - /// - public const string TEXT_HTML = "text/html"; + /// + /// Mime type for HTML. + /// + public const string TEXT_HTML = "text/html"; - /// - /// Mime type for json. - /// - public const string APPLICATION_JSON = "application/json"; - } + /// + /// Mime type for json. + /// + public const string APPLICATION_JSON = "application/json"; + } - /// - /// The content language. Either English, Arabic, Spanish or Japanese. - /// - public class ContentLanguage - { - /// - /// English. - /// - public const string ENGLISH = "en"; - /// - /// Arabic. - /// - public const string ARABIC = "ar"; - /// - /// Spanish. - /// - public const string SPANISH = "es"; - /// - /// Japanese - /// - public const string JAPANESE = "ja"; - } + /// + /// The content language. Either English, Arabic, Spanish or Japanese. + /// + public class ContentLanguage + { + /// + /// English. + /// + public const string ENGLISH = "en"; + /// + /// Arabic. + /// + public const string ARABIC = "ar"; + /// + /// Spanish. + /// + public const string SPANISH = "es"; + /// + /// Japanese + /// + public const string JAPANESE = "ja"; + } - /// - /// The content language. - /// - public class AcceptLanguage - { - /// - /// English. - /// - public const string ENGLISH = "en"; - /// - /// Arabic. - /// - public const string ARABIC = "ar"; - /// - /// Spanish. - /// - public const string SPANISH = "es"; - /// - /// Japanese. - /// - public const string JAPANESE = "ja"; - /// - /// German. - /// - public const string GERMAN = "de"; - /// - /// French. - /// - public const string FRENCH = "fr"; - /// - /// Italian. - /// - public const string ITALIAN = "it"; - /// - /// Korean. - /// - public const string KOREAN = "ko"; - /// - /// Brazilian Portuguese. - /// - public const string BRAZILIAN_PORTUGUESE = "pt-br"; - /// - /// Simplified Chinese. - /// - public const string SIMPLIFIED_CHINESE = "zh-cn"; - /// - /// Traditional Chinese. - /// - public const string TRADITIONAL_CHINESE = "zh-tw"; - } + /// + /// The accepted languages. + /// + public class AcceptLanguage + { + /// + /// English. + /// + public const string ENGLISH = "en"; + /// + /// Arabic. + /// + public const string ARABIC = "ar"; + /// + /// Spanish. + /// + public const string SPANISH = "es"; + /// + /// Japanese. + /// + public const string JAPANESE = "ja"; + /// + /// German. + /// + public const string GERMAN = "de"; + /// + /// French. + /// + public const string FRENCH = "fr"; + /// + /// Italian. + /// + public const string ITALIAN = "it"; + /// + /// Korean. + /// + public const string KOREAN = "ko"; + /// + /// Brazilian Portuguese. + /// + public const string BRAZILIAN_PORTUGUESE = "pt-br"; + /// + /// Simplified Chinese. + /// + public const string SIMPLIFIED_CHINESE = "zh-cn"; + /// + /// Traditional Chinese. + /// + public const string TRADITIONAL_CHINESE = "zh-tw"; + } - /// - /// The Personality Insights version. - /// - public class PersonalityInsightsVersion - { - /// - /// The version. - /// - public const string Version = "2016-10-20"; - } + /// + /// The Personality Insights version. + /// + public class PersonalityInsightsVersion + { + /// + /// The version. + /// + public const string Version = "2016-10-20"; + } } diff --git a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs index 30d0f108f..d4a358898 100644 --- a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs +++ b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs @@ -26,154 +26,154 @@ namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v3 { - /// - /// This class wraps the Personality Insights service. - /// Personality Insights Service - /// - public class PersonalityInsights : IWatsonService - { - #region Private Data - private const string SERVICE_ID = "PersonalityInsightsV3"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Profile - private const string SERVICE_GET_PROFILE = "/v3/profile"; - - public delegate void OnGetProfile(Profile profile, string data); - - public bool GetProfile(OnGetProfile callback, string source, - string contentType = ContentType.TEXT_PLAIN, - string contentLanguage = ContentLanguage.ENGLISH, - string accept = ContentType.APPLICATION_JSON, - string acceptLanguage = AcceptLanguage.ENGLISH, - bool raw_scores = false, - bool csv_headers = false, - bool consumption_preferences = false, - string version = PersonalityInsightsVersion.Version, - string data = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new ArgumentNullException("A JSON or Text source is required for GetProfile!"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_PROFILE); - if (connector == null) - return false; - - GetProfileRequest req = new GetProfileRequest(); - req.Source = source; - req.Callback = callback; - req.Data = data; - req.OnResponse = GetProfileResponse; - - req.Parameters["raw_scores"] = raw_scores.ToString(); - req.Parameters["csv_headers"] = csv_headers.ToString(); - req.Parameters["consumption_preferences"] = consumption_preferences.ToString(); - req.Parameters["version"] = version; - - req.Headers["Content-Type"] = contentType; - req.Headers["Content-Language"] = contentLanguage; - req.Headers["Accept"] = accept; - req.Headers["Accept-Language"] = acceptLanguage; - - if (source.StartsWith(Application.dataPath)) - { - string jsonData = default(string); - jsonData = File.ReadAllText(source); - req.Send = System.Text.Encoding.UTF8.GetBytes(jsonData); - } - else - { - req.Send = System.Text.Encoding.UTF8.GetBytes(source); - } - - return connector.Send(req); - } - - /// - /// Get profile request. - /// - public class GetProfileRequest : RESTConnector.Request - { - /// - /// The source string. - /// - public string Source { get; set; } - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetProfile Callback { get; set; } - } - - private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - Profile response = new Profile(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetProfileRequest)req).Callback != null) - ((GetProfileRequest)req).Callback(resp.Success ? response : null, ((GetProfileRequest)req).Data); - } - #endregion - - #region IWatsonService implementation - public string GetServiceID() - { - return SERVICE_ID; - } - - public void GetServiceStatus(ServiceStatus callback) - { - if (Utilities.Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); - } - - private class CheckServiceStatus - { - private PersonalityInsights m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(PersonalityInsights service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - if (!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, ContentLanguage.ENGLISH)) - m_Callback(SERVICE_ID, false); - } - - private void OnGetProfile(Profile resp, string data) - { - if (m_Callback != null) - m_Callback(SERVICE_ID, resp != null); - } - } - #endregion - } + /// + /// This class wraps the Personality Insights service. + /// Personality Insights Service + /// + public class PersonalityInsights : IWatsonService + { + #region Private Data + private const string SERVICE_ID = "PersonalityInsightsV3"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Profile + private const string SERVICE_GET_PROFILE = "/v3/profile"; + + public delegate void OnGetProfile(Profile profile, string data); + + public bool GetProfile(OnGetProfile callback, string source, + string contentType = ContentType.TEXT_PLAIN, + string contentLanguage = ContentLanguage.ENGLISH, + string accept = ContentType.APPLICATION_JSON, + string acceptLanguage = AcceptLanguage.ENGLISH, + bool raw_scores = false, + bool csv_headers = false, + bool consumption_preferences = false, + string version = PersonalityInsightsVersion.Version, + string data = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new ArgumentNullException("A JSON or Text source is required for GetProfile!"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_PROFILE); + if (connector == null) + return false; + + GetProfileRequest req = new GetProfileRequest(); + req.Source = source; + req.Callback = callback; + req.Data = data; + req.OnResponse = GetProfileResponse; + + req.Parameters["raw_scores"] = raw_scores.ToString(); + req.Parameters["csv_headers"] = csv_headers.ToString(); + req.Parameters["consumption_preferences"] = consumption_preferences.ToString(); + req.Parameters["version"] = version; + + req.Headers["Content-Type"] = contentType; + req.Headers["Content-Language"] = contentLanguage; + req.Headers["Accept"] = accept; + req.Headers["Accept-Language"] = acceptLanguage; + + if (source.StartsWith(Application.dataPath)) + { + string jsonData = default(string); + jsonData = File.ReadAllText(source); + req.Send = System.Text.Encoding.UTF8.GetBytes(jsonData); + } + else + { + req.Send = System.Text.Encoding.UTF8.GetBytes(source); + } + + return connector.Send(req); + } + + /// + /// Get profile request. + /// + public class GetProfileRequest : RESTConnector.Request + { + /// + /// The source string. + /// + public string Source { get; set; } + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetProfile Callback { get; set; } + } + + private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Profile response = new Profile(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetProfileRequest)req).Callback != null) + ((GetProfileRequest)req).Callback(resp.Success ? response : null, ((GetProfileRequest)req).Data); + } + #endregion + + #region IWatsonService implementation + public string GetServiceID() + { + return SERVICE_ID; + } + + public void GetServiceStatus(ServiceStatus callback) + { + if (Utilities.Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + private class CheckServiceStatus + { + private PersonalityInsights m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(PersonalityInsights service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + if (!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, ContentLanguage.ENGLISH)) + m_Callback(SERVICE_ID, false); + } + + private void OnGetProfile(Profile resp, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, resp != null); + } + } + #endregion + } } \ No newline at end of file diff --git a/Scripts/UnitTests/TestPersonalityInsightsV3.cs b/Scripts/UnitTests/TestPersonalityInsightsV3.cs index d3b977811..97c743a79 100644 --- a/Scripts/UnitTests/TestPersonalityInsightsV3.cs +++ b/Scripts/UnitTests/TestPersonalityInsightsV3.cs @@ -23,175 +23,176 @@ namespace IBM.Watson.DeveloperCloud.UnitTests { - public class TestPersonalityInsightsV3 : UnitTest { - PersonalityInsights m_personalityInsights = new PersonalityInsights(); - private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; + public class TestPersonalityInsightsV3 : UnitTest + { + PersonalityInsights m_personalityInsights = new PersonalityInsights(); + private string testString = "Facing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\""; - bool m_GetProfileTextTested = false; - bool m_GetProfileJsonTested = false; + bool m_GetProfileTextTested = false; + bool m_GetProfileJsonTested = false; - public override IEnumerator RunTest() + public override IEnumerator RunTest() + { + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + + if (Utilities.Config.Instance.FindCredentials(m_personalityInsights.GetServiceID()) == null) + yield break; + + Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Text!"); + m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true); + while (!m_GetProfileTextTested) + yield return null; + + Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Json!"); + m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true); + while (!m_GetProfileJsonTested) + yield return null; + + yield break; + } + + private void OnGetProfileText(Profile profile, string data) + { + Test(profile != null); + + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); + + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); + + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); + + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); + } + + if (profile.needs != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); + } + + if (profile.behavior != null && profile.behavior.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } + } + + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) { - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); + } + + m_GetProfileTextTested = true; + } + } + + private void OnGetProfileJson(Profile profile, string data) + { + Test(profile != null); - if ( Utilities.Config.Instance.FindCredentials( m_personalityInsights.GetServiceID() ) == null ) - yield break; + if (profile != null) + { + if (!string.IsNullOrEmpty(profile.processed_language)) + Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); - Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Text!"); - m_personalityInsights.GetProfile(OnGetProfileText, testString, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true); - while(!m_GetProfileTextTested) - yield return null; + Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); - Log.Debug("TestPersonalityInsightsV3", "Attempting GetProfile using Json!"); - m_personalityInsights.GetProfile(OnGetProfileJson, dataPath, ContentType.TEXT_HTML, ContentLanguage.ENGLISH, ContentType.APPLICATION_JSON, AcceptLanguage.ENGLISH, true, true, true); - while(!m_GetProfileJsonTested) - yield return null; + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); - yield break; + if (profile.personality != null && profile.personality.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); + foreach (TraitTreeNode node in profile.personality) + LogTraitTree(node); + } + + if (profile.values != null && profile.values.Length > 0) + { + Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); + foreach (TraitTreeNode node in profile.values) + LogTraitTree(node); } - private void OnGetProfileText(Profile profile, string data) + if (profile.needs != null && profile.personality.Length > 0) { - Test(profile != null); - - if(profile != null) - { - if (!string.IsNullOrEmpty(profile.processed_language)) - Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); - - Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); - - if (!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); - - if (profile.personality != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); - foreach (TraitTreeNode node in profile.personality) - LogTraitTree(node); - } - - if (profile.values != null && profile.values.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); - foreach (TraitTreeNode node in profile.values) - LogTraitTree(node); - } - - if (profile.needs != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); - foreach (TraitTreeNode node in profile.needs) - LogTraitTree(node); - } - - if(profile.behavior != null && profile.behavior.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); - foreach(BehaviorNode behavior in profile.behavior) - { - Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); - Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); - Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); - Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); - Log.Debug("TestPersonalityInsightsV3", "----------------"); - } - } - - if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); - foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) - LogConsumptionPreferencesCategory(categoryNode); - } - - m_GetProfileTextTested = true; - } + Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); + foreach (TraitTreeNode node in profile.needs) + LogTraitTree(node); } - private void OnGetProfileJson(Profile profile, string data) + if (profile.behavior != null && profile.behavior.Length > 0) { - Test(profile != null); - - if(profile != null) - { - if (!string.IsNullOrEmpty(profile.processed_language)) - Log.Debug("TestPersonalityInsightsV3", "processed_language: {0}", profile.processed_language); - - Log.Debug("TestPersonalityInsightsV3", "word_count: {0}", profile.word_count); - - if (!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("TestPersonalityInsightsV3", "word_count_message: {0}", profile.word_count_message); - - if (profile.personality != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Personality trait tree"); - foreach (TraitTreeNode node in profile.personality) - LogTraitTree(node); - } - - if (profile.values != null && profile.values.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Values trait tree"); - foreach (TraitTreeNode node in profile.values) - LogTraitTree(node); - } - - if (profile.needs != null && profile.personality.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Needs trait tree"); - foreach (TraitTreeNode node in profile.needs) - LogTraitTree(node); - } - - if (profile.behavior != null && profile.behavior.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); - foreach (BehaviorNode behavior in profile.behavior) - { - Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); - Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); - Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); - Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); - Log.Debug("TestPersonalityInsightsV3", "----------------"); - } - } - - if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) - { - Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); - foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) - LogConsumptionPreferencesCategory(categoryNode); - } - - m_GetProfileJsonTested = true; - } + Log.Debug("TestPersonalityInsightsV3", "Behavior tree"); + foreach (BehaviorNode behavior in profile.behavior) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0}", behavior.trait_id); + Log.Debug("TestPersonalityInsightsV3", "name: {0}", behavior.name); + Log.Debug("TestPersonalityInsightsV3", "category: {0}", behavior.category); + Log.Debug("TestPersonalityInsightsV3", "percentage: {0}", behavior.percentage.ToString()); + Log.Debug("TestPersonalityInsightsV3", "----------------"); + } } - private void LogTraitTree(TraitTreeNode traitTreeNode) + if (profile.consumption_preferences != null && profile.consumption_preferences.Length > 0) { - Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", - string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, - string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, - string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, - string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), - string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); - - if(traitTreeNode.children != null && traitTreeNode.children.Length > 0) - foreach (TraitTreeNode childNode in traitTreeNode.children) - LogTraitTree(childNode); + Log.Debug("TestPersonalityInsightsV3", "ConsumptionPreferencesCategories"); + foreach (ConsumptionPreferencesCategoryNode categoryNode in profile.consumption_preferences) + LogConsumptionPreferencesCategory(categoryNode); } - private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) - { - Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); + m_GetProfileJsonTested = true; + } + } + + private void LogTraitTree(TraitTreeNode traitTreeNode) + { + Log.Debug("TestPersonalityInsightsV3", "trait_id: {0} | name: {1} | category: {2} | percentile: {3} | raw_score: {4}", + string.IsNullOrEmpty(traitTreeNode.trait_id) ? "null" : traitTreeNode.trait_id, + string.IsNullOrEmpty(traitTreeNode.name) ? "null" : traitTreeNode.name, + string.IsNullOrEmpty(traitTreeNode.category) ? "null" : traitTreeNode.category, + string.IsNullOrEmpty(traitTreeNode.percentile.ToString()) ? "null" : traitTreeNode.percentile.ToString(), + string.IsNullOrEmpty(traitTreeNode.raw_score.ToString()) ? "null" : traitTreeNode.raw_score.ToString()); + + if (traitTreeNode.children != null && traitTreeNode.children.Length > 0) + foreach (TraitTreeNode childNode in traitTreeNode.children) + LogTraitTree(childNode); + } + + private void LogConsumptionPreferencesCategory(ConsumptionPreferencesCategoryNode categoryNode) + { + Log.Debug("TestPersonalityInsightsV3", "consumption_preference_category_id: {0} | name: {1}", categoryNode.consumption_preference_category_id, categoryNode.name); - foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) - Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", - string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, - string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, - string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); - } + foreach (ConsumptionPreferencesNode preferencesNode in categoryNode.consumption_preferences) + Log.Debug("TestPersonalityInsightsV3", "\t consumption_preference_id: {0} | name: {1} | score: {2}", + string.IsNullOrEmpty(preferencesNode.consumption_preference_id) ? "null" : preferencesNode.consumption_preference_id, + string.IsNullOrEmpty(preferencesNode.name) ? "null" : preferencesNode.name, + string.IsNullOrEmpty(preferencesNode.score.ToString()) ? "null" : preferencesNode.score.ToString()); } + } } From d55e742b5278347e7dee97e14eac59db6b52508c Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 25 Oct 2016 17:36:21 -0500 Subject: [PATCH 18/28] formatting, trace recording device to console --- .../Scripts/ExampleStreaming.cs | 281 +++++++++--------- 1 file changed, 140 insertions(+), 141 deletions(-) diff --git a/Examples/ServiceExamples/Scripts/ExampleStreaming.cs b/Examples/ServiceExamples/Scripts/ExampleStreaming.cs index 4ba1e19e6..59ee303e9 100755 --- a/Examples/ServiceExamples/Scripts/ExampleStreaming.cs +++ b/Examples/ServiceExamples/Scripts/ExampleStreaming.cs @@ -24,145 +24,144 @@ public class ExampleStreaming : MonoBehaviour { - private int m_RecordingRoutine = 0; - - - private string m_MicrophoneID = null; - private AudioClip m_Recording = null; - private int m_RecordingBufferSize = 2; - private int m_RecordingHZ = 22050; - - - private SpeechToText m_SpeechToText = new SpeechToText(); - - void Start() - { - LogSystem.InstallDefaultReactors(); - Log.Debug("ExampleStreaming", "Start();"); - - Active = true; - - StartRecording(); - } - - public bool Active - { - get { return m_SpeechToText.IsListening; } - set { - if ( value && !m_SpeechToText.IsListening ) - { - m_SpeechToText.DetectSilence = true; - m_SpeechToText.EnableWordConfidence = false; - m_SpeechToText.EnableTimestamps = false; - m_SpeechToText.SilenceThreshold = 0.03f; - m_SpeechToText.MaxAlternatives = 1; - m_SpeechToText.EnableContinousRecognition = true; - m_SpeechToText.EnableInterimResults = true; - m_SpeechToText.OnError = OnError; - m_SpeechToText.StartListening( OnRecognize ); - } - else if ( !value && m_SpeechToText.IsListening ) - { - m_SpeechToText.StopListening(); - } - } - } - - private void StartRecording() - { - if (m_RecordingRoutine == 0) - { - UnityObjectUtil.StartDestroyQueue(); - m_RecordingRoutine = Runnable.Run(RecordingHandler()); - } - } - - private void StopRecording() - { - if (m_RecordingRoutine != 0) - { - Microphone.End(m_MicrophoneID); - Runnable.Stop(m_RecordingRoutine); - m_RecordingRoutine = 0; - } - } - - private void OnError( string error ) - { - Active = false; - - Log.Debug("ExampleStreaming", "Error! {0}", error); - } - - private IEnumerator RecordingHandler() - { - m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ); - yield return null; // let m_RecordingRoutine get set.. - - if (m_Recording == null) - { - StopRecording(); - yield break; - } - - bool bFirstBlock = true; - int midPoint = m_Recording.samples / 2; - float[] samples = null; - - while (m_RecordingRoutine != 0 && m_Recording != null) - { - int writePos = Microphone.GetPosition(m_MicrophoneID); - if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID)) - { - Log.Error("MicrophoneWidget", "Microphone disconnected."); - - StopRecording(); - yield break; - } - - if ((bFirstBlock && writePos >= midPoint) - || (!bFirstBlock && writePos < midPoint)) - { - // front block is recorded, make a RecordClip and pass it onto our callback. - samples = new float[midPoint]; - m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint); - - AudioData record = new AudioData(); - record.MaxLevel = Mathf.Max(samples); - record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false); - record.Clip.SetData(samples, 0); - - m_SpeechToText.OnListen(record); - - bFirstBlock = !bFirstBlock; - } - else - { - // calculate the number of samples remaining until we ready for a block of audio, - // and wait that amount of time it will take to record. - int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos); - float timeRemaining = (float)remaining / (float)m_RecordingHZ; - - yield return new WaitForSeconds(timeRemaining); - } - - } - - yield break; - } - - private void OnRecognize(SpeechRecognitionEvent result) - { - if (result != null && result.results.Length > 0) - { - foreach (var res in result.results) - { - foreach (var alt in res.alternatives) - { - string text = alt.transcript; - Log.Debug("ExampleStreaming", string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); - } - } - } - } + private int m_RecordingRoutine = 0; + private string m_MicrophoneID = null; + private AudioClip m_Recording = null; + private int m_RecordingBufferSize = 2; + private int m_RecordingHZ = 22050; + + private SpeechToText m_SpeechToText = new SpeechToText(); + + void Start() + { + LogSystem.InstallDefaultReactors(); + Log.Debug("ExampleStreaming", "Start();"); + + Active = true; + + StartRecording(); + } + + public bool Active + { + get { return m_SpeechToText.IsListening; } + set + { + if (value && !m_SpeechToText.IsListening) + { + m_SpeechToText.DetectSilence = true; + m_SpeechToText.EnableWordConfidence = false; + m_SpeechToText.EnableTimestamps = false; + m_SpeechToText.SilenceThreshold = 0.03f; + m_SpeechToText.MaxAlternatives = 1; + m_SpeechToText.EnableContinousRecognition = true; + m_SpeechToText.EnableInterimResults = true; + m_SpeechToText.OnError = OnError; + m_SpeechToText.StartListening(OnRecognize); + } + else if (!value && m_SpeechToText.IsListening) + { + m_SpeechToText.StopListening(); + } + } + } + + private void StartRecording() + { + if (m_RecordingRoutine == 0) + { + UnityObjectUtil.StartDestroyQueue(); + m_RecordingRoutine = Runnable.Run(RecordingHandler()); + } + } + + private void StopRecording() + { + if (m_RecordingRoutine != 0) + { + Microphone.End(m_MicrophoneID); + Runnable.Stop(m_RecordingRoutine); + m_RecordingRoutine = 0; + } + } + + private void OnError(string error) + { + Active = false; + + Log.Debug("ExampleStreaming", "Error! {0}", error); + } + + private IEnumerator RecordingHandler() + { + Log.Debug("ExampleStreaming", "devices: {0}", Microphone.devices); + m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ); + yield return null; // let m_RecordingRoutine get set.. + + if (m_Recording == null) + { + StopRecording(); + yield break; + } + + bool bFirstBlock = true; + int midPoint = m_Recording.samples / 2; + float[] samples = null; + + while (m_RecordingRoutine != 0 && m_Recording != null) + { + int writePos = Microphone.GetPosition(m_MicrophoneID); + if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID)) + { + Log.Error("MicrophoneWidget", "Microphone disconnected."); + + StopRecording(); + yield break; + } + + if ((bFirstBlock && writePos >= midPoint) + || (!bFirstBlock && writePos < midPoint)) + { + // front block is recorded, make a RecordClip and pass it onto our callback. + samples = new float[midPoint]; + m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint); + + AudioData record = new AudioData(); + record.MaxLevel = Mathf.Max(samples); + record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false); + record.Clip.SetData(samples, 0); + + m_SpeechToText.OnListen(record); + + bFirstBlock = !bFirstBlock; + } + else + { + // calculate the number of samples remaining until we ready for a block of audio, + // and wait that amount of time it will take to record. + int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos); + float timeRemaining = (float)remaining / (float)m_RecordingHZ; + + yield return new WaitForSeconds(timeRemaining); + } + + } + + yield break; + } + + private void OnRecognize(SpeechRecognitionEvent result) + { + if (result != null && result.results.Length > 0) + { + foreach (var res in result.results) + { + foreach (var alt in res.alternatives) + { + string text = alt.transcript; + Log.Debug("ExampleStreaming", string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); + } + } + } + } } \ No newline at end of file From 3797720a6c329e461c2b6f105ffb3514a731a9d3 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Wed, 26 Oct 2016 11:36:53 -0500 Subject: [PATCH 19/28] add editorconfig file, apply formatting to service examples --- .editorconfig | 11 + .../Scripts/ExampleAlchemyDataNews.cs | 37 +- .../Scripts/ExampleAlchemyLanguage.cs | 1139 ++++++++--------- .../Scripts/ExampleConversation.cs | 93 +- .../ExampleConversationExperimental.cs | 49 +- .../Scripts/ExampleDocumentConversion.cs | 78 +- .../Scripts/ExampleLanguageTranslation.cs | 27 +- .../Scripts/ExampleLanguageTranslator.cs | 29 +- .../ExampleNaturalLanguageClassifier.cs | 30 +- .../Scripts/ExamplePersonalityInsightsV2.cs | 100 +- .../Scripts/ExamplePersonalityInsightsV3.cs | 0 .../Scripts/ExampleRetrieveAndRank.cs | 768 +++++------ .../Scripts/ExampleSpeechToText.cs | 868 ++++++------- .../Scripts/ExampleTextToSpeech.cs | 498 +++---- .../Scripts/ExampleToneAnalyzer.cs | 24 +- .../Scripts/ExampleTradeoffAnalytics.cs | 208 +-- .../Scripts/ExampleVisualRecognition.cs | 380 +++--- 17 files changed, 2179 insertions(+), 2160 deletions(-) create mode 100644 .editorconfig mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExampleLanguageTranslation.cs mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExampleLanguageTranslator.cs mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExampleNaturalLanguageClassifier.cs mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExampleToneAnalyzer.cs mode change 100644 => 100755 Examples/ServiceExamples/Scripts/ExampleTradeoffAnalytics.cs diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..64b7d729c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +; Top-most EditorConfig file +root = true + +; Unix-style newlines +[*] +end_of_line = LF + +; 2-column space indentation +[*.cs] +indent_style = space +indent_size = 2 diff --git a/Examples/ServiceExamples/Scripts/ExampleAlchemyDataNews.cs b/Examples/ServiceExamples/Scripts/ExampleAlchemyDataNews.cs index 834e451d3..960b0efcb 100755 --- a/Examples/ServiceExamples/Scripts/ExampleAlchemyDataNews.cs +++ b/Examples/ServiceExamples/Scripts/ExampleAlchemyDataNews.cs @@ -16,30 +16,31 @@ */ using UnityEngine; -using System.Collections; using System.Collections.Generic; using IBM.Watson.DeveloperCloud.Services.AlchemyAPI.v1; using IBM.Watson.DeveloperCloud.Logging; using System; -public class ExampleAlchemyDataNews : MonoBehaviour { - private AlchemyAPI m_AlchemyAPI = new AlchemyAPI(); - - void Start () { - LogSystem.InstallDefaultReactors(); +public class ExampleAlchemyDataNews : MonoBehaviour +{ + private AlchemyAPI m_AlchemyAPI = new AlchemyAPI(); - string[] returnFields = {Fields.ENRICHED_URL_ENTITIES, Fields.ENRICHED_URL_KEYWORDS}; - Dictionary queryFields = new Dictionary(); - queryFields.Add(Fields.ENRICHED_URL_RELATIONS_RELATION_SUBJECT_TEXT, "Obama"); - queryFields.Add(Fields.ENRICHED_URL_CLEANEDTITLE, "Washington"); + void Start() + { + LogSystem.InstallDefaultReactors(); - if (!m_AlchemyAPI.GetNews(OnGetNews, returnFields, queryFields)) - Log.Debug("ExampleAlchemyData", "Failed to get news!"); - } + string[] returnFields = { Fields.ENRICHED_URL_ENTITIES, Fields.ENRICHED_URL_KEYWORDS }; + Dictionary queryFields = new Dictionary(); + queryFields.Add(Fields.ENRICHED_URL_RELATIONS_RELATION_SUBJECT_TEXT, "Obama"); + queryFields.Add(Fields.ENRICHED_URL_CLEANEDTITLE, "Washington"); - private void OnGetNews(NewsResponse newsData, string data) - { - if(newsData != null) - Log.Debug("ExampleAlchemyData", "status: {0}", newsData.status); - } + if (!m_AlchemyAPI.GetNews(OnGetNews, returnFields, queryFields)) + Log.Debug("ExampleAlchemyData", "Failed to get news!"); + } + + private void OnGetNews(NewsResponse newsData, string data) + { + if (newsData != null) + Log.Debug("ExampleAlchemyData", "status: {0}", newsData.status); + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleAlchemyLanguage.cs b/Examples/ServiceExamples/Scripts/ExampleAlchemyLanguage.cs index e87375f9a..44a4109c5 100755 --- a/Examples/ServiceExamples/Scripts/ExampleAlchemyLanguage.cs +++ b/Examples/ServiceExamples/Scripts/ExampleAlchemyLanguage.cs @@ -16,7 +16,6 @@ */ using UnityEngine; -using System.Collections; using IBM.Watson.DeveloperCloud.Services.AlchemyAPI.v1; using IBM.Watson.DeveloperCloud.Logging; @@ -24,584 +23,584 @@ #pragma warning disable 0414 public class ExampleAlchemyLanguage : MonoBehaviour { - private AlchemyAPI m_AlchemyAPI = new AlchemyAPI(); - private string m_ExampleURL_unitySDK = "https://developer.ibm.com/open/2016/01/21/introducing-watson-unity-sdk/"; - private string m_ExampleURL_watsonJeopardy = "http://www.nytimes.com/2011/02/17/science/17jeopardy-watson.html"; - private string m_ExampleURL_microformats = "http://microformats.org/wiki/hcard"; - private string m_ExampleText_unitySDK = "Game on! Introducing Watson Unity SDK, \nRICHARD LYLE / JANUARY 21, 2016 \nAfter several months of work we are happy to present the Watson Unity SDK, an SDK to enable the Unity community to access the Watson Developer Cloud and build a cognitive application in Unity.\n\nI’ve been involved in the game industry for 22+ years now, but I can tell you in all honestly working in the Watson Innovation Labs and on this project has been the highlight of my career. This SDK really represents the first phase in what we plan to bring to the community, which in the end will be a framework for building a full cognitive application.\n\nYou as a developer will find very simple C# service abstractions for accessing Dialog, Speech To Text, Text to Speech, Language Translation, and Natural Language Classification services. Additionally, we’ve implemented something we are calling a Widget, which has inputs and outputs and performs some basic function.\n\nThese widgets can be connected together to form a graph for the data that’s routed for a given cognitive application. The widgets will attempt to automatically connect to each other, or you as a developer can override that behavior and manually take control of the process. We’ve implemented widgets for all of the basic services and provide a couple of example applications showing how they can work together.\n\nWe plan to continue to expand and build on the Watson Unity SDK. We invite you to join us in contributing to and using the SDK, or by simply giving us your feedback. We’d love to have you on board for this ride!"; - private string m_ExampleText_watsonJeopardy = "Computer Wins on 'Jeopardy!': Trivial, It's Not\nBy JOHN MARKOFF\nYORKTOWN HEIGHTS, N.Y. — In the end, the humans on \"Jeopardy!\" surrendered meekly.\n\nFacing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\"\n\nThis article has been revised to reflect the following correction:\n\nCorrection: February 24, 2011\n\n\nAn article last Thursday about the I.B.M. computer Watson misidentified the academic field vindicated by Watson's besting of two human opponents on \"Jeopardy!\" It is artificial intelligence — not computer science, a broader field that includes artificial intelligence."; - void Start() - { - LogSystem.InstallDefaultReactors(); - string unitySDK_release_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/unitySDK_release.html"; - string watson_beats_jeopardy_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; - string microformats_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/microformats.html"; - string ycombinator_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/ycombinator_news.html"; - //// Get Author URL POST - //if (!m_AlchemyAPI.GetAuthors(OnGetAuthors, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get authors URL POST!"); - - ////Get Author HTML POST - //if (!m_AlchemyAPI.GetAuthors(OnGetAuthors, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get authors HTML POST!"); - - ////Get Concepts Text POST - if (!m_AlchemyAPI.GetRankedConcepts(OnGetConcepts, m_ExampleText_watsonJeopardy)) - Log.Debug("ExampleAlchemyLanguage", "Failed to get concepts Text POST!"); - - ////Get Concepts HTML POST - //if (!m_AlchemyAPI.GetRankedConcepts(OnGetConcepts, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get concepts HTML POST!"); - - ////Get Concepts URL POST - //if (!m_AlchemyAPI.GetRankedConcepts(OnGetCzoncepts, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get concepts HTML POST!"); - - ////Get Date URL POST - //if (!m_AlchemyAPI.GetDates(OnGetDates, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get dates by URL POST"); - - ////Get Date Text POST - //if (!m_AlchemyAPI.GetDates(OnGetDates, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get dates by text POST"); - - ////Get Date HTML POST - //if (!m_AlchemyAPI.GetDates(OnGetDates, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get dates by HTML POST"); - - ////Get Emotions URL POST - //if (!m_AlchemyAPI.GetEmotions(OnGetEmotions, m_ExampleURL_watsonJeopardy, true)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get emotions by URL POST"); - - ////Get Emotions Text POST - //if (!m_AlchemyAPI.GetEmotions(OnGetEmotions, m_ExampleText_watsonJeopardy, true)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get emotions by text POST"); - - ////Get Emotions HTML POST - //if (!m_AlchemyAPI.GetEmotions(OnGetEmotions, watson_beats_jeopardy_html, true)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get emotions by HTML POST"); - - ////Extract Entities URL POST - //if (!m_AlchemyAPI.ExtractEntities(OnExtractEntities, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get entities by URL POST"); - - ////Extract Entities Text POST - //if (!m_AlchemyAPI.ExtractEntities(OnExtractEntities, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get entities by text POST"); - - ////Extract Entities HTML POST - //if (!m_AlchemyAPI.ExtractEntities(OnExtractEntities, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get entities by HTML POST"); - - ////Detect Feeds URL POST - //if (!m_AlchemyAPI.DetectFeeds(OnDetectFeeds, "http://time.com/newsfeed/")) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get feeds by URL POST"); - - ////Detect Feeds HTML POST - ////if (!m_AlchemyAPI.DetectFeeds(OnDetectFeeds, ycombinator_html)) - //// Log.Debug("ExampleAlchemyLanguage", "Failed to get feeds by URL POST"); - - ////Extract Keywords URL POST - //if (!m_AlchemyAPI.ExtractKeywords(OnExtractKeywords, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get keywords by URL POST"); - - ////Extract Keywords Text POST - //if (!m_AlchemyAPI.ExtractKeywords(OnExtractKeywords, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get keywords by text POST"); - - ////Extract Keywords HTML POST - //if (!m_AlchemyAPI.ExtractKeywords(OnExtractKeywords, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get keywords by HTML POST"); - - ////Extract Languages URL POST - //if (!m_AlchemyAPI.GetLanguages(OnGetLanguages, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get languages by text POST"); - - ////Extract Languages Text POST - //if (!m_AlchemyAPI.GetLanguages(OnGetLanguages, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get languages by text POST"); - - ////Extract Languages HTML POST - //if (!m_AlchemyAPI.GetLanguages(OnGetLanguages, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get languages by HTML POST"); - - ////Get Microformats URL POST - //if (!m_AlchemyAPI.GetMicroformats(OnGetMicroformats, m_ExampleURL_microformats)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get microformats by text POST"); + private AlchemyAPI m_AlchemyAPI = new AlchemyAPI(); + private string m_ExampleURL_unitySDK = "https://developer.ibm.com/open/2016/01/21/introducing-watson-unity-sdk/"; + private string m_ExampleURL_watsonJeopardy = "http://www.nytimes.com/2011/02/17/science/17jeopardy-watson.html"; + private string m_ExampleURL_microformats = "http://microformats.org/wiki/hcard"; + private string m_ExampleText_unitySDK = "Game on! Introducing Watson Unity SDK, \nRICHARD LYLE / JANUARY 21, 2016 \nAfter several months of work we are happy to present the Watson Unity SDK, an SDK to enable the Unity community to access the Watson Developer Cloud and build a cognitive application in Unity.\n\nI’ve been involved in the game industry for 22+ years now, but I can tell you in all honestly working in the Watson Innovation Labs and on this project has been the highlight of my career. This SDK really represents the first phase in what we plan to bring to the community, which in the end will be a framework for building a full cognitive application.\n\nYou as a developer will find very simple C# service abstractions for accessing Dialog, Speech To Text, Text to Speech, Language Translation, and Natural Language Classification services. Additionally, we’ve implemented something we are calling a Widget, which has inputs and outputs and performs some basic function.\n\nThese widgets can be connected together to form a graph for the data that’s routed for a given cognitive application. The widgets will attempt to automatically connect to each other, or you as a developer can override that behavior and manually take control of the process. We’ve implemented widgets for all of the basic services and provide a couple of example applications showing how they can work together.\n\nWe plan to continue to expand and build on the Watson Unity SDK. We invite you to join us in contributing to and using the SDK, or by simply giving us your feedback. We’d love to have you on board for this ride!"; + private string m_ExampleText_watsonJeopardy = "Computer Wins on 'Jeopardy!': Trivial, It's Not\nBy JOHN MARKOFF\nYORKTOWN HEIGHTS, N.Y. — In the end, the humans on \"Jeopardy!\" surrendered meekly.\n\nFacing certain defeat at the hands of a room-size I.B.M. computer on Wednesday evening, Ken Jennings, famous for winning 74 games in a row on the TV quiz show, acknowledged the obvious. \"I, for one, welcome our new computer overlords,\" he wrote on his video screen, borrowing a line from a \"Simpsons\" episode.\n\nFrom now on, if the answer is \"the computer champion on \"Jeopardy!,\" the question will be, \"What is Watson?\"\n\nFor I.B.M., the showdown was not merely a well-publicized stunt and a $1 million prize, but proof that the company has taken a big step toward a world in which intelligent machines will understand and respond to humans, and perhaps inevitably, replace some of them.\n\nWatson, specifically, is a \"question answering machine\" of a type that artificial intelligence researchers have struggled with for decades — a computer akin to the one on \"Star Trek\" that can understand questions posed in natural language and answer them.\n\nWatson showed itself to be imperfect, but researchers at I.B.M. and other companies are already developing uses for Watson's technologies that could have a significant impact on the way doctors practice and consumers buy products.\n\n\"Cast your mind back 20 years and who would have thought this was possible?\" said Edward Feigenbaum, a Stanford University computer scientist and a pioneer in the field.\n\nIn its \"Jeopardy!\" project, I.B.M. researchers were tackling a game that requires not only encyclopedic recall, but also the ability to untangle convoluted and often opaque statements, a modicum of luck, and quick, strategic button pressing.\n\nThe contest, which was taped in January here at the company's T. J. Watson Research Laboratory before an audience of I.B.M. executives and company clients, played out in three televised episodes concluding Wednesday. At the end of the first day, Watson was in a tie with Brad Rutter, another ace human player, at $5,000 each, with Mr. Jennings trailing with $2,000.\n\nBut on the second day, Watson went on a tear. By night's end, Watson had a commanding lead with a total of $35,734, compared with Mr. Rutter's $10,400 and Mr. Jennings's $4,800.\n\nVictory was not cemented until late in the third match, when Watson was in Nonfiction. \"Same category for $1,200,\" it said in a manufactured tenor, and lucked into a Daily Double. Mr. Jennings grimaced.\n\nEven later in the match, however, had Mr. Jennings won another key Daily Double it might have come down to Final Jeopardy, I.B.M. researchers acknowledged.\n\nThe final tally was $77,147 to Mr. Jennings's $24,000 and Mr. Rutter's $21,600.\n\nMore than anything, the contest was a vindication for the academic field of artificial intelligence, which began with great promise in the 1960s with the vision of creating a thinking machine and which became the laughingstock of Silicon Valley in the 1980s, when a series of heavily financed start-up companies went bankrupt.\n\nDespite its intellectual prowess, Watson was by no means omniscient. On Tuesday evening during Final Jeopardy, the category was U.S. Cities and the clue was: \"Its largest airport is named for a World War II hero; its second largest for a World War II battle.\"\n\nWatson drew guffaws from many in the television audience when it responded \"What is Toronto?????\"\n\nThe string of question marks indicated that the system had very low confidence in its response, I.B.M. researchers said, but because it was Final Jeopardy, it was forced to give a response. The machine did not suffer much damage. It had wagered just $947 on its result. (The correct answer is, \"What is Chicago?\")\n\n\"We failed to deeply understand what was going on there,\" said David Ferrucci, an I.B.M. researcher who led the development of Watson. \"The reality is that there's lots of data where the title is U.S. cities and the answers are countries, European cities, people, mayors. Even though it says U.S. cities, we had very little confidence that that's the distinguishing feature.\"\n\nThe researchers also acknowledged that the machine had benefited from the \"buzzer factor.\"\n\nBoth Mr. Jennings and Mr. Rutter are accomplished at anticipating the light that signals it is possible to \"buzz in,\" and can sometimes get in with virtually zero lag time. The danger is to buzz too early, in which case the contestant is penalized and \"locked out\" for roughly a quarter of a second.\n\nWatson, on the other hand, does not anticipate the light, but has a weighted scheme that allows it, when it is highly confident, to hit the buzzer in as little as 10 milliseconds, making it very hard for humans to beat. When it was less confident, it took longer to buzz in. In the second round, Watson beat the others to the buzzer in 24 out of 30 Double Jeopardy questions.\n\n\"It sort of wants to get beaten when it doesn't have high confidence,\" Dr. Ferrucci said. \"It doesn't want to look stupid.\"\n\nBoth human players said that Watson's button pushing skill was not necessarily an unfair advantage. \"I beat Watson a couple of times,\" Mr. Rutter said.\n\nWhen Watson did buzz in, it made the most of it. Showing the ability to parse language, it responded to, \"A recent best seller by Muriel Barbery is called 'This of the Hedgehog,' \" with \"What is Elegance?\"\n\nIt showed its facility with medical diagnosis. With the answer: \"You just need a nap. You don't have this sleep disorder that can make sufferers nod off while standing up,\" Watson replied, \"What is narcolepsy?\"\n\nThe coup de grâce came with the answer, \"William Wilkenson's 'An Account of the Principalities of Wallachia and Moldavia' inspired this author's most famous novel.\" Mr. Jennings wrote, correctly, Bram Stoker, but realized that he could not catch up with Watson's winnings and wrote out his surrender.\n\nBoth players took the contest and its outcome philosophically.\n\n\"I had a great time and I would do it again in a heartbeat,\" said Mr. Jennings. \"It's not about the results; this is about being part of the future.\"\n\nFor I.B.M., the future will happen very quickly, company executives said. On Thursday it plans to announce that it will collaborate with Columbia University and the University of Maryland to create a physician's assistant service that will allow doctors to query a cybernetic assistant. The company also plans to work with Nuance Communications Inc. to add voice recognition to the physician's assistant, possibly making the service available in as little as 18 months.\n\n\"I have been in medical education for 40 years and we're still a very memory-based curriculum,\" said Dr. Herbert Chase, a professor of clinical medicine at Columbia University who is working with I.B.M. on the physician's assistant. \"The power of Watson- like tools will cause us to reconsider what it is we want students to do.\"\n\nI.B.M. executives also said they are in discussions with a major consumer electronics retailer to develop a version of Watson, named after I.B.M.'s founder, Thomas J. Watson, that would be able to interact with consumers on a variety of subjects like buying decisions and technical support.\n\nDr. Ferrucci sees none of the fears that have been expressed by theorists and science fiction writers about the potential of computers to usurp humans.\n\n\"People ask me if this is HAL,\" he said, referring to the computer in \"2001: A Space Odyssey.\" \"HAL's not the focus; the focus is on the computer on 'Star Trek,' where you have this intelligent information seek dialogue, where you can ask follow-up questions and the computer can look at all the evidence and tries to ask follow-up questions. That's very cool.\"\n\nThis article has been revised to reflect the following correction:\n\nCorrection: February 24, 2011\n\n\nAn article last Thursday about the I.B.M. computer Watson misidentified the academic field vindicated by Watson's besting of two human opponents on \"Jeopardy!\" It is artificial intelligence — not computer science, a broader field that includes artificial intelligence."; + void Start() + { + LogSystem.InstallDefaultReactors(); + string unitySDK_release_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/unitySDK_release.html"; + string watson_beats_jeopardy_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; + string microformats_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/microformats.html"; + string ycombinator_html = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/ycombinator_news.html"; + //// Get Author URL POST + //if (!m_AlchemyAPI.GetAuthors(OnGetAuthors, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get authors URL POST!"); + + ////Get Author HTML POST + //if (!m_AlchemyAPI.GetAuthors(OnGetAuthors, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get authors HTML POST!"); + + ////Get Concepts Text POST + if (!m_AlchemyAPI.GetRankedConcepts(OnGetConcepts, m_ExampleText_watsonJeopardy)) + Log.Debug("ExampleAlchemyLanguage", "Failed to get concepts Text POST!"); + + ////Get Concepts HTML POST + //if (!m_AlchemyAPI.GetRankedConcepts(OnGetConcepts, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get concepts HTML POST!"); + + ////Get Concepts URL POST + //if (!m_AlchemyAPI.GetRankedConcepts(OnGetCzoncepts, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get concepts HTML POST!"); + + ////Get Date URL POST + //if (!m_AlchemyAPI.GetDates(OnGetDates, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get dates by URL POST"); + + ////Get Date Text POST + //if (!m_AlchemyAPI.GetDates(OnGetDates, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get dates by text POST"); + + ////Get Date HTML POST + //if (!m_AlchemyAPI.GetDates(OnGetDates, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get dates by HTML POST"); + + ////Get Emotions URL POST + //if (!m_AlchemyAPI.GetEmotions(OnGetEmotions, m_ExampleURL_watsonJeopardy, true)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get emotions by URL POST"); + + ////Get Emotions Text POST + //if (!m_AlchemyAPI.GetEmotions(OnGetEmotions, m_ExampleText_watsonJeopardy, true)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get emotions by text POST"); + + ////Get Emotions HTML POST + //if (!m_AlchemyAPI.GetEmotions(OnGetEmotions, watson_beats_jeopardy_html, true)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get emotions by HTML POST"); + + ////Extract Entities URL POST + //if (!m_AlchemyAPI.ExtractEntities(OnExtractEntities, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get entities by URL POST"); + + ////Extract Entities Text POST + //if (!m_AlchemyAPI.ExtractEntities(OnExtractEntities, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get entities by text POST"); + + ////Extract Entities HTML POST + //if (!m_AlchemyAPI.ExtractEntities(OnExtractEntities, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get entities by HTML POST"); + + ////Detect Feeds URL POST + //if (!m_AlchemyAPI.DetectFeeds(OnDetectFeeds, "http://time.com/newsfeed/")) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get feeds by URL POST"); + + ////Detect Feeds HTML POST + ////if (!m_AlchemyAPI.DetectFeeds(OnDetectFeeds, ycombinator_html)) + //// Log.Debug("ExampleAlchemyLanguage", "Failed to get feeds by URL POST"); + + ////Extract Keywords URL POST + //if (!m_AlchemyAPI.ExtractKeywords(OnExtractKeywords, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get keywords by URL POST"); + + ////Extract Keywords Text POST + //if (!m_AlchemyAPI.ExtractKeywords(OnExtractKeywords, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get keywords by text POST"); + + ////Extract Keywords HTML POST + //if (!m_AlchemyAPI.ExtractKeywords(OnExtractKeywords, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get keywords by HTML POST"); + + ////Extract Languages URL POST + //if (!m_AlchemyAPI.GetLanguages(OnGetLanguages, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get languages by text POST"); + + ////Extract Languages Text POST + //if (!m_AlchemyAPI.GetLanguages(OnGetLanguages, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get languages by text POST"); + + ////Extract Languages HTML POST + //if (!m_AlchemyAPI.GetLanguages(OnGetLanguages, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get languages by HTML POST"); + + ////Get Microformats URL POST + //if (!m_AlchemyAPI.GetMicroformats(OnGetMicroformats, m_ExampleURL_microformats)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get microformats by text POST"); + + ////Get Microformats HTML POST + ////if (!m_AlchemyAPI.GetMicroformats(OnGetMicroformats, microformats_html)) + //// Log.Debug("ExampleAlchemyLanguage", "Failed to get microformats by text POST"); + + ////Get PublicationDate URL POST + //if (!m_AlchemyAPI.GetPublicationDate(OnGetPublicationDate, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get publication dates by url POST"); + + ////Get PublicationDate HTML POST + //if (!m_AlchemyAPI.GetPublicationDate(OnGetPublicationDate, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get publication dates by html POST"); - ////Get Microformats HTML POST - ////if (!m_AlchemyAPI.GetMicroformats(OnGetMicroformats, microformats_html)) - //// Log.Debug("ExampleAlchemyLanguage", "Failed to get microformats by text POST"); - - ////Get PublicationDate URL POST - //if (!m_AlchemyAPI.GetPublicationDate(OnGetPublicationDate, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get publication dates by url POST"); + ////Get Relations URL POST + //if (!m_AlchemyAPI.GetRelations(OnGetRelations, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get relations by text POST"); - ////Get PublicationDate HTML POST - //if (!m_AlchemyAPI.GetPublicationDate(OnGetPublicationDate, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get publication dates by html POST"); + ////Get Relations Text POST + //if (!m_AlchemyAPI.GetRelations(OnGetRelations, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get relations by text POST"); - ////Get Relations URL POST - //if (!m_AlchemyAPI.GetRelations(OnGetRelations, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get relations by text POST"); + ////Get Relations HTML POST + //if (!m_AlchemyAPI.GetRelations(OnGetRelations, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get relations by HTML POST"); - ////Get Relations Text POST - //if (!m_AlchemyAPI.GetRelations(OnGetRelations, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get relations by text POST"); + ////Get Sentiment URL POST + //if (!m_AlchemyAPI.GetTextSentiment(OnGetTextSentiment, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get sentiment by text POST"); - ////Get Relations HTML POST - //if (!m_AlchemyAPI.GetRelations(OnGetRelations, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get relations by HTML POST"); + ////Get Sentiment Text POST + //if (!m_AlchemyAPI.GetTextSentiment(OnGetTextSentiment, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get sentiment by text POST"); - ////Get Sentiment URL POST - //if (!m_AlchemyAPI.GetTextSentiment(OnGetTextSentiment, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get sentiment by text POST"); + ////Get Sentiment HTML POST + //if (!m_AlchemyAPI.GetTextSentiment(OnGetTextSentiment, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get sentiment by HTML POST"); - ////Get Sentiment Text POST - //if (!m_AlchemyAPI.GetTextSentiment(OnGetTextSentiment, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get sentiment by text POST"); + ////Get Targeted Sentiment URL POST + //if (!m_AlchemyAPI.GetTargetedSentiment(OnGetTargetedSentiment, m_ExampleURL_watsonJeopardy, "Jeopardy|Jennings|Watson")) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get targeted sentiment by text POST"); - ////Get Sentiment HTML POST - //if (!m_AlchemyAPI.GetTextSentiment(OnGetTextSentiment, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get sentiment by HTML POST"); + ////Get Targeted Sentiment Text POST + //if (!m_AlchemyAPI.GetTargetedSentiment(OnGetTargetedSentiment, m_ExampleText_watsonJeopardy, "Jeopardy|Jennings|Watson")) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get targeted sentiment by text POST"); - ////Get Targeted Sentiment URL POST - //if (!m_AlchemyAPI.GetTargetedSentiment(OnGetTargetedSentiment, m_ExampleURL_watsonJeopardy, "Jeopardy|Jennings|Watson")) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get targeted sentiment by text POST"); + ////Get Targeted Sentiment HTML POST + //if (!m_AlchemyAPI.GetTargetedSentiment(OnGetTargetedSentiment, watson_beats_jeopardy_html, "Jeopardy|Jennings|Watson")) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get targeted sentiment by HTML POST"); - ////Get Targeted Sentiment Text POST - //if (!m_AlchemyAPI.GetTargetedSentiment(OnGetTargetedSentiment, m_ExampleText_watsonJeopardy, "Jeopardy|Jennings|Watson")) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get targeted sentiment by text POST"); - - ////Get Targeted Sentiment HTML POST - //if (!m_AlchemyAPI.GetTargetedSentiment(OnGetTargetedSentiment, watson_beats_jeopardy_html, "Jeopardy|Jennings|Watson")) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get targeted sentiment by HTML POST"); - - ////Get Taxonomy URL POST - //if (!m_AlchemyAPI.GetRankedTaxonomy(OnGetRankedTaxonomy, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get ranked taxonomy by text POST"); - - ////Get Taxonomy Text POST - //if (!m_AlchemyAPI.GetRankedTaxonomy(OnGetRankedTaxonomy, m_ExampleText_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get ranked taxonomy by text POST"); - - ////Get Taxonomy HTML POST - //if (!m_AlchemyAPI.GetRankedTaxonomy(OnGetRankedTaxonomy, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get ranked taxonomy by HTML POST"); - - ////Get Text HTML POST - //if (!m_AlchemyAPI.GetText(OnGetText, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get text by text POST"); - - ////Get Text URL POST - //if (!m_AlchemyAPI.GetText(OnGetText, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get text by text POST"); - - ////Get Raw Text HTML POST - //if (!m_AlchemyAPI.GetRawText(OnGetText, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get raw text by text POST"); - - ////Get Raw Text URL POST - //if (!m_AlchemyAPI.GetRawText(OnGetText, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get raw text by text POST"); - - ////Get Title HTML POST - //if (!m_AlchemyAPI.GetTitle(OnGetTitle, watson_beats_jeopardy_html)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get title by text POST"); - - ////Get Title URL POST - //if (!m_AlchemyAPI.GetTitle(OnGetTitle, m_ExampleURL_watsonJeopardy)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get title by text POST"); - - //// Get Combined Data URL POST - //if (!m_AlchemyAPI.GetCombinedData(OnGetCombinedData, m_ExampleURL_watsonJeopardy, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data by text POST"); - - ////Get Combined Data Text POST - //if (!m_AlchemyAPI.GetCombinedData(OnGetCombinedData, m_ExampleText_watsonJeopardy, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data by text POST"); - - ////Get Combined Data HTML POST - //if (!m_AlchemyAPI.GetCombinedData(OnGetCombinedData, watson_beats_jeopardy_html, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true)) - // Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data by HTML POST"); - } - - private void OnGetAuthors(AuthorsData authors, string data) - { - if (authors != null) - { - Log.Debug("ExampleAlchemyLanguage", "data: {0}", data); - if (authors.authors.names.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No authors found!"); - - foreach (string name in authors.authors.names) - Log.Debug("ExampleAlchemyLanguage", "Author " + name + " found!"); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Author!"); - } - } - - private void OnGetConcepts(ConceptsData concepts, string data) - { - if (concepts != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", concepts.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", concepts.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", concepts.language); - if (concepts.concepts.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No concepts found!"); - - foreach (Concept concept in concepts.concepts) - Log.Debug("ExampleAlchemyLanguage", "Concept: {0}, Relevance: {1}", concept.text, concept.relevance); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Concepts!"); - } - } - - private void OnGetDates(DateData dates, string data) - { - if (dates != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", dates.status); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", dates.language); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", dates.url); - if (dates.dates == null || dates.dates.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No dates found!"); - else - foreach (Date date in dates.dates) - Log.Debug("ExampleAlchemyLanguage", "Text: {0}, Date: {1}", date.text, date.date); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Dates!"); - } - } - - private void OnGetEmotions(EmotionData emotions, string data) - { - if (emotions != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", emotions.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", emotions.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", emotions.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", emotions.text); - if (emotions.docEmotions == null) - Log.Debug("ExampleAlchemyLanguage", "No emotions found!"); - else - { - Log.Debug("ExampleAlchemyLanguage", "anger: {0}", emotions.docEmotions.anger); - Log.Debug("ExampleAlchemyLanguage", "disgust: {0}", emotions.docEmotions.disgust); - Log.Debug("ExampleAlchemyLanguage", "fear: {0}", emotions.docEmotions.fear); - Log.Debug("ExampleAlchemyLanguage", "joy: {0}", emotions.docEmotions.joy); - Log.Debug("ExampleAlchemyLanguage", "sadness: {0}", emotions.docEmotions.sadness); - } - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Emotions!"); - } - } - - private void OnExtractEntities(EntityData entityData, string data) - { - if (entityData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", entityData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", entityData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", entityData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", entityData.text); - if (entityData == null || entityData.entities.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No entities found!"); - else - foreach (Entity entity in entityData.entities) - Log.Debug("ExampleAlchemyLanguage", "text: {0}, type: {1}", entity.text, entity.type); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Emotions!"); - } - } - - private void OnDetectFeeds(FeedData feedData, string data) - { - if (feedData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", feedData.status); - if (feedData == null || feedData.feeds.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No feeds found!"); - else - foreach (Feed feed in feedData.feeds) - Log.Debug("ExampleAlchemyLanguage", "text: {0}", feed.feed); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Feeds!"); - } - } - - private void OnExtractKeywords(KeywordData keywordData, string data) - { - if (keywordData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", keywordData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", keywordData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", keywordData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", keywordData.text); - if (keywordData == null || keywordData.keywords.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No keywords found!"); - else - foreach (Keyword keyword in keywordData.keywords) - Log.Debug("ExampleAlchemyLanguage", "text: {0}, relevance: {1}", keyword.text, keyword.relevance); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Keywords!"); - } - } - - private void OnGetLanguages(LanguageData languages, string data) - { - if (languages != null) - { - if (string.IsNullOrEmpty(languages.language)) - Log.Debug("ExampleAlchemyLanguage", "No languages detected!"); - else - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", languages.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", languages.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", languages.language); - Log.Debug("ExampleAlchemyLanguage", "ethnologue: {0}", languages.ethnologue); - Log.Debug("ExampleAlchemyLanguage", "iso_639_1: {0}", languages.iso_639_1); - Log.Debug("ExampleAlchemyLanguage", "iso_639_2: {0}", languages.iso_639_2); - Log.Debug("ExampleAlchemyLanguage", "iso_639_3: {0}", languages.iso_639_3); - Log.Debug("ExampleAlchemyLanguage", "native_speakers: {0}", languages.native_speakers); - Log.Debug("ExampleAlchemyLanguage", "wikipedia: {0}", languages.wikipedia); - } - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Dates!"); - } - } - - private void OnGetMicroformats(MicroformatData microformats, string data) - { - if (microformats != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", microformats.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", microformats.url); - if (microformats.microformats.Length == 0) - Log.Warning("ExampleAlchemyLanguage", "No microformats found!"); - else - { - foreach (Microformat microformat in microformats.microformats) - Log.Debug("ExampleAlchemyLanguage", "field: {0}, data: {1}.", microformat.field, microformat.data); - } - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Microformats!"); - } - } - - private void OnGetPublicationDate(PubDateData pubDates, string data) - { - if (pubDates != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", pubDates.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", pubDates.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", pubDates.language); - if (pubDates.publicationDate != null) - Log.Debug("ExampleAlchemyLanguage", "date: {0}, confident: {1}", pubDates.publicationDate.date, pubDates.publicationDate.confident); - else - Log.Debug("ExampleAlchemyLanguage", "Failed to find Publication Dates!"); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Publication Dates!"); - } - } - - private void OnGetRelations(RelationsData relationsData, string data) - { - if (relationsData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", relationsData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", relationsData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", relationsData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", relationsData.text); - if (relationsData.relations == null || relationsData.relations.Length == 0) - Log.Debug("ExampleAlchemyLanguage", "No relations found!"); - else - foreach (Relation relation in relationsData.relations) - if (relation.subject != null && !string.IsNullOrEmpty(relation.subject.text)) - Log.Debug("ExampleAlchemyLanguage", "Text: {0}, Date: {1}", relation.sentence, relation.subject.text); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); - } - } - - private void OnGetTextSentiment(SentimentData sentimentData, string data) - { - if (sentimentData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", sentimentData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", sentimentData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", sentimentData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", sentimentData.text); - if (sentimentData.docSentiment == null) - Log.Debug("ExampleAlchemyLanguage", "No sentiment found!"); - else - if (sentimentData.docSentiment != null && !string.IsNullOrEmpty(sentimentData.docSentiment.type)) - Log.Debug("ExampleAlchemyLanguage", "Sentiment: {0}, Score: {1}", sentimentData.docSentiment.type, sentimentData.docSentiment.score); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); - } - } - - private void OnGetTargetedSentiment(TargetedSentimentData sentimentData, string data) - { - if (sentimentData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", sentimentData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", sentimentData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", sentimentData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", sentimentData.text); - if (sentimentData.results == null) - Log.Debug("ExampleAlchemyLanguage", "No sentiment found!"); - else - if (sentimentData.results == null || sentimentData.results.Length == 0) - Log.Warning("ExampleAlchemyLanguage", "No sentiment results!"); - else - foreach (TargetedSentiment result in sentimentData.results) - Log.Debug("ExampleAlchemyLanguage", "text: {0}, sentiment: {1}, score: {2}", result.text, result.sentiment.score, result.sentiment.type); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); - } - } - - private void OnGetRankedTaxonomy(TaxonomyData taxonomyData, string data) - { - if (taxonomyData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", taxonomyData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", taxonomyData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", taxonomyData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", taxonomyData.text); - if (taxonomyData.taxonomy == null) - Log.Debug("ExampleAlchemyLanguage", "No taxonomy found!"); - else - if (taxonomyData.taxonomy == null || taxonomyData.taxonomy.Length == 0) - Log.Warning("ExampleAlchemyLanguage", "No taxonomy results!"); - else - foreach (Taxonomy taxonomy in taxonomyData.taxonomy) - Log.Debug("ExampleAlchemyLanguage", "label: {0}, score: {1}", taxonomy.label, taxonomy.score); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); - } - } - - private void OnGetText(TextData textData, string data) - { - if (textData != null) - { - Log.Debug("ExampleAlchemyLanuguage", "status: {0}", textData.status); - Log.Debug("ExampleAlchemyLanuguage", "url: {0}", textData.url); - Log.Debug("ExampleAlchemyLanuguage", "text: {0}", textData.text); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find text!"); - } - - } - - private void OnGetTitle(Title titleData, string data) - { - if (titleData != null) - { - Log.Debug("ExampleAlchemyLanuguage", "status: {0}", titleData.status); - Log.Debug("ExampleAlchemyLanuguage", "url: {0}", titleData.url); - Log.Debug("ExampleAlchemyLanuguage", "text: {0}", titleData.title); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to find title!"); - } - - } - - private void OnGetCombinedData(CombinedCallData combinedData, string data) - { - if (combinedData != null) - { - Log.Debug("ExampleAlchemyLanguage", "status: {0}", combinedData.status); - Log.Debug("ExampleAlchemyLanguage", "url: {0}", combinedData.url); - Log.Debug("ExampleAlchemyLanguage", "language: {0}", combinedData.language); - Log.Debug("ExampleAlchemyLanguage", "text: {0}", combinedData.text); - Log.Debug("ExampleAlchemyLanguage", "image: {0}", combinedData.image); - - if (combinedData.imageKeywords != null && combinedData.imageKeywords.Length > 0) - foreach (ImageKeyword imageKeyword in combinedData.imageKeywords) - Log.Debug("ExampleAlchemyLanguage", "ImageKeyword: {0}, Score: {1}", imageKeyword.text, imageKeyword.score); - - if (combinedData.publicationDate != null) - Log.Debug("ExampleAlchemyLanguage", "publicationDate: {0}, Score: {1}", combinedData.publicationDate.date, combinedData.publicationDate.confident); - - if (combinedData.authors != null && combinedData.authors.names.Length > 0) - foreach (string authors in combinedData.authors.names) - Log.Debug("ExampleAlchemyLanguage", "Authors: {0}", authors); - - if (combinedData.docSentiment != null) - Log.Debug("ExampleAlchemyLanguage", "DocSentiment: {0}, Score: {1}, Mixed: {2}", combinedData.docSentiment.type, combinedData.docSentiment.score, combinedData.docSentiment.mixed); - - if (combinedData.feeds != null && combinedData.feeds.Length > 0) - foreach (Feed feed in combinedData.feeds) - Log.Debug("ExampleAlchemyLanguage", "Feeds: {0}", feed.feed); - - if (combinedData.keywords != null && combinedData.keywords.Length > 0) - foreach (Keyword keyword in combinedData.keywords) - Log.Debug("ExampleAlchemyLanguage", "Keyword: {0}, relevance: {1}", keyword.text, keyword.relevance); - - if (combinedData.concepts != null && combinedData.concepts.Length > 0) - foreach (Concept concept in combinedData.concepts) - Log.Debug("ExampleAlchemyLanguage", "Concept: {0}, Relevance: {1}", concept.text, concept.relevance); - - if (combinedData.entities != null && combinedData.entities.Length > 0) - foreach (Entity entity in combinedData.entities) - Log.Debug("ExampleAlchemyLanguage", "Entity: {0}, Type: {1}, Relevance: {2}", entity.text, entity.type, entity.relevance); - - if (combinedData.relations != null && combinedData.relations.Length > 0) - foreach (Relation relation in combinedData.relations) - Log.Debug("ExampleAlchemyLanguage", "Relations: {0}", relation.subject.text); - - if (combinedData.taxonomy != null && combinedData.taxonomy.Length > 0) - foreach (Taxonomy taxonomy in combinedData.taxonomy) - Log.Debug("ExampleAlchemyLanguage", "Taxonomy: {0}, Score: {1}, Confident: {2}", taxonomy.label, taxonomy.score, taxonomy.confident); - - if (combinedData.dates != null && combinedData.dates.Length > 0) - foreach (Date date in combinedData.dates) - Log.Debug("ExampleAlchemyLanguage", "Dates", date.text, date.date); - - if (combinedData.docEmotions != null && combinedData.docEmotions.Length > 0) - foreach (DocEmotions emotions in combinedData.docEmotions) - Log.Debug("ExampleAlchemyLanguage", "Doc Emotions: anger: {0}, disgust: {1}, fear: {2}, joy: {3}, sadness: {4}", emotions.anger, emotions.disgust, emotions.fear, emotions.joy, emotions.sadness); - } - else - { - Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data!"); - } + ////Get Taxonomy URL POST + //if (!m_AlchemyAPI.GetRankedTaxonomy(OnGetRankedTaxonomy, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get ranked taxonomy by text POST"); + + ////Get Taxonomy Text POST + //if (!m_AlchemyAPI.GetRankedTaxonomy(OnGetRankedTaxonomy, m_ExampleText_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get ranked taxonomy by text POST"); + + ////Get Taxonomy HTML POST + //if (!m_AlchemyAPI.GetRankedTaxonomy(OnGetRankedTaxonomy, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get ranked taxonomy by HTML POST"); + + ////Get Text HTML POST + //if (!m_AlchemyAPI.GetText(OnGetText, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get text by text POST"); + + ////Get Text URL POST + //if (!m_AlchemyAPI.GetText(OnGetText, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get text by text POST"); + + ////Get Raw Text HTML POST + //if (!m_AlchemyAPI.GetRawText(OnGetText, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get raw text by text POST"); + + ////Get Raw Text URL POST + //if (!m_AlchemyAPI.GetRawText(OnGetText, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get raw text by text POST"); + + ////Get Title HTML POST + //if (!m_AlchemyAPI.GetTitle(OnGetTitle, watson_beats_jeopardy_html)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get title by text POST"); + + ////Get Title URL POST + //if (!m_AlchemyAPI.GetTitle(OnGetTitle, m_ExampleURL_watsonJeopardy)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get title by text POST"); + + //// Get Combined Data URL POST + //if (!m_AlchemyAPI.GetCombinedData(OnGetCombinedData, m_ExampleURL_watsonJeopardy, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data by text POST"); + + ////Get Combined Data Text POST + //if (!m_AlchemyAPI.GetCombinedData(OnGetCombinedData, m_ExampleText_watsonJeopardy, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data by text POST"); + + ////Get Combined Data HTML POST + //if (!m_AlchemyAPI.GetCombinedData(OnGetCombinedData, watson_beats_jeopardy_html, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true)) + // Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data by HTML POST"); + } + + private void OnGetAuthors(AuthorsData authors, string data) + { + if (authors != null) + { + Log.Debug("ExampleAlchemyLanguage", "data: {0}", data); + if (authors.authors.names.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No authors found!"); + + foreach (string name in authors.authors.names) + Log.Debug("ExampleAlchemyLanguage", "Author " + name + " found!"); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Author!"); + } + } + + private void OnGetConcepts(ConceptsData concepts, string data) + { + if (concepts != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", concepts.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", concepts.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", concepts.language); + if (concepts.concepts.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No concepts found!"); + + foreach (Concept concept in concepts.concepts) + Log.Debug("ExampleAlchemyLanguage", "Concept: {0}, Relevance: {1}", concept.text, concept.relevance); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Concepts!"); + } + } + + private void OnGetDates(DateData dates, string data) + { + if (dates != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", dates.status); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", dates.language); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", dates.url); + if (dates.dates == null || dates.dates.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No dates found!"); + else + foreach (Date date in dates.dates) + Log.Debug("ExampleAlchemyLanguage", "Text: {0}, Date: {1}", date.text, date.date); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Dates!"); + } + } + + private void OnGetEmotions(EmotionData emotions, string data) + { + if (emotions != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", emotions.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", emotions.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", emotions.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", emotions.text); + if (emotions.docEmotions == null) + Log.Debug("ExampleAlchemyLanguage", "No emotions found!"); + else + { + Log.Debug("ExampleAlchemyLanguage", "anger: {0}", emotions.docEmotions.anger); + Log.Debug("ExampleAlchemyLanguage", "disgust: {0}", emotions.docEmotions.disgust); + Log.Debug("ExampleAlchemyLanguage", "fear: {0}", emotions.docEmotions.fear); + Log.Debug("ExampleAlchemyLanguage", "joy: {0}", emotions.docEmotions.joy); + Log.Debug("ExampleAlchemyLanguage", "sadness: {0}", emotions.docEmotions.sadness); + } + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Emotions!"); + } + } + + private void OnExtractEntities(EntityData entityData, string data) + { + if (entityData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", entityData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", entityData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", entityData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", entityData.text); + if (entityData == null || entityData.entities.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No entities found!"); + else + foreach (Entity entity in entityData.entities) + Log.Debug("ExampleAlchemyLanguage", "text: {0}, type: {1}", entity.text, entity.type); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Emotions!"); + } + } + + private void OnDetectFeeds(FeedData feedData, string data) + { + if (feedData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", feedData.status); + if (feedData == null || feedData.feeds.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No feeds found!"); + else + foreach (Feed feed in feedData.feeds) + Log.Debug("ExampleAlchemyLanguage", "text: {0}", feed.feed); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Feeds!"); + } + } + + private void OnExtractKeywords(KeywordData keywordData, string data) + { + if (keywordData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", keywordData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", keywordData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", keywordData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", keywordData.text); + if (keywordData == null || keywordData.keywords.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No keywords found!"); + else + foreach (Keyword keyword in keywordData.keywords) + Log.Debug("ExampleAlchemyLanguage", "text: {0}, relevance: {1}", keyword.text, keyword.relevance); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Keywords!"); + } + } + + private void OnGetLanguages(LanguageData languages, string data) + { + if (languages != null) + { + if (string.IsNullOrEmpty(languages.language)) + Log.Debug("ExampleAlchemyLanguage", "No languages detected!"); + else + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", languages.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", languages.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", languages.language); + Log.Debug("ExampleAlchemyLanguage", "ethnologue: {0}", languages.ethnologue); + Log.Debug("ExampleAlchemyLanguage", "iso_639_1: {0}", languages.iso_639_1); + Log.Debug("ExampleAlchemyLanguage", "iso_639_2: {0}", languages.iso_639_2); + Log.Debug("ExampleAlchemyLanguage", "iso_639_3: {0}", languages.iso_639_3); + Log.Debug("ExampleAlchemyLanguage", "native_speakers: {0}", languages.native_speakers); + Log.Debug("ExampleAlchemyLanguage", "wikipedia: {0}", languages.wikipedia); + } + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Dates!"); + } + } + + private void OnGetMicroformats(MicroformatData microformats, string data) + { + if (microformats != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", microformats.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", microformats.url); + if (microformats.microformats.Length == 0) + Log.Warning("ExampleAlchemyLanguage", "No microformats found!"); + else + { + foreach (Microformat microformat in microformats.microformats) + Log.Debug("ExampleAlchemyLanguage", "field: {0}, data: {1}.", microformat.field, microformat.data); + } + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Microformats!"); + } + } + + private void OnGetPublicationDate(PubDateData pubDates, string data) + { + if (pubDates != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", pubDates.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", pubDates.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", pubDates.language); + if (pubDates.publicationDate != null) + Log.Debug("ExampleAlchemyLanguage", "date: {0}, confident: {1}", pubDates.publicationDate.date, pubDates.publicationDate.confident); + else + Log.Debug("ExampleAlchemyLanguage", "Failed to find Publication Dates!"); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Publication Dates!"); + } + } + + private void OnGetRelations(RelationsData relationsData, string data) + { + if (relationsData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", relationsData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", relationsData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", relationsData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", relationsData.text); + if (relationsData.relations == null || relationsData.relations.Length == 0) + Log.Debug("ExampleAlchemyLanguage", "No relations found!"); + else + foreach (Relation relation in relationsData.relations) + if (relation.subject != null && !string.IsNullOrEmpty(relation.subject.text)) + Log.Debug("ExampleAlchemyLanguage", "Text: {0}, Date: {1}", relation.sentence, relation.subject.text); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); + } + } + + private void OnGetTextSentiment(SentimentData sentimentData, string data) + { + if (sentimentData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", sentimentData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", sentimentData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", sentimentData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", sentimentData.text); + if (sentimentData.docSentiment == null) + Log.Debug("ExampleAlchemyLanguage", "No sentiment found!"); + else + if (sentimentData.docSentiment != null && !string.IsNullOrEmpty(sentimentData.docSentiment.type)) + Log.Debug("ExampleAlchemyLanguage", "Sentiment: {0}, Score: {1}", sentimentData.docSentiment.type, sentimentData.docSentiment.score); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); + } + } + + private void OnGetTargetedSentiment(TargetedSentimentData sentimentData, string data) + { + if (sentimentData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", sentimentData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", sentimentData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", sentimentData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", sentimentData.text); + if (sentimentData.results == null) + Log.Debug("ExampleAlchemyLanguage", "No sentiment found!"); + else + if (sentimentData.results == null || sentimentData.results.Length == 0) + Log.Warning("ExampleAlchemyLanguage", "No sentiment results!"); + else + foreach (TargetedSentiment result in sentimentData.results) + Log.Debug("ExampleAlchemyLanguage", "text: {0}, sentiment: {1}, score: {2}", result.text, result.sentiment.score, result.sentiment.type); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); + } + } + + private void OnGetRankedTaxonomy(TaxonomyData taxonomyData, string data) + { + if (taxonomyData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", taxonomyData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", taxonomyData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", taxonomyData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", taxonomyData.text); + if (taxonomyData.taxonomy == null) + Log.Debug("ExampleAlchemyLanguage", "No taxonomy found!"); + else + if (taxonomyData.taxonomy == null || taxonomyData.taxonomy.Length == 0) + Log.Warning("ExampleAlchemyLanguage", "No taxonomy results!"); + else + foreach (Taxonomy taxonomy in taxonomyData.taxonomy) + Log.Debug("ExampleAlchemyLanguage", "label: {0}, score: {1}", taxonomy.label, taxonomy.score); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find Relations!"); + } + } + + private void OnGetText(TextData textData, string data) + { + if (textData != null) + { + Log.Debug("ExampleAlchemyLanuguage", "status: {0}", textData.status); + Log.Debug("ExampleAlchemyLanuguage", "url: {0}", textData.url); + Log.Debug("ExampleAlchemyLanuguage", "text: {0}", textData.text); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find text!"); + } + + } + + private void OnGetTitle(Title titleData, string data) + { + if (titleData != null) + { + Log.Debug("ExampleAlchemyLanuguage", "status: {0}", titleData.status); + Log.Debug("ExampleAlchemyLanuguage", "url: {0}", titleData.url); + Log.Debug("ExampleAlchemyLanuguage", "text: {0}", titleData.title); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to find title!"); + } + + } + + private void OnGetCombinedData(CombinedCallData combinedData, string data) + { + if (combinedData != null) + { + Log.Debug("ExampleAlchemyLanguage", "status: {0}", combinedData.status); + Log.Debug("ExampleAlchemyLanguage", "url: {0}", combinedData.url); + Log.Debug("ExampleAlchemyLanguage", "language: {0}", combinedData.language); + Log.Debug("ExampleAlchemyLanguage", "text: {0}", combinedData.text); + Log.Debug("ExampleAlchemyLanguage", "image: {0}", combinedData.image); + + if (combinedData.imageKeywords != null && combinedData.imageKeywords.Length > 0) + foreach (ImageKeyword imageKeyword in combinedData.imageKeywords) + Log.Debug("ExampleAlchemyLanguage", "ImageKeyword: {0}, Score: {1}", imageKeyword.text, imageKeyword.score); + + if (combinedData.publicationDate != null) + Log.Debug("ExampleAlchemyLanguage", "publicationDate: {0}, Score: {1}", combinedData.publicationDate.date, combinedData.publicationDate.confident); + + if (combinedData.authors != null && combinedData.authors.names.Length > 0) + foreach (string authors in combinedData.authors.names) + Log.Debug("ExampleAlchemyLanguage", "Authors: {0}", authors); + + if (combinedData.docSentiment != null) + Log.Debug("ExampleAlchemyLanguage", "DocSentiment: {0}, Score: {1}, Mixed: {2}", combinedData.docSentiment.type, combinedData.docSentiment.score, combinedData.docSentiment.mixed); + + if (combinedData.feeds != null && combinedData.feeds.Length > 0) + foreach (Feed feed in combinedData.feeds) + Log.Debug("ExampleAlchemyLanguage", "Feeds: {0}", feed.feed); + + if (combinedData.keywords != null && combinedData.keywords.Length > 0) + foreach (Keyword keyword in combinedData.keywords) + Log.Debug("ExampleAlchemyLanguage", "Keyword: {0}, relevance: {1}", keyword.text, keyword.relevance); + + if (combinedData.concepts != null && combinedData.concepts.Length > 0) + foreach (Concept concept in combinedData.concepts) + Log.Debug("ExampleAlchemyLanguage", "Concept: {0}, Relevance: {1}", concept.text, concept.relevance); + + if (combinedData.entities != null && combinedData.entities.Length > 0) + foreach (Entity entity in combinedData.entities) + Log.Debug("ExampleAlchemyLanguage", "Entity: {0}, Type: {1}, Relevance: {2}", entity.text, entity.type, entity.relevance); + + if (combinedData.relations != null && combinedData.relations.Length > 0) + foreach (Relation relation in combinedData.relations) + Log.Debug("ExampleAlchemyLanguage", "Relations: {0}", relation.subject.text); + + if (combinedData.taxonomy != null && combinedData.taxonomy.Length > 0) + foreach (Taxonomy taxonomy in combinedData.taxonomy) + Log.Debug("ExampleAlchemyLanguage", "Taxonomy: {0}, Score: {1}, Confident: {2}", taxonomy.label, taxonomy.score, taxonomy.confident); + + if (combinedData.dates != null && combinedData.dates.Length > 0) + foreach (Date date in combinedData.dates) + Log.Debug("ExampleAlchemyLanguage", "Dates", date.text, date.date); + + if (combinedData.docEmotions != null && combinedData.docEmotions.Length > 0) + foreach (DocEmotions emotions in combinedData.docEmotions) + Log.Debug("ExampleAlchemyLanguage", "Doc Emotions: anger: {0}, disgust: {1}, fear: {2}, joy: {3}, sadness: {4}", emotions.anger, emotions.disgust, emotions.fear, emotions.joy, emotions.sadness); + } + else + { + Log.Debug("ExampleAlchemyLanguage", "Failed to get combined data!"); } + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleConversation.cs b/Examples/ServiceExamples/Scripts/ExampleConversation.cs index 00c5cf156..307075f0a 100755 --- a/Examples/ServiceExamples/Scripts/ExampleConversation.cs +++ b/Examples/ServiceExamples/Scripts/ExampleConversation.cs @@ -23,59 +23,60 @@ public class ExampleConversation : MonoBehaviour { - private Conversation m_Conversation = new Conversation(); - private string m_WorkspaceID; - private bool m_UseAlternateIntents = true; - private string[] questionArray = { "can you turn up the AC", "can you turn on the wipers", "can you turn off the wipers", "can you turn down the ac", "can you unlock the door"}; + private Conversation m_Conversation = new Conversation(); + private string m_WorkspaceID; + private bool m_UseAlternateIntents = true; + private string[] questionArray = { "can you turn up the AC", "can you turn on the wipers", "can you turn off the wipers", "can you turn down the ac", "can you unlock the door" }; - void Start () { - LogSystem.InstallDefaultReactors(); - m_WorkspaceID = Config.Instance.GetVariableValue("ConversationV1_ID"); + void Start() + { + LogSystem.InstallDefaultReactors(); + m_WorkspaceID = Config.Instance.GetVariableValue("ConversationV1_ID"); - Debug.Log("**********User: Hello!"); - MessageWithOnlyInput("Hello!"); - } + Debug.Log("**********User: Hello!"); + MessageWithOnlyInput("Hello!"); + } + + private void MessageWithOnlyInput(string input) + { + if (string.IsNullOrEmpty(input)) + throw new ArgumentNullException("input"); + + m_Conversation.Message(OnMessageWithOnlyInput, m_WorkspaceID, input); + } - private void MessageWithOnlyInput(string input) - { - if (string.IsNullOrEmpty(input)) - throw new ArgumentNullException("input"); - m_Conversation.Message(OnMessageWithOnlyInput, m_WorkspaceID, input); - } - - - private void OnMessageWithOnlyInput(MessageResponse resp, string customData) - { - if (resp != null) - { - foreach (Intent mi in resp.intents) - Debug.Log("intent: " + mi.intent + ", confidence: " + mi.confidence); + private void OnMessageWithOnlyInput(MessageResponse resp, string customData) + { + if (resp != null) + { + foreach (Intent mi in resp.intents) + Debug.Log("intent: " + mi.intent + ", confidence: " + mi.confidence); - if (resp.output != null && resp.output.text.Length > 0) - foreach (string txt in resp.output.text) - Debug.Log("output: " + txt); + if (resp.output != null && resp.output.text.Length > 0) + foreach (string txt in resp.output.text) + Debug.Log("output: " + txt); - string questionStr = questionArray[UnityEngine.Random.Range(0, questionArray.Length - 1)]; - Debug.Log(string.Format("**********User: {0}", questionStr)); + string questionStr = questionArray[UnityEngine.Random.Range(0, questionArray.Length - 1)]; + Debug.Log(string.Format("**********User: {0}", questionStr)); - MessageRequest messageRequest = new MessageRequest(); - messageRequest.InputText = questionStr; - messageRequest.alternate_intents = m_UseAlternateIntents; - messageRequest.ContextData = resp.context; + MessageRequest messageRequest = new MessageRequest(); + messageRequest.InputText = questionStr; + messageRequest.alternate_intents = m_UseAlternateIntents; + messageRequest.ContextData = resp.context; - MessageWithFullMessageRequest(messageRequest); - } - else - { - Debug.Log("Failed to invoke Message();"); - } - } + MessageWithFullMessageRequest(messageRequest); + } + else + { + Debug.Log("Failed to invoke Message();"); + } + } - private void MessageWithFullMessageRequest(MessageRequest messageRequest) - { - if (messageRequest == null) - throw new ArgumentNullException("messageRequest"); - m_Conversation.Message(OnMessageWithOnlyInput, m_WorkspaceID, messageRequest); - } + private void MessageWithFullMessageRequest(MessageRequest messageRequest) + { + if (messageRequest == null) + throw new ArgumentNullException("messageRequest"); + m_Conversation.Message(OnMessageWithOnlyInput, m_WorkspaceID, messageRequest); + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleConversationExperimental.cs b/Examples/ServiceExamples/Scripts/ExampleConversationExperimental.cs index 5bb64d1e2..a5fc5bcc1 100755 --- a/Examples/ServiceExamples/Scripts/ExampleConversationExperimental.cs +++ b/Examples/ServiceExamples/Scripts/ExampleConversationExperimental.cs @@ -23,31 +23,32 @@ public class ExampleConversationExperimental : MonoBehaviour { - private ConversationExperimental m_Conversation = new ConversationExperimental(); - private string m_WorkspaceID; - private string m_Input = "Can you unlock the door?"; + private ConversationExperimental m_Conversation = new ConversationExperimental(); + private string m_WorkspaceID; + private string m_Input = "Can you unlock the door?"; - void Start () { - LogSystem.InstallDefaultReactors(); - m_WorkspaceID = Config.Instance.GetVariableValue("ConversationExperimentalV1_ID"); - Debug.Log("User: " + m_Input); + void Start() + { + LogSystem.InstallDefaultReactors(); + m_WorkspaceID = Config.Instance.GetVariableValue("ConversationExperimentalV1_ID"); + Debug.Log("User: " + m_Input); - m_Conversation.Message(m_WorkspaceID, m_Input, OnMessage); - } + m_Conversation.Message(m_WorkspaceID, m_Input, OnMessage); + } - void OnMessage (MessageResponse resp) - { - if(resp != null) - { - foreach(MessageIntent mi in resp.intents) - Debug.Log("intent: " + mi.intent + ", confidence: " + mi.confidence); - - if(resp.output != null && !string.IsNullOrEmpty(resp.output.text)) - Debug.Log("response: " + resp.output.text); - } - else - { - Debug.Log("Failed to invoke Message();"); - } - } + void OnMessage(MessageResponse resp) + { + if (resp != null) + { + foreach (MessageIntent mi in resp.intents) + Debug.Log("intent: " + mi.intent + ", confidence: " + mi.confidence); + + if (resp.output != null && !string.IsNullOrEmpty(resp.output.text)) + Debug.Log("response: " + resp.output.text); + } + else + { + Debug.Log("Failed to invoke Message();"); + } + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleDocumentConversion.cs b/Examples/ServiceExamples/Scripts/ExampleDocumentConversion.cs index edbd21852..a385cdc44 100755 --- a/Examples/ServiceExamples/Scripts/ExampleDocumentConversion.cs +++ b/Examples/ServiceExamples/Scripts/ExampleDocumentConversion.cs @@ -22,49 +22,49 @@ public class ExampleDocumentConversion : MonoBehaviour { - private DocumentConversion m_DocumentConversion = new DocumentConversion(); - - void Start () - { - LogSystem.InstallDefaultReactors(); LogSystem.InstallDefaultReactors(); - string examplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; + private DocumentConversion m_DocumentConversion = new DocumentConversion(); - if (!m_DocumentConversion.ConvertDocument(OnConvertDocument, examplePath, ConversionTarget.NORMALIZED_TEXT)) - Log.Debug("ExampleDocumentConversion", "Document conversion failed!"); - } + void Start() + { + LogSystem.InstallDefaultReactors(); LogSystem.InstallDefaultReactors(); + string examplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; + + if (!m_DocumentConversion.ConvertDocument(OnConvertDocument, examplePath, ConversionTarget.NORMALIZED_TEXT)) + Log.Debug("ExampleDocumentConversion", "Document conversion failed!"); + } - private void OnConvertDocument(ConvertedDocument documentConversionResponse, string data) + private void OnConvertDocument(ConvertedDocument documentConversionResponse, string data) + { + if (documentConversionResponse != null) { - if (documentConversionResponse != null) + if (!string.IsNullOrEmpty(documentConversionResponse.media_type_detected)) + Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.media_type_detected); + if (!string.IsNullOrEmpty(documentConversionResponse.source_document_id)) + Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.source_document_id); + if (!string.IsNullOrEmpty(documentConversionResponse.timestamp)) + Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.timestamp); + if (documentConversionResponse.metadata != null && documentConversionResponse.metadata.Length > 0) + { + Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.metadata.Length); + foreach (Metadata metadata in documentConversionResponse.metadata) + Log.Debug("ExampleDocumentConversion", "metadata | name: {0}, content: {1}", metadata.name, metadata.content); + } + if (documentConversionResponse.answer_units != null && documentConversionResponse.answer_units.Length > 0) + { + Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.answer_units.Length); + foreach (AnswerUnit answerUnit in documentConversionResponse.answer_units) { - if(!string.IsNullOrEmpty(documentConversionResponse.media_type_detected)) - Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.media_type_detected); - if (!string.IsNullOrEmpty(documentConversionResponse.source_document_id)) - Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.source_document_id); - if(!string.IsNullOrEmpty(documentConversionResponse.timestamp)) - Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.timestamp); - if (documentConversionResponse.metadata != null && documentConversionResponse.metadata.Length > 0) - { - Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.metadata.Length); - foreach (Metadata metadata in documentConversionResponse.metadata) - Log.Debug("ExampleDocumentConversion", "metadata | name: {0}, content: {1}", metadata.name, metadata.content); - } - if (documentConversionResponse.answer_units != null && documentConversionResponse.answer_units.Length > 0) - { - Log.Debug("ExampleDocumentConversion", "mediaTypeDetected: {0}", documentConversionResponse.answer_units.Length); - foreach (AnswerUnit answerUnit in documentConversionResponse.answer_units) - { - Log.Debug("ExampleDocumentConversion", "answerUnit | type: {0}, title: {1}, parent_id: {2}, id: {3}, direction: {4}", answerUnit.type, answerUnit.title, answerUnit.parent_id, answerUnit.id, answerUnit.direction); - if (answerUnit.content != null && answerUnit.content.Length > 0) - foreach (Content content in answerUnit.content) - Log.Debug("ExampleDocumentConversion", "content | mediaType: {0}, text: {1}", content.media_type, content.text); - } - } - - if (!string.IsNullOrEmpty(documentConversionResponse.htmlContent)) - Log.Debug("ExampleDocumentConversion", "HTMLContent: {0}", documentConversionResponse.htmlContent); - if (!string.IsNullOrEmpty(documentConversionResponse.textContent)) - Log.Debug("ExampleDocumentConversion", "TextContent: {0}", documentConversionResponse.textContent); + Log.Debug("ExampleDocumentConversion", "answerUnit | type: {0}, title: {1}, parent_id: {2}, id: {3}, direction: {4}", answerUnit.type, answerUnit.title, answerUnit.parent_id, answerUnit.id, answerUnit.direction); + if (answerUnit.content != null && answerUnit.content.Length > 0) + foreach (Content content in answerUnit.content) + Log.Debug("ExampleDocumentConversion", "content | mediaType: {0}, text: {1}", content.media_type, content.text); } + } + + if (!string.IsNullOrEmpty(documentConversionResponse.htmlContent)) + Log.Debug("ExampleDocumentConversion", "HTMLContent: {0}", documentConversionResponse.htmlContent); + if (!string.IsNullOrEmpty(documentConversionResponse.textContent)) + Log.Debug("ExampleDocumentConversion", "TextContent: {0}", documentConversionResponse.textContent); } + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleLanguageTranslation.cs b/Examples/ServiceExamples/Scripts/ExampleLanguageTranslation.cs old mode 100644 new mode 100755 index 408afb152..7b3d3754b --- a/Examples/ServiceExamples/Scripts/ExampleLanguageTranslation.cs +++ b/Examples/ServiceExamples/Scripts/ExampleLanguageTranslation.cs @@ -18,19 +18,20 @@ using UnityEngine; using IBM.Watson.DeveloperCloud.Services.LanguageTranslation.v1; -public class ExampleLanguageTranslation : MonoBehaviour { - private LanguageTranslation m_Translate = new LanguageTranslation(); - private string m_PharseToTranslate = "How do I get to the disco?"; +public class ExampleLanguageTranslation : MonoBehaviour +{ + private LanguageTranslation m_Translate = new LanguageTranslation(); + private string m_PharseToTranslate = "How do I get to the disco?"; - void Start () - { - Debug.Log("English Phrase to translate: " + m_PharseToTranslate); - m_Translate.GetTranslation(m_PharseToTranslate, "en", "es", OnGetTranslation); - } + void Start() + { + Debug.Log("English Phrase to translate: " + m_PharseToTranslate); + m_Translate.GetTranslation(m_PharseToTranslate, "en", "es", OnGetTranslation); + } - private void OnGetTranslation(Translations translation) - { - if (translation != null && translation.translations.Length > 0) - Debug.Log("Spanish Translation: " + translation.translations[0].translation); - } + private void OnGetTranslation(Translations translation) + { + if (translation != null && translation.translations.Length > 0) + Debug.Log("Spanish Translation: " + translation.translations[0].translation); + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleLanguageTranslator.cs b/Examples/ServiceExamples/Scripts/ExampleLanguageTranslator.cs old mode 100644 new mode 100755 index 562a4a423..47d420eed --- a/Examples/ServiceExamples/Scripts/ExampleLanguageTranslator.cs +++ b/Examples/ServiceExamples/Scripts/ExampleLanguageTranslator.cs @@ -18,19 +18,20 @@ using UnityEngine; using IBM.Watson.DeveloperCloud.Services.LanguageTranslator.v1; -public class ExampleLanguageTranslator : MonoBehaviour { - private LanguageTranslator m_Translate = new LanguageTranslator(); - private string m_PharseToTranslate = "How do I get to the disco?"; - - void Start () - { - Debug.Log("English Phrase to translate: " + m_PharseToTranslate); - m_Translate.GetTranslation(m_PharseToTranslate, "en", "es", OnGetTranslation); - } +public class ExampleLanguageTranslator : MonoBehaviour +{ + private LanguageTranslator m_Translate = new LanguageTranslator(); + private string m_PharseToTranslate = "How do I get to the disco?"; - private void OnGetTranslation(Translations translation) - { - if (translation != null && translation.translations.Length > 0) - Debug.Log("Spanish Translation: " + translation.translations[0].translation); - } + void Start() + { + Debug.Log("English Phrase to translate: " + m_PharseToTranslate); + m_Translate.GetTranslation(m_PharseToTranslate, "en", "es", OnGetTranslation); + } + + private void OnGetTranslation(Translations translation) + { + if (translation != null && translation.translations.Length > 0) + Debug.Log("Spanish Translation: " + translation.translations[0].translation); + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleNaturalLanguageClassifier.cs b/Examples/ServiceExamples/Scripts/ExampleNaturalLanguageClassifier.cs old mode 100644 new mode 100755 index 0ff4dabcf..73d8f12cf --- a/Examples/ServiceExamples/Scripts/ExampleNaturalLanguageClassifier.cs +++ b/Examples/ServiceExamples/Scripts/ExampleNaturalLanguageClassifier.cs @@ -20,21 +20,21 @@ public class ExampleNaturalLanguageClassifier : MonoBehaviour { - private NaturalLanguageClassifier m_NaturalLanguageClassifier = new NaturalLanguageClassifier(); - private string m_ClassifierId = "3a84d1x62-nlc-768"; - private string m_InputString = "Is it hot outside?"; + private NaturalLanguageClassifier m_NaturalLanguageClassifier = new NaturalLanguageClassifier(); + private string m_ClassifierId = "3a84d1x62-nlc-768"; + private string m_InputString = "Is it hot outside?"; - void Start () - { - Debug.Log("Input String: " + m_InputString); - m_NaturalLanguageClassifier.Classify(m_ClassifierId, m_InputString, OnClassify); - } + void Start() + { + Debug.Log("Input String: " + m_InputString); + m_NaturalLanguageClassifier.Classify(m_ClassifierId, m_InputString, OnClassify); + } - private void OnClassify(ClassifyResult result) - { - if (result != null) - { - Debug.Log("Classify Result: " + result.top_class); - } - } + private void OnClassify(ClassifyResult result) + { + if (result != null) + { + Debug.Log("Classify Result: " + result.top_class); + } + } } diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs old mode 100644 new mode 100755 index dbcca7b34..89ca1fc10 --- a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs +++ b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV2.cs @@ -21,62 +21,62 @@ public class ExamplePersonalityInsightsV2 : MonoBehaviour { - PersonalityInsights m_personalityInsights = new PersonalityInsights(); + PersonalityInsights m_personalityInsights = new PersonalityInsights(); - void Start () - { - LogSystem.InstallDefaultReactors(); - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + void Start() + { + LogSystem.InstallDefaultReactors(); + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - if(!m_personalityInsights.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, Language.ENGLISH)) - Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - } + if (!m_personalityInsights.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, Language.ENGLISH)) + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); + } - private void OnGetProfile(Profile profile, string data) + private void OnGetProfile(Profile profile, string data) + { + Log.Debug("ExamplePersonalityInsights", "data: {0}", data); + if (profile != null) { - Log.Debug("ExamplePersonalityInsights", "data: {0}", data); - if(profile != null) - { - if(!string.IsNullOrEmpty(profile.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", profile.id); - if(!string.IsNullOrEmpty(profile.source)) - Log.Debug("ExamplePersonalityInsights", "source: {0}", profile.source); - if(!string.IsNullOrEmpty(profile.processed_lang)) - Log.Debug("ExamplePersonalityInsights", "proccessed_lang: {0}", profile.processed_lang); - if(!string.IsNullOrEmpty(profile.word_count)) - Log.Debug("ExamplePersonalityInsights", "word_count: {0}", profile.word_count); - if(!string.IsNullOrEmpty(profile.word_count_message)) - Log.Debug("ExamplePersonalityInsights", "word_count_message: {0}", profile.word_count_message); + if (!string.IsNullOrEmpty(profile.id)) + Log.Debug("ExamplePersonalityInsights", "id: {0}", profile.id); + if (!string.IsNullOrEmpty(profile.source)) + Log.Debug("ExamplePersonalityInsights", "source: {0}", profile.source); + if (!string.IsNullOrEmpty(profile.processed_lang)) + Log.Debug("ExamplePersonalityInsights", "proccessed_lang: {0}", profile.processed_lang); + if (!string.IsNullOrEmpty(profile.word_count)) + Log.Debug("ExamplePersonalityInsights", "word_count: {0}", profile.word_count); + if (!string.IsNullOrEmpty(profile.word_count_message)) + Log.Debug("ExamplePersonalityInsights", "word_count_message: {0}", profile.word_count_message); - if(profile.tree != null) - { - LogTraitTree(profile.tree); - } - } - else - { - Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); - } + if (profile.tree != null) + { + LogTraitTree(profile.tree); + } } - - private void LogTraitTree(TraitTreeNode traitTreeNode) + else { - if(!string.IsNullOrEmpty(traitTreeNode.id)) - Log.Debug("ExamplePersonalityInsights", "id: {0}", traitTreeNode.id); - if(!string.IsNullOrEmpty(traitTreeNode.name)) - Log.Debug("ExamplePersonalityInsights", "name: {0}", traitTreeNode.name); - if(!string.IsNullOrEmpty(traitTreeNode.category)) - Log.Debug("ExamplePersonalityInsights", "category: {0}", traitTreeNode.category); - if(!string.IsNullOrEmpty(traitTreeNode.percentage)) - Log.Debug("ExamplePersonalityInsights", "percentage: {0}", traitTreeNode.percentage); - if(!string.IsNullOrEmpty(traitTreeNode.sampling_error)) - Log.Debug("ExamplePersonalityInsights", "sampling_error: {0}", traitTreeNode.sampling_error); - if(!string.IsNullOrEmpty(traitTreeNode.raw_score)) - Log.Debug("ExamplePersonalityInsights", "raw_score: {0}", traitTreeNode.raw_score); - if(!string.IsNullOrEmpty(traitTreeNode.raw_sampling_error)) - Log.Debug("ExamplePersonalityInsights", "raw_sampling_error: {0}", traitTreeNode.raw_sampling_error); - if(traitTreeNode.children != null && traitTreeNode.children.Length > 0) - foreach(TraitTreeNode childNode in traitTreeNode.children) - LogTraitTree(childNode); + Log.Debug("ExamplePersonalityInsights", "Failed to get profile!"); } + } + + private void LogTraitTree(TraitTreeNode traitTreeNode) + { + if (!string.IsNullOrEmpty(traitTreeNode.id)) + Log.Debug("ExamplePersonalityInsights", "id: {0}", traitTreeNode.id); + if (!string.IsNullOrEmpty(traitTreeNode.name)) + Log.Debug("ExamplePersonalityInsights", "name: {0}", traitTreeNode.name); + if (!string.IsNullOrEmpty(traitTreeNode.category)) + Log.Debug("ExamplePersonalityInsights", "category: {0}", traitTreeNode.category); + if (!string.IsNullOrEmpty(traitTreeNode.percentage)) + Log.Debug("ExamplePersonalityInsights", "percentage: {0}", traitTreeNode.percentage); + if (!string.IsNullOrEmpty(traitTreeNode.sampling_error)) + Log.Debug("ExamplePersonalityInsights", "sampling_error: {0}", traitTreeNode.sampling_error); + if (!string.IsNullOrEmpty(traitTreeNode.raw_score)) + Log.Debug("ExamplePersonalityInsights", "raw_score: {0}", traitTreeNode.raw_score); + if (!string.IsNullOrEmpty(traitTreeNode.raw_sampling_error)) + Log.Debug("ExamplePersonalityInsights", "raw_sampling_error: {0}", traitTreeNode.raw_sampling_error); + if (traitTreeNode.children != null && traitTreeNode.children.Length > 0) + foreach (TraitTreeNode childNode in traitTreeNode.children) + LogTraitTree(childNode); + } } diff --git a/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs b/Examples/ServiceExamples/Scripts/ExamplePersonalityInsightsV3.cs old mode 100644 new mode 100755 diff --git a/Examples/ServiceExamples/Scripts/ExampleRetrieveAndRank.cs b/Examples/ServiceExamples/Scripts/ExampleRetrieveAndRank.cs index 4f3111225..5d2a6ef2b 100755 --- a/Examples/ServiceExamples/Scripts/ExampleRetrieveAndRank.cs +++ b/Examples/ServiceExamples/Scripts/ExampleRetrieveAndRank.cs @@ -28,446 +28,446 @@ #pragma warning disable 219 public class ExampleRetrieveAndRank : MonoBehaviour { - private RetrieveAndRank m_RetrieveAndRank = new RetrieveAndRank(); - - void Start() + private RetrieveAndRank m_RetrieveAndRank = new RetrieveAndRank(); + + void Start() + { + LogSystem.InstallDefaultReactors(); + + string testClusterID = Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestClusterID"); + string testClusterConfigName = "cranfield_solr_config"; + string testClusterConfigPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_solr_config.zip"; + string testRankerTrainingPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_training_data.csv"; + string testAnswerDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_answer_data.csv"; + string testRankerID = "3b140ax15-rank-10035"; + string rankerToDelete = "3b140ax14-rank-10015"; + string indexDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_data.json"; + string testCollectionName = "test-collection"; + string testQuery = "What is the basic mechanisim of the transonic aileron buzz"; + + //// Get clusters + //Log.Debug("ExampleRetrieveAndRank", "Attempting to get clusters!"); + //if (!m_RetrieveAndRank.GetClusters(OnGetClusters)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get clusters!"); + + //// Create cluster + //Log.Debug("ExampleRetrieveAndRank", "Attempting to create cluster!"); + //if (!m_RetrieveAndRank.CreateCluster(OnCreateCluster, "unity-test-cluster", "1")) + // Log.Debug("ExampleRetrieveAndRank", "Failed to create cluster!"); + + //// Delete cluster + //string clusterToDelete = "scabeadb4c_cd5a_4745_b1b9_156c6292687c"; + //Log.Debug("ExampleRetrieveAndRank", "Attempting to delete cluster {0}!", clusterToDelete); + //if (!m_RetrieveAndRank.DeleteCluster(OnDeleteCluster, clusterToDelete)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to delete cluster!"); + + //// Get cluster + //Log.Debug("ExampleRetrieveAndRank", "Attempting to get cluster {0}!", testClusterID); + //if (!m_RetrieveAndRank.GetCluster(OnGetCluster, testClusterID)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get cluster!"); + + //// List cluster configs + //Log.Debug("ExampleRetrieveAndRank", "Attempting to get cluster configs for {0}!", testClusterID); + //if (!m_RetrieveAndRank.GetClusterConfigs(OnGetClusterConfigs, testClusterID)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get cluster configs!"); + + //// Delete cluster config + //string clusterConfigToDelete = "test-config"; + //Log.Debug("ExampleRetrieveAndRank", "Attempting to delete cluster {0} config {1}!", testClusterID, clusterConfigToDelete); + //if (!m_RetrieveAndRank.DeleteClusterConfig(OnDeleteClusterConfig, testClusterID, clusterConfigToDelete)) + // Log.Debug("ExampleRetriveAndRank", "Failed to delete cluster config {0}", clusterConfigToDelete); + + //// Get cluster config + //Log.Debug("ExampleRetrieveAndRank", "Attempting to get cluster {0} config {1}!", testClusterID, testClusterConfigName); + //if (!m_RetrieveAndRank.GetClusterConfig(OnGetClusterConfig, testClusterID, testClusterConfigName)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get cluster config {0}!", testClusterConfigName); + + //// Upload cluster config + //Log.Debug("ExampleRetrieveAndRank", "Attempting to upload cluster {0} config {1}!", testClusterID, testClusterConfigName); + //if (!m_RetrieveAndRank.UploadClusterConfig(OnUploadClusterConfig, testClusterID, testClusterConfigName, testClusterConfigPath)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to upload cluster config {0}!", testClusterConfigPath); + + //// List Collection request + //Log.Debug("ExampleRetrieveAndRank", "Attempting to list collections!"); + //if (!m_RetrieveAndRank.ForwardCollectionRequest(OnGetCollections, testClusterID, CollectionsAction.LIST)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get collections!"); + + //// Create Collection request + //Log.Debug("ExampleRetrieveAndRank", "Attempting to create collection!"); + //if (!m_RetrieveAndRank.ForwardCollectionRequest(OnGetCollections, testClusterID, CollectionsAction.CREATE, "TestCollectionToDelete", testClusterConfigName)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to create collections!"); + + //// Delete Collection request + //Log.Debug("ExampleRetrieveAndRank", "Attempting to delete collection!"); + //if (!m_RetrieveAndRank.ForwardCollectionRequest(OnGetCollections, testClusterID, CollectionsAction.DELETE, "TestCollectionToDelete")) + // Log.Debug("ExampleRetrieveAndRank", "Failed to delete collections!"); + + //// Index documents + //Log.Debug("ExampleRetrieveAndRank", "Attempting to index documents!"); + //if (!m_RetrieveAndRank.IndexDocuments(OnIndexDocuments, indexDataPath, testClusterID, testCollectionName)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to index documents!"); + + //// Standard Search + //Log.Debug("ExampleRetrieveAndRank", "Attempting to search!"); + //string[] fl = { "title", "id", "body", "author", "bibliography" }; + //if (!m_RetrieveAndRank.Search(OnSearch, testClusterID, testCollectionName, testQuery, fl)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to search!"); + + //// Ranked Search + //Log.Debug("ExampleRetrieveAndRank", "Attempting to search!"); + //string[] fl = { "title", "id", "body", "author", "bibliography" }; + //if (!m_RetrieveAndRank.Search(OnSearch, testClusterID, testCollectionName, testQuery, fl, true)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to search!"); + + //// Get rankers + //Log.Debug("ExampleRetrieveAndRank", "Attempting to get rankers!"); + //if (!m_RetrieveAndRank.GetRankers(OnGetRankers)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get rankers!"); + + //// Create ranker + //Log.Debug("ExampleRetrieveAndRank", "Attempting to create rankers!"); + //if (!m_RetrieveAndRank.CreateRanker(OnCreateRanker, testRankerTrainingPath, "testRanker")) + // Log.Debug("ExampleRetrieveAndRank", "Failed to create ranker!"); + + // Rank + Log.Debug("ExampleRetrieveAndRank", "Attempting to rank!"); + if (!m_RetrieveAndRank.Rank(OnRank, testRankerID, testAnswerDataPath)) + Log.Debug("ExampleRetriveAndRank", "Failed to rank!"); + + //// Delete rankers + //Log.Debug("ExampleRetriveAndRank", "Attempting to delete ranker {0}!", rankerToDelete); + //if (!m_RetrieveAndRank.DeleteRanker(OnDeleteRanker, rankerToDelete)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to delete ranker {0}!", rankerToDelete); + + //// Get ranker info + //Log.Debug("ExampleRetrieveAndRank", "Attempting to get Ranker Info!"); + //if (!m_RetrieveAndRank.GetRanker(OnGetRanker, testRankerID)) + // Log.Debug("ExampleRetrieveAndRank", "Failed to get ranker!"); + } + + private void OnGetClusters(SolrClusterListResponse resp, string data) + { + if (resp != null) { - LogSystem.InstallDefaultReactors(); - - string testClusterID = Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestClusterID"); - string testClusterConfigName = "cranfield_solr_config"; - string testClusterConfigPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_solr_config.zip"; - string testRankerTrainingPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_training_data.csv"; - string testAnswerDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/ranker_answer_data.csv"; - string testRankerID = "3b140ax15-rank-10035"; - string rankerToDelete = "3b140ax14-rank-10015"; - string indexDataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/RetrieveAndRank/cranfield_data.json"; - string testCollectionName = "test-collection"; - string testQuery = "What is the basic mechanisim of the transonic aileron buzz"; - - //// Get clusters - //Log.Debug("ExampleRetrieveAndRank", "Attempting to get clusters!"); - //if (!m_RetrieveAndRank.GetClusters(OnGetClusters)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get clusters!"); - - //// Create cluster - //Log.Debug("ExampleRetrieveAndRank", "Attempting to create cluster!"); - //if (!m_RetrieveAndRank.CreateCluster(OnCreateCluster, "unity-test-cluster", "1")) - // Log.Debug("ExampleRetrieveAndRank", "Failed to create cluster!"); - - //// Delete cluster - //string clusterToDelete = "scabeadb4c_cd5a_4745_b1b9_156c6292687c"; - //Log.Debug("ExampleRetrieveAndRank", "Attempting to delete cluster {0}!", clusterToDelete); - //if (!m_RetrieveAndRank.DeleteCluster(OnDeleteCluster, clusterToDelete)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to delete cluster!"); - - //// Get cluster - //Log.Debug("ExampleRetrieveAndRank", "Attempting to get cluster {0}!", testClusterID); - //if (!m_RetrieveAndRank.GetCluster(OnGetCluster, testClusterID)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get cluster!"); - - //// List cluster configs - //Log.Debug("ExampleRetrieveAndRank", "Attempting to get cluster configs for {0}!", testClusterID); - //if (!m_RetrieveAndRank.GetClusterConfigs(OnGetClusterConfigs, testClusterID)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get cluster configs!"); - - //// Delete cluster config - //string clusterConfigToDelete = "test-config"; - //Log.Debug("ExampleRetrieveAndRank", "Attempting to delete cluster {0} config {1}!", testClusterID, clusterConfigToDelete); - //if (!m_RetrieveAndRank.DeleteClusterConfig(OnDeleteClusterConfig, testClusterID, clusterConfigToDelete)) - // Log.Debug("ExampleRetriveAndRank", "Failed to delete cluster config {0}", clusterConfigToDelete); - - //// Get cluster config - //Log.Debug("ExampleRetrieveAndRank", "Attempting to get cluster {0} config {1}!", testClusterID, testClusterConfigName); - //if (!m_RetrieveAndRank.GetClusterConfig(OnGetClusterConfig, testClusterID, testClusterConfigName)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get cluster config {0}!", testClusterConfigName); - - //// Upload cluster config - //Log.Debug("ExampleRetrieveAndRank", "Attempting to upload cluster {0} config {1}!", testClusterID, testClusterConfigName); - //if (!m_RetrieveAndRank.UploadClusterConfig(OnUploadClusterConfig, testClusterID, testClusterConfigName, testClusterConfigPath)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to upload cluster config {0}!", testClusterConfigPath); - - //// List Collection request - //Log.Debug("ExampleRetrieveAndRank", "Attempting to list collections!"); - //if (!m_RetrieveAndRank.ForwardCollectionRequest(OnGetCollections, testClusterID, CollectionsAction.LIST)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get collections!"); - - //// Create Collection request - //Log.Debug("ExampleRetrieveAndRank", "Attempting to create collection!"); - //if (!m_RetrieveAndRank.ForwardCollectionRequest(OnGetCollections, testClusterID, CollectionsAction.CREATE, "TestCollectionToDelete", testClusterConfigName)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to create collections!"); - - //// Delete Collection request - //Log.Debug("ExampleRetrieveAndRank", "Attempting to delete collection!"); - //if (!m_RetrieveAndRank.ForwardCollectionRequest(OnGetCollections, testClusterID, CollectionsAction.DELETE, "TestCollectionToDelete")) - // Log.Debug("ExampleRetrieveAndRank", "Failed to delete collections!"); - - //// Index documents - //Log.Debug("ExampleRetrieveAndRank", "Attempting to index documents!"); - //if (!m_RetrieveAndRank.IndexDocuments(OnIndexDocuments, indexDataPath, testClusterID, testCollectionName)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to index documents!"); - - //// Standard Search - //Log.Debug("ExampleRetrieveAndRank", "Attempting to search!"); - //string[] fl = { "title", "id", "body", "author", "bibliography" }; - //if (!m_RetrieveAndRank.Search(OnSearch, testClusterID, testCollectionName, testQuery, fl)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to search!"); - - //// Ranked Search - //Log.Debug("ExampleRetrieveAndRank", "Attempting to search!"); - //string[] fl = { "title", "id", "body", "author", "bibliography" }; - //if (!m_RetrieveAndRank.Search(OnSearch, testClusterID, testCollectionName, testQuery, fl, true)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to search!"); - - //// Get rankers - //Log.Debug("ExampleRetrieveAndRank", "Attempting to get rankers!"); - //if (!m_RetrieveAndRank.GetRankers(OnGetRankers)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get rankers!"); - - //// Create ranker - //Log.Debug("ExampleRetrieveAndRank", "Attempting to create rankers!"); - //if (!m_RetrieveAndRank.CreateRanker(OnCreateRanker, testRankerTrainingPath, "testRanker")) - // Log.Debug("ExampleRetrieveAndRank", "Failed to create ranker!"); - - // Rank - Log.Debug("ExampleRetrieveAndRank", "Attempting to rank!"); - if (!m_RetrieveAndRank.Rank(OnRank, testRankerID, testAnswerDataPath)) - Log.Debug("ExampleRetriveAndRank", "Failed to rank!"); - - //// Delete rankers - //Log.Debug("ExampleRetriveAndRank", "Attempting to delete ranker {0}!", rankerToDelete); - //if (!m_RetrieveAndRank.DeleteRanker(OnDeleteRanker, rankerToDelete)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to delete ranker {0}!", rankerToDelete); - - //// Get ranker info - //Log.Debug("ExampleRetrieveAndRank", "Attempting to get Ranker Info!"); - //if (!m_RetrieveAndRank.GetRanker(OnGetRanker, testRankerID)) - // Log.Debug("ExampleRetrieveAndRank", "Failed to get ranker!"); + foreach (SolrClusterResponse cluster in resp.clusters) + Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | cluster name: {0}, size: {1}, ID: {2}, status: {3}.", cluster.cluster_name, cluster.cluster_size, cluster.solr_cluster_id, cluster.solr_cluster_status); } - - private void OnGetClusters(SolrClusterListResponse resp, string data) + else { - if (resp != null) - { - foreach (SolrClusterResponse cluster in resp.clusters) - Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | cluster name: {0}, size: {1}, ID: {2}, status: {3}.", cluster.cluster_name, cluster.cluster_size, cluster.solr_cluster_id, cluster.solr_cluster_status); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | Get Cluster Response is null!"); - } + Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | Get Cluster Response is null!"); } + } - private void OnCreateCluster(SolrClusterResponse resp, string data) + private void OnCreateCluster(SolrClusterResponse resp, string data) + { + if (resp != null) { - if (resp != null) - { - Log.Debug("ExampleRetrieveAndRank", "OnCreateClusters | name: {0}, size: {1}, ID: {2}, status: {3}.", resp.cluster_name, resp.cluster_size, resp.solr_cluster_id, resp.solr_cluster_status); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnCreateClusters | Get Cluster Response is null!"); - } + Log.Debug("ExampleRetrieveAndRank", "OnCreateClusters | name: {0}, size: {1}, ID: {2}, status: {3}.", resp.cluster_name, resp.cluster_size, resp.solr_cluster_id, resp.solr_cluster_status); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnCreateClusters | Get Cluster Response is null!"); } + } - private void OnDeleteCluster(bool success, string data) + private void OnDeleteCluster(bool success, string data) + { + if (success) { - if (success) - { - Log.Debug("ExampleRetrieveAndRank", "OnDeleteCluster | Success!"); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnDeleteCluster | Failure!"); - } + Log.Debug("ExampleRetrieveAndRank", "OnDeleteCluster | Success!"); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnDeleteCluster | Failure!"); } + } - private void OnGetCluster(SolrClusterResponse resp, string data) + private void OnGetCluster(SolrClusterResponse resp, string data) + { + if (resp != null) { - if (resp != null) - { - Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | name: {0}, size: {1}, ID: {2}, status: {3}.", resp.cluster_name, resp.cluster_size, resp.solr_cluster_id, resp.solr_cluster_status); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | Get Cluster Response is null!"); - } + Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | name: {0}, size: {1}, ID: {2}, status: {3}.", resp.cluster_name, resp.cluster_size, resp.solr_cluster_id, resp.solr_cluster_status); } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnGetClusters | Get Cluster Response is null!"); + } + } - private void OnGetClusterConfigs(SolrConfigList resp, string data) + private void OnGetClusterConfigs(SolrConfigList resp, string data) + { + if (resp != null) { - if (resp != null) - { - if (resp.solr_configs.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfigs | no cluster configs!"); + if (resp.solr_configs.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfigs | no cluster configs!"); - foreach (string config in resp.solr_configs) - Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfigs | solr_config: " + config); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnGetClustersConfigs | Get Cluster Configs Response is null!"); - } + foreach (string config in resp.solr_configs) + Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfigs | solr_config: " + config); } - - private void OnDeleteClusterConfig(bool success, string data) + else { - if (success) - { - Log.Debug("ExampleRetrieveAndRank", "OnDeleteClusterConfig | Success!"); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnDeleteClusterConfig | Failure!"); - } + Log.Debug("ExampleRetrieveAndRank", "OnGetClustersConfigs | Get Cluster Configs Response is null!"); } + } - - private void OnGetClusterConfig(byte[] respData, string data) + private void OnDeleteClusterConfig(bool success, string data) + { + if (success) + { + Log.Debug("ExampleRetrieveAndRank", "OnDeleteClusterConfig | Success!"); + } + else { + Log.Debug("ExampleRetrieveAndRank", "OnDeleteClusterConfig | Failure!"); + } + } + + + private void OnGetClusterConfig(byte[] respData, string data) + { #if UNITY_EDITOR - if (respData != null) - { - Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfig | success!"); - string currentDirectory = Application.dataPath; - var path = EditorUtility.SaveFilePanel("Save Config", currentDirectory, "config", "zip"); - if (!string.IsNullOrEmpty(path)) - { - currentDirectory = Path.GetDirectoryName(path); - m_RetrieveAndRank.SaveConfig(OnSaveConfig, respData, path, data); - } - } - else - Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfig | respData is null!"); + if (respData != null) + { + Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfig | success!"); + string currentDirectory = Application.dataPath; + var path = EditorUtility.SaveFilePanel("Save Config", currentDirectory, "config", "zip"); + if (!string.IsNullOrEmpty(path)) + { + currentDirectory = Path.GetDirectoryName(path); + m_RetrieveAndRank.SaveConfig(OnSaveConfig, respData, path, data); + } + } + else + Log.Debug("ExampleRetrieveAndRank", "OnGetClusterConfig | respData is null!"); #else Log.Debug("ExampleRetrieveAndRank", "Not in editor - skipping download."); #endif - } + } + + private void OnSaveConfig(bool success, string data) + { + if (success) + Log.Debug("ExampleRetrieveAndRank", "OnSaveConfig | success!"); + else + Log.Debug("ExampleRetrieveAndRank", "OnSaveConfig | fail!"); + } + + private void OnUploadClusterConfig(UploadResponse resp, string data) + { + if (resp != null) + { + Log.Debug("ExampleRetrieveAndRank", "OnUploadClusterConfig | Success! {0}, {1}", resp.message, resp.statusCode); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnUploadClusterConfig | Failure!"); + } + } - private void OnSaveConfig(bool success, string data) + private void OnGetCollections(CollectionsResponse resp, string data) + { + if (resp != null) { - if (success) - Log.Debug("ExampleRetrieveAndRank", "OnSaveConfig | success!"); + if (resp.responseHeader != null) + Log.Debug("ExampleRetrieveAndRank", "OnGetCollections | status: {0}, QTime: {1}.", resp.responseHeader.status, resp.responseHeader.QTime); + if (resp.collections != null) + { + if (resp.collections.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "OnGetCollections | There are no collections!"); else - Log.Debug("ExampleRetrieveAndRank", "OnSaveConfig | fail!"); + foreach (string collection in resp.collections) + Log.Debug("ExampleRetrieveAndRank", "\tOnGetCollections | collection: {0}", collection); + } + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnGetCollections | GetCollections Response is null!"); } + } - private void OnUploadClusterConfig(UploadResponse resp, string data) + private void OnIndexDocuments(IndexResponse resp, string data) + { + if (resp != null) { - if (resp != null) - { - Log.Debug("ExampleRetrieveAndRank", "OnUploadClusterConfig | Success! {0}, {1}", resp.message, resp.statusCode); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnUploadClusterConfig | Failure!"); - } + if (resp.responseHeader != null) + Log.Debug("ExampleRetrieveAndRank", "OnIndexDocuments | status: {0}, QTime: {1}", resp.responseHeader.status, resp.responseHeader.QTime); + else + Log.Debug("ExampleRetrieveAndRank", "OnIndexDocuments | Response header is null!"); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnIndexDocuments | response is null!"); } + } - private void OnGetCollections(CollectionsResponse resp, string data) + private void OnGetRankers(ListRankersPayload resp, string data) + { + if (resp != null) { - if(resp != null) - { - if(resp.responseHeader != null) - Log.Debug("ExampleRetrieveAndRank", "OnGetCollections | status: {0}, QTime: {1}.", resp.responseHeader.status, resp.responseHeader.QTime); - if(resp.collections != null) - { - if (resp.collections.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "OnGetCollections | There are no collections!"); - else - foreach (string collection in resp.collections) - Log.Debug("ExampleRetrieveAndRank", "\tOnGetCollections | collection: {0}", collection); - } - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnGetCollections | GetCollections Response is null!"); - } + if (resp.rankers.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "OnGetRankers | no rankers!"); + foreach (RankerInfoPayload ranker in resp.rankers) + Log.Debug("ExampleRetrieveAndRank", "OnGetRankers | ranker name: {0}, ID: {1}, created: {2}, url: {3}.", ranker.name, ranker.ranker_id, ranker.created, ranker.url); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnGetRankers | Get Ranker Response is null!"); } + } - private void OnIndexDocuments(IndexResponse resp, string data) + private void OnCreateRanker(RankerStatusPayload resp, string data) + { + if (resp != null) { - if(resp != null) - { - if (resp.responseHeader != null) - Log.Debug("ExampleRetrieveAndRank", "OnIndexDocuments | status: {0}, QTime: {1}", resp.responseHeader.status, resp.responseHeader.QTime); - else - Log.Debug("ExampleRetrieveAndRank", "OnIndexDocuments | Response header is null!"); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnIndexDocuments | response is null!"); - } + Log.Debug("ExampleRetrieveAndRank", "OnCreateRanker | ID: {0}, url: {1}, name: {2}, created: {3}, status: {4}, statusDescription: {5}.", resp.ranker_id, resp.url, resp.name, resp.created, resp.status, resp.status_description); } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnCreateRanker | Get Cluster Response is null!"); + } + } - private void OnGetRankers(ListRankersPayload resp, string data) + private void OnRank(RankerOutputPayload resp, string data) + { + if (resp != null) { - if (resp != null) + Log.Debug("ExampleRetrieveAndRank", "OnRank | ID: {0}, url: {1}, top_answer: {2}.", resp.ranker_id, resp.url, resp.top_answer); + if (resp.answers != null) + if (resp.answers.Length == 0) { - if (resp.rankers.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "OnGetRankers | no rankers!"); - foreach (RankerInfoPayload ranker in resp.rankers) - Log.Debug("ExampleRetrieveAndRank", "OnGetRankers | ranker name: {0}, ID: {1}, created: {2}, url: {3}.", ranker.name, ranker.ranker_id, ranker.created, ranker.url); + Log.Debug("ExampleRetrieveAndRank", "\tThere are no answers!"); } else { - Log.Debug("ExampleRetrieveAndRank", "OnGetRankers | Get Ranker Response is null!"); + foreach (RankedAnswer answer in resp.answers) + Log.Debug("ExampleRetrieveAndRank", "\tOnRank | answerID: {0}, score: {1}, confidence: {2}.", answer.answer_id, answer.score, answer.confidence); } } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnRank | Rank response is null!"); + } + } + + private void OnGetRanker(RankerStatusPayload resp, string data) + { + if (resp != null) + { + Log.Debug("ExampleRetrieveAndRank", "GetRanker | ranker_id: {0}, url: {1}, name: {2}, created: {3}, status: {4}, status_description: {5}.", resp.ranker_id, resp.url, resp.name, resp.created, resp.status, resp.status_description); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "GetRanker | GetRanker response is null!"); + } + } + + private void OnDeleteRanker(bool success, string data) + { + if (success) + { + Log.Debug("ExampleRetrieveAndRank", "OnDeleteRanker | Success!"); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "OnDeleteRanker | Failure!"); + } + } - private void OnCreateRanker(RankerStatusPayload resp, string data) - { - if (resp != null) - { - Log.Debug("ExampleRetrieveAndRank", "OnCreateRanker | ID: {0}, url: {1}, name: {2}, created: {3}, status: {4}, statusDescription: {5}.", resp.ranker_id, resp.url, resp.name, resp.created, resp.status, resp.status_description); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnCreateRanker | Get Cluster Response is null!"); - } - } - - private void OnRank(RankerOutputPayload resp, string data) - { - if (resp != null) - { - Log.Debug("ExampleRetrieveAndRank", "OnRank | ID: {0}, url: {1}, top_answer: {2}.", resp.ranker_id, resp.url, resp.top_answer); - if (resp.answers != null) - if (resp.answers.Length == 0) - { - Log.Debug("ExampleRetrieveAndRank", "\tThere are no answers!"); - } - else - { - foreach (RankedAnswer answer in resp.answers) - Log.Debug("ExampleRetrieveAndRank", "\tOnRank | answerID: {0}, score: {1}, confidence: {2}.", answer.answer_id, answer.score, answer.confidence); - } - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnRank | Rank response is null!"); - } - } - - private void OnGetRanker(RankerStatusPayload resp, string data) - { - if(resp != null) - { - Log.Debug("ExampleRetrieveAndRank", "GetRanker | ranker_id: {0}, url: {1}, name: {2}, created: {3}, status: {4}, status_description: {5}.", resp.ranker_id, resp.url, resp.name, resp.created, resp.status, resp.status_description); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "GetRanker | GetRanker response is null!"); - } - } - - private void OnDeleteRanker(bool success, string data) - { - if (success) - { - Log.Debug("ExampleRetrieveAndRank", "OnDeleteRanker | Success!"); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "OnDeleteRanker | Failure!"); - } - } - - private void OnSearch(SearchResponse resp, string data) + private void OnSearch(SearchResponse resp, string data) + { + if (resp != null) { - if(resp != null) + if (resp.responseHeader != null) + { + Log.Debug("ExampleRetrieveAndRank", "Search | status: {0}, QTime: {1}.", resp.responseHeader.status, resp.responseHeader.QTime); + if (resp.responseHeader._params != null) + Log.Debug("ExampleRetrieveAndRank", "\tSearch | params.q: {0}, params.fl: {1}, params.wt: {2}.", resp.responseHeader._params.q, resp.responseHeader._params.fl, resp.responseHeader._params.wt); + else + Log.Debug("ExampleRetrieveAndRank", "Search | responseHeader.params is null!"); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search | response header is null!"); + } + + if (resp.response != null) + { + Log.Debug("ExampleRetrieveAndRank", "Search | numFound: {0}, start: {1}.", resp.response.numFound, resp.response.start); + if (resp.response.docs != null) { - if(resp.responseHeader != null) - { - Log.Debug("ExampleRetrieveAndRank", "Search | status: {0}, QTime: {1}.", resp.responseHeader.status, resp.responseHeader.QTime); - if (resp.responseHeader._params != null) - Log.Debug("ExampleRetrieveAndRank", "\tSearch | params.q: {0}, params.fl: {1}, params.wt: {2}.", resp.responseHeader._params.q, resp.responseHeader._params.fl, resp.responseHeader._params.wt); - else - Log.Debug("ExampleRetrieveAndRank", "Search | responseHeader.params is null!"); - } - else + if (resp.response.docs.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "Search | There are no docs!"); + else + foreach (Doc doc in resp.response.docs) { - Log.Debug("ExampleRetrieveAndRank", "Search | response header is null!"); - } + Log.Debug("ExampleRetrieveAndRank", "\tSearch | id: {0}.", doc.id); - if (resp.response != null) - { - Log.Debug("ExampleRetrieveAndRank", "Search | numFound: {0}, start: {1}.", resp.response.numFound, resp.response.start); - if(resp.response.docs != null) - { - if (resp.response.docs.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "Search | There are no docs!"); - else - foreach (Doc doc in resp.response.docs) - { - Log.Debug("ExampleRetrieveAndRank", "\tSearch | id: {0}.", doc.id); - - if (doc.title != null) - { - if (doc.title.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "Search | There are no title"); - else - foreach (string s in doc.title) - Log.Debug("ExampleRetrieveAndRank", "\tSearch | title: {0}.", s); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "Search | title is null"); - } - - if (doc.author != null) - { - if (doc.author.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "Search | There are no authors"); - else - foreach (string s in doc.author) - Log.Debug("ExampleRetrieveAndRank", "\tSearch | Author: {0}.", s); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "Search | Authors is null"); - } - - if (doc.body != null) - { - if (doc.body.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "Search | There are no body"); - else - foreach (string s in doc.body) - Log.Debug("ExampleRetrieveAndRank", "\tSearch | body: {0}.", s); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "Search | Body is null"); - } - - if (doc.bibliography != null) - { - if (doc.bibliography.Length == 0) - Log.Debug("ExampleRetrieveAndRank", "Search | There are no bibliographies"); - else - foreach (string s in doc.bibliography) - Log.Debug("ExampleRetrieveAndRank", "\tSearch | bibliography: {0}.", s); - } - else - { - Log.Debug("ExampleRetrieveAndRank", "Search | Bibliography is null"); - } - } - } + if (doc.title != null) + { + if (doc.title.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "Search | There are no title"); else - { - Log.Debug("ExampleRetrieveAndRank", "Search | docs are null!"); - } - } - else - { - Log.Debug("ExampleRetrieveAndRank", "Search | response is null!"); + foreach (string s in doc.title) + Log.Debug("ExampleRetrieveAndRank", "\tSearch | title: {0}.", s); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search | title is null"); + } + + if (doc.author != null) + { + if (doc.author.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "Search | There are no authors"); + else + foreach (string s in doc.author) + Log.Debug("ExampleRetrieveAndRank", "\tSearch | Author: {0}.", s); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search | Authors is null"); + } + + if (doc.body != null) + { + if (doc.body.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "Search | There are no body"); + else + foreach (string s in doc.body) + Log.Debug("ExampleRetrieveAndRank", "\tSearch | body: {0}.", s); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search | Body is null"); + } + + if (doc.bibliography != null) + { + if (doc.bibliography.Length == 0) + Log.Debug("ExampleRetrieveAndRank", "Search | There are no bibliographies"); + else + foreach (string s in doc.bibliography) + Log.Debug("ExampleRetrieveAndRank", "\tSearch | bibliography: {0}.", s); + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search | Bibliography is null"); + } } } else { - Log.Debug("ExampleRetrieveAndRank", "Search response is null!"); + Log.Debug("ExampleRetrieveAndRank", "Search | docs are null!"); } + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search | response is null!"); + } + } + else + { + Log.Debug("ExampleRetrieveAndRank", "Search response is null!"); } + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleSpeechToText.cs b/Examples/ServiceExamples/Scripts/ExampleSpeechToText.cs index 83af8506f..292efa554 100755 --- a/Examples/ServiceExamples/Scripts/ExampleSpeechToText.cs +++ b/Examples/ServiceExamples/Scripts/ExampleSpeechToText.cs @@ -22,447 +22,447 @@ public class ExampleSpeechToText : MonoBehaviour { - [SerializeField] - private AudioClip m_AudioClip = new AudioClip(); - private SpeechToText m_SpeechToText = new SpeechToText(); + [SerializeField] + private AudioClip m_AudioClip = new AudioClip(); + private SpeechToText m_SpeechToText = new SpeechToText(); + + private string m_CreatedCustomizationID; + private string m_CreatedCorpusName = "unity-corpus"; + private string m_CustomCorpusFilePath; + + void Start() + { + //m_SpeechToText.Recognize(m_AudioClip, HandleOnRecognize); + LogSystem.InstallDefaultReactors(); + + m_CustomCorpusFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-corpus.txt"; + + // test GetModels and GetModel + //TestGetModels(); + + // test CreateSession + //TestCreateSession("en-US_BroadbandModel"); + + // test GetCustomizations + //TestGetCustomizations(); + + // test create, get and delete customizations + //TestCreateCustomization(); + } + + private void TestGetModels() + { + Log.Debug("ExampleSpeechToText", "Attempting to get models"); + m_SpeechToText.GetModels(HandleGetModels); + } + + private void TestGetModel(string modelID) + { + Log.Debug("ExampleSpeechToText", "Attempting to get model {0}", modelID); + m_SpeechToText.GetModel(HandleGetModel, modelID); + } + + private void TestGetCustomizations() + { + Log.Debug("ExampleSpeechToText", "Attempting to get customizations"); + m_SpeechToText.GetCustomizations(HandleGetCustomizations); + } + + private void TestCreateCustomization() + { + Log.Debug("ExampleSpeechToText", "Attempting create customization"); + m_SpeechToText.CreateCustomization(HandleCreateCustomization, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); + } + + private void TestDeleteCustomization(string customizationID) + { + Log.Debug("ExampleSpeechToText", "Attempting to delete customization {0}", customizationID); + m_SpeechToText.DeleteCustomization(HandleDeleteCustomization, customizationID); + } + + private void TestGetCustomization(string customizationID) + { + Log.Debug("ExampleSpeechToText", "Attempting to get customization {0}", customizationID); + m_SpeechToText.GetCustomization(HandleGetCustomization, customizationID); + } + + private void TestTrainCustomization(string customizationID) + { + Log.Debug("ExampleSpeechToText", "Attempting to train customization {0}", customizationID); + m_SpeechToText.TrainCustomization(HandleTrainCustomization, customizationID); + } + + private void TestUpgradeCustomization(string customizationID) + { + Log.Debug("ExampleSpeechToText", "Attempting to upgrade customization {0}", customizationID); + m_SpeechToText.UpgradeCustomization(HandleUpgradeCustomization, customizationID); + } + + private void TestResetCustomization(string customizationID) + { + Log.Debug("ExampleSpeechToText", "Attempting to reset customization {0}", customizationID); + m_SpeechToText.ResetCustomization(HandleResetCustomization, customizationID); + } + + private void TestGetCustomCorpora(string customizationID) + { + Log.Debug("ExampleSpeechToText", "Attempting to get custom corpora for {0}", customizationID); + m_SpeechToText.GetCustomCorpora(HandleGetCustomCorpora, customizationID); + } + + private void TestDeleteCustomCorpus(string customizationID, string corpusName) + { + Log.Debug("ExampleSpeechToText", "Attempting to delete custom corpus {1} in customization {0}", customizationID, corpusName); + m_SpeechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, customizationID, corpusName); + } + + private void TestAddCustomCorpus(string customizationID, string corpusName, bool allowOverwrite, string trainingDataPath) + { + Log.Debug("ExampleSpeechToText", "Attempting to add custom corpus {1} in customization {0}", customizationID, corpusName); + m_SpeechToText.AddCustomCorpus(HandleAddCustomCorpus, customizationID, corpusName, allowOverwrite, trainingDataPath); + } + + private void TestGetCustomWords() + { + Log.Debug("ExampleSpeechToText", "Attempting to get custom words."); + m_SpeechToText.GetCustomWords(HandleGetCustomWords, m_CreatedCustomizationID); + } + + private void TestAddCustomWordsPath(string customizationID, string wordsJsonPath) + { + Log.Debug("ExampleSpeechToText", "Attempting to add custom words in customization {0} using Words json path {1}", customizationID, wordsJsonPath); + m_SpeechToText.AddCustomWords(HandleAddCustomWords, customizationID, wordsJsonPath); + } + + private void TestAddCustomWordsWordsObject(string customizationID, Words words) + { + Log.Debug("ExampleSpeechToText", "Attempting to add custom words in customization {0} using Words object", customizationID); + m_SpeechToText.AddCustomWords(HandleAddCustomWords, customizationID, words); + } + + private void TestDeleteCustomWord(string customizationID, string word) + { + Log.Debug("ExampleSpeechToText", "Attempting to delete custom word {1} in customization {0}", customizationID, word); + m_SpeechToText.DeleteCustomWord(HandleDeleteCustomWord, customizationID, word); + } + + private void TestGetCustomWord(string customizationID, string word) + { + Log.Debug("ExampleSpeechToText", "Attempting to get custom word {1} in customization {0}", customizationID, word); + m_SpeechToText.GetCustomWord(HandleGetCustomWord, customizationID, word); + } + + + + private void HandleGetModels(Model[] models) + { + if (models != null) + { + if (models != null) + { + if (models.Length == 0) + { + Log.Warning("ExampleSpeedchToText", "There are no custom models!"); + } + else + { + foreach (Model model in models) + { + Log.Debug("ExampleSpeechToText", "Model: {0}", model.name); + } + + TestGetModel((models[Random.Range(0, models.Length - 1)] as Model).name); + } + } + } + else + { + Log.Warning("ExampleSpeechToText", "Failed to get models!"); + } + } + + private void HandleGetModel(Model model) + { + if (model != null) + { + Log.Debug("ExampleSpeechToText", "Model - name: {0} | description: {1} | language:{2} | rate: {3} | sessions: {4} | url: {5} | customLanguageModel: {6}", + model.name, model.description, model.language, model.rate, model.sessions, model.url, model.supported_features.custom_language_model); + } + else + { + Log.Warning("ExampleSpeechToText", "Failed to get model!"); + } + } + + private void HandleOnRecognize(SpeechRecognitionEvent result) + { + if (result != null && result.results.Length > 0) + { + foreach (var res in result.results) + { + foreach (var alt in res.alternatives) + { + string text = alt.transcript; + Log.Debug("ExampleSpeechToText", string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); + } + } + } + } + + private void HandleGetCustomizations(Customizations customizations, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (customizations != null) + { + if (customizations.customizations.Length > 0) + { + foreach (Customization customization in customizations.customizations) + Log.Debug("ExampleSpeechToText", "Customization - name: {0} | description: {1} | status: {2}", customization.name, customization.description, customization.status); + + Log.Debug("ExampleSpeechToText", "GetCustomizations() succeeded!"); + } + else + { + Log.Debug("ExampleSpeechToText", "There are no customizations!"); + } + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to get customizations!"); + } + } + + private void HandleCreateCustomization(CustomizationID customizationID, string customData) + { + if (customizationID != null) + { + Log.Debug("ExampleSpeechToText", "Customization created: {0}", customizationID.customization_id); + Log.Debug("ExampleSpeechToText", "CreateCustomization() succeeded!"); + + m_CreatedCustomizationID = customizationID.customization_id; + TestGetCustomization(m_CreatedCustomizationID); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to create customization!"); + } + } + + private void HandleDeleteCustomization(bool success, string customData) + { + if (success) + { + Log.Debug("ExampleSpeechToText", "Deleted customization {0}!", m_CreatedCustomizationID); + Log.Debug("ExampleSpeechToText", "DeletedCustomization() succeeded!"); + m_CreatedCustomizationID = default(string); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to delete customization!"); + } + } + + private void HandleGetCustomization(Customization customization, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (customization != null) + { + Log.Debug("ExampleSpeechToText", "Customization - name: {0} | description: {1} | status: {2}", customization.name, customization.description, customization.status); + Log.Debug("ExampleSpeechToText", "GetCustomization() succeeded!"); + + // test add custom corpora + //TestAddCustomCorpus(m_CreatedCustomizationID, m_CreatedCorpusName, true, m_CustomCorpusFilePath); + TestDeleteCustomization(m_CreatedCustomizationID); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to get customization {0}!", m_CreatedCustomizationID); + } + } + + private void HandleTrainCustomization(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (success) + { + Log.Debug("ExampleSpeechToText", "Train customization {0}!", m_CreatedCustomizationID); + Log.Debug("ExampleSpeechToText", "TrainCustomization() succeeded!"); + + TestResetCustomization(m_CreatedCustomizationID); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to train customization!"); + } + } + + private void HandleUpgradeCustomization(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (success) + { + Log.Debug("ExampleSpeechToText", "Upgrade customization {0}!", m_CreatedCustomizationID); + Log.Debug("ExampleSpeechToText", "UpgradeCustomization() succeeded!"); + + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to upgrade customization!"); + } + } - private string m_CreatedCustomizationID; - private string m_CreatedCorpusName = "unity-corpus"; - private string m_CustomCorpusFilePath; + private void HandleResetCustomization(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - void Start() + if (success) { - //m_SpeechToText.Recognize(m_AudioClip, HandleOnRecognize); - LogSystem.InstallDefaultReactors(); + Log.Debug("ExampleSpeechToText", "Reset customization {0}!", m_CreatedCustomizationID); + Log.Debug("ExampleSpeechToText", "ResetCustomization() succeeded!"); - m_CustomCorpusFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-corpus.txt"; - - // test GetModels and GetModel - //TestGetModels(); + // test delete custom corpus + TestDeleteCustomCorpus(m_CreatedCustomizationID, m_CreatedCorpusName); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to reset customization!"); + } + } - // test CreateSession - //TestCreateSession("en-US_BroadbandModel"); + private void HandleGetCustomCorpora(Corpora corpora, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "CustomData: {0}", customData); - // test GetCustomizations - //TestGetCustomizations(); + if (corpora != null) + { + if (corpora.corpora.Length > 0) + { + foreach (Corpus corpus in corpora.corpora) + Log.Debug("ExampleSpeechToText", "Corpus - name: {0} | total_words: {1} | out_of_vocabulary_words: {2} | staus: {3}", + corpus.name, corpus.total_words, corpus.out_of_vocabulary_words, corpus.status); + + //TestUpgradeCustomization(m_CreatedCustomizationID); + TestTrainCustomization(m_CreatedCustomizationID); + } + else + { + Log.Debug("ExampleSpeechToText", "There are no custom corpora!"); + } + + Log.Debug("ExampleSpeechToText", "GetCustomCorpora() succeeded!"); + TestDeleteCustomization(m_CreatedCustomizationID); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to get custom corpora!"); + } + } + + private void HandleDeleteCustomCorpus(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (success) + { + Log.Debug("ExampleSpeechToText", "DeleteCustomCorpus() succeeded!"); - // test create, get and delete customizations - //TestCreateCustomization(); } + else + { + Log.Debug("ExampleSpeechToText", "Failed to delete custom corpus!"); + } + } + + private void HandleAddCustomCorpus(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (success) + { + Log.Debug("ExampleSpeechToText", "AddCustomCorpus() succeeded!"); + + // test get custom corpora + TestGetCustomCorpora(m_CreatedCustomizationID); + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to delete custom corpus!"); + } + } + + private void HandleGetCustomWords(WordsList wordList, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (wordList != null) + { + if (wordList.words != null && wordList.words.Length > 0) + { + foreach (WordData word in wordList.words) + Log.Debug("ExampleSpeechToText", "WordData - word: {0} | sounds like: {1} | display as: {2}", word.word, word.sounds_like, word.display_as); + } + else + { + Log.Debug("ExampleSpeechToText", "No custom words found!"); + } + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to get custom words!"); + } + } + + private void HandleAddCustomWords(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (success) + { + Log.Debug("ExampleSpeechToText", "AddCustomWOrds() succeeded!"); + + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to add custom words!"); + } + } + + private void HandleDeleteCustomWord(bool success, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); + + if (success) + { + Log.Debug("ExampleSpeechToText", "DeleteCustomWord() succeeded!"); + + } + else + { + Log.Debug("ExampleSpeechToText", "Failed to delete custom word!"); + } + } + + private void HandleGetCustomWord(WordData word, string customData) + { + if (!string.IsNullOrEmpty(customData)) + Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - private void TestGetModels() - { - Log.Debug("ExampleSpeechToText", "Attempting to get models"); - m_SpeechToText.GetModels(HandleGetModels); - } - - private void TestGetModel(string modelID) - { - Log.Debug("ExampleSpeechToText", "Attempting to get model {0}", modelID); - m_SpeechToText.GetModel(HandleGetModel, modelID); - } - - private void TestGetCustomizations() - { - Log.Debug("ExampleSpeechToText", "Attempting to get customizations"); - m_SpeechToText.GetCustomizations(HandleGetCustomizations); - } - - private void TestCreateCustomization() - { - Log.Debug("ExampleSpeechToText", "Attempting create customization"); - m_SpeechToText.CreateCustomization(HandleCreateCustomization, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); - } - - private void TestDeleteCustomization(string customizationID) - { - Log.Debug("ExampleSpeechToText", "Attempting to delete customization {0}", customizationID); - m_SpeechToText.DeleteCustomization(HandleDeleteCustomization, customizationID); - } - - private void TestGetCustomization(string customizationID) - { - Log.Debug("ExampleSpeechToText", "Attempting to get customization {0}", customizationID); - m_SpeechToText.GetCustomization(HandleGetCustomization, customizationID); - } - - private void TestTrainCustomization(string customizationID) - { - Log.Debug("ExampleSpeechToText", "Attempting to train customization {0}", customizationID); - m_SpeechToText.TrainCustomization(HandleTrainCustomization, customizationID); - } - - private void TestUpgradeCustomization(string customizationID) - { - Log.Debug("ExampleSpeechToText", "Attempting to upgrade customization {0}", customizationID); - m_SpeechToText.UpgradeCustomization(HandleUpgradeCustomization, customizationID); - } - - private void TestResetCustomization(string customizationID) - { - Log.Debug("ExampleSpeechToText", "Attempting to reset customization {0}", customizationID); - m_SpeechToText.ResetCustomization(HandleResetCustomization, customizationID); - } - - private void TestGetCustomCorpora(string customizationID) - { - Log.Debug("ExampleSpeechToText", "Attempting to get custom corpora for {0}", customizationID); - m_SpeechToText.GetCustomCorpora(HandleGetCustomCorpora, customizationID); - } - - private void TestDeleteCustomCorpus(string customizationID, string corpusName) - { - Log.Debug("ExampleSpeechToText", "Attempting to delete custom corpus {1} in customization {0}", customizationID, corpusName); - m_SpeechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, customizationID, corpusName); - } - - private void TestAddCustomCorpus(string customizationID, string corpusName, bool allowOverwrite, string trainingDataPath) - { - Log.Debug("ExampleSpeechToText", "Attempting to add custom corpus {1} in customization {0}", customizationID, corpusName); - m_SpeechToText.AddCustomCorpus(HandleAddCustomCorpus, customizationID, corpusName, allowOverwrite, trainingDataPath); - } - - private void TestGetCustomWords() - { - Log.Debug("ExampleSpeechToText", "Attempting to get custom words."); - m_SpeechToText.GetCustomWords(HandleGetCustomWords, m_CreatedCustomizationID); - } - - private void TestAddCustomWordsPath(string customizationID, string wordsJsonPath) - { - Log.Debug("ExampleSpeechToText", "Attempting to add custom words in customization {0} using Words json path {1}", customizationID, wordsJsonPath); - m_SpeechToText.AddCustomWords(HandleAddCustomWords, customizationID, wordsJsonPath); - } - - private void TestAddCustomWordsWordsObject(string customizationID, Words words) - { - Log.Debug("ExampleSpeechToText", "Attempting to add custom words in customization {0} using Words object", customizationID); - m_SpeechToText.AddCustomWords(HandleAddCustomWords, customizationID, words); - } - - private void TestDeleteCustomWord(string customizationID, string word) - { - Log.Debug("ExampleSpeechToText", "Attempting to delete custom word {1} in customization {0}", customizationID, word); - m_SpeechToText.DeleteCustomWord(HandleDeleteCustomWord, customizationID, word); - } - - private void TestGetCustomWord(string customizationID, string word) - { - Log.Debug("ExampleSpeechToText", "Attempting to get custom word {1} in customization {0}", customizationID, word); - m_SpeechToText.GetCustomWord(HandleGetCustomWord, customizationID, word); - } - - - - private void HandleGetModels(Model[] models) - { - if (models != null) - { - if (models != null) - { - if (models.Length == 0) - { - Log.Warning("ExampleSpeedchToText", "There are no custom models!"); - } - else - { - foreach (Model model in models) - { - Log.Debug("ExampleSpeechToText", "Model: {0}", model.name); - } - - TestGetModel((models[Random.Range(0, models.Length - 1)] as Model).name); - } - } - } - else - { - Log.Warning("ExampleSpeechToText", "Failed to get models!"); - } - } - - private void HandleGetModel(Model model) - { - if(model != null) - { - Log.Debug("ExampleSpeechToText", "Model - name: {0} | description: {1} | language:{2} | rate: {3} | sessions: {4} | url: {5} | customLanguageModel: {6}", - model.name, model.description, model.language, model.rate, model.sessions, model.url, model.supported_features.custom_language_model); - } - else - { - Log.Warning("ExampleSpeechToText", "Failed to get model!"); - } - } - - private void HandleOnRecognize (SpeechRecognitionEvent result) - { - if (result != null && result.results.Length > 0) - { - foreach( var res in result.results ) - { - foreach( var alt in res.alternatives ) - { - string text = alt.transcript; - Log.Debug("ExampleSpeechToText", string.Format( "{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); - } - } - } - } - - private void HandleGetCustomizations(Customizations customizations, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (customizations != null) - { - if(customizations.customizations.Length > 0) - { - foreach (Customization customization in customizations.customizations) - Log.Debug("ExampleSpeechToText", "Customization - name: {0} | description: {1} | status: {2}", customization.name, customization.description, customization.status); - - Log.Debug("ExampleSpeechToText", "GetCustomizations() succeeded!"); - } - else - { - Log.Debug("ExampleSpeechToText", "There are no customizations!"); - } - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to get customizations!"); - } - } - - private void HandleCreateCustomization(CustomizationID customizationID, string customData) - { - if(customizationID != null) - { - Log.Debug("ExampleSpeechToText", "Customization created: {0}", customizationID.customization_id); - Log.Debug("ExampleSpeechToText", "CreateCustomization() succeeded!"); - - m_CreatedCustomizationID = customizationID.customization_id; - TestGetCustomization(m_CreatedCustomizationID); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to create customization!"); - } - } - - private void HandleDeleteCustomization(bool success, string customData) - { - if (success) - { - Log.Debug("ExampleSpeechToText", "Deleted customization {0}!", m_CreatedCustomizationID); - Log.Debug("ExampleSpeechToText", "DeletedCustomization() succeeded!"); - m_CreatedCustomizationID = default(string); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to delete customization!"); - } - } - - private void HandleGetCustomization(Customization customization, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if(customization != null) - { - Log.Debug("ExampleSpeechToText", "Customization - name: {0} | description: {1} | status: {2}", customization.name, customization.description, customization.status); - Log.Debug("ExampleSpeechToText", "GetCustomization() succeeded!"); - - // test add custom corpora - //TestAddCustomCorpus(m_CreatedCustomizationID, m_CreatedCorpusName, true, m_CustomCorpusFilePath); - TestDeleteCustomization(m_CreatedCustomizationID); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to get customization {0}!", m_CreatedCustomizationID); - } - } - - private void HandleTrainCustomization(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "Train customization {0}!", m_CreatedCustomizationID); - Log.Debug("ExampleSpeechToText", "TrainCustomization() succeeded!"); - - TestResetCustomization(m_CreatedCustomizationID); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to train customization!"); - } - } - - private void HandleUpgradeCustomization(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "Upgrade customization {0}!", m_CreatedCustomizationID); - Log.Debug("ExampleSpeechToText", "UpgradeCustomization() succeeded!"); - - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to upgrade customization!"); - } - } - - private void HandleResetCustomization(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "Reset customization {0}!", m_CreatedCustomizationID); - Log.Debug("ExampleSpeechToText", "ResetCustomization() succeeded!"); - - // test delete custom corpus - TestDeleteCustomCorpus(m_CreatedCustomizationID, m_CreatedCorpusName); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to reset customization!"); - } - } - - private void HandleGetCustomCorpora(Corpora corpora, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "CustomData: {0}", customData); - - if(corpora != null) - { - if(corpora.corpora.Length > 0) - { - foreach (Corpus corpus in corpora.corpora) - Log.Debug("ExampleSpeechToText", "Corpus - name: {0} | total_words: {1} | out_of_vocabulary_words: {2} | staus: {3}", - corpus.name, corpus.total_words, corpus.out_of_vocabulary_words, corpus.status); - - //TestUpgradeCustomization(m_CreatedCustomizationID); - TestTrainCustomization(m_CreatedCustomizationID); - } - else - { - Log.Debug("ExampleSpeechToText", "There are no custom corpora!"); - } - - Log.Debug("ExampleSpeechToText", "GetCustomCorpora() succeeded!"); - TestDeleteCustomization(m_CreatedCustomizationID); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to get custom corpora!"); - } - } - - private void HandleDeleteCustomCorpus(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "DeleteCustomCorpus() succeeded!"); - - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to delete custom corpus!"); - } - } - - private void HandleAddCustomCorpus(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "AddCustomCorpus() succeeded!"); - - // test get custom corpora - TestGetCustomCorpora(m_CreatedCustomizationID); - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to delete custom corpus!"); - } - } - - private void HandleGetCustomWords(WordsList wordList, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if(wordList != null) - { - if (wordList.words != null && wordList.words.Length > 0) - { - foreach (WordData word in wordList.words) - Log.Debug("ExampleSpeechToText", "WordData - word: {0} | sounds like: {1} | display as: {2}", word.word, word.sounds_like, word.display_as); - } - else - { - Log.Debug("ExampleSpeechToText", "No custom words found!"); - } - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to get custom words!"); - } - } - - private void HandleAddCustomWords(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "AddCustomWOrds() succeeded!"); - - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to add custom words!"); - } - } - - private void HandleDeleteCustomWord(bool success, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if (success) - { - Log.Debug("ExampleSpeechToText", "DeleteCustomWord() succeeded!"); - - } - else - { - Log.Debug("ExampleSpeechToText", "Failed to delete custom word!"); - } - } - - private void HandleGetCustomWord(WordData word, string customData) - { - if (!string.IsNullOrEmpty(customData)) - Log.Debug("ExampleSpeechToText", "custom data: {0}", customData); - - if(word != null) - Log.Debug("ExampleSpeechToText", "WordData - word: {0} | sounds like: {1} | display as: {2}", word.word, word.sounds_like, word.display_as); - } + if (word != null) + Log.Debug("ExampleSpeechToText", "WordData - word: {0} | sounds like: {1} | display as: {2}", word.word, word.sounds_like, word.display_as); + } } \ No newline at end of file diff --git a/Examples/ServiceExamples/Scripts/ExampleTextToSpeech.cs b/Examples/ServiceExamples/Scripts/ExampleTextToSpeech.cs index 0222d75ae..8086396a5 100755 --- a/Examples/ServiceExamples/Scripts/ExampleTextToSpeech.cs +++ b/Examples/ServiceExamples/Scripts/ExampleTextToSpeech.cs @@ -22,254 +22,254 @@ public class ExampleTextToSpeech : MonoBehaviour { - TextToSpeech m_TextToSpeech = new TextToSpeech(); - string m_TestString = "I'm sorry. This is Text to Speech!I'm sorry. This is Text to Speech!"; - - - void Start () - { - LogSystem.InstallDefaultReactors(); - - //// Get Voices - //Log.Debug("ExampleTextToSpeech", "Attempting to get voices."); - //m_TextToSpeech.GetVoices(OnGetVoices); - - //// Get Voice - ////string selectedVoice = "en-US_AllisonVoice"; - //Log.Debug("ExampleTextToSpeech", "Attempting to get voice {0}.", VoiceType.en_US_Allison); - //m_TextToSpeech.GetVoice(OnGetVoice, VoiceType.en_US_Allison); - - //// Get Pronunciation - //string testWord = "Watson"; - //Log.Debug("ExampleTextToSpeech", "Attempting to get pronunciation of {0}", testWord); - //m_TextToSpeech.GetPronunciation(OnGetPronunciation, testWord, VoiceType.en_US_Allison); - - // Get Customizations - //Log.Debug("ExampleTextToSpeech", "Attempting to get a list of customizations"); - //m_TextToSpeech.GetCustomizations(OnGetCustomizations); - - // Create Customization - //Log.Debug("ExampleTextToSpeech", "Attempting to create a customization"); - //string customizationName = "unity-example-customization"; - //string customizationLanguage = "en-US"; - //string customizationDescription = "A text to speech voice customization created within Unity."; - //m_TextToSpeech.CreateCustomization(OnCreateCustomization, customizationName, customizationLanguage, customizationDescription); - - // Delete Customization - //Log.Debug("ExampleTextToSpeech", "Attempting to delete a customization"); - //string customizationIdentifierToDelete = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //if (!m_TextToSpeech.DeleteCustomization(OnDeleteCustomization, customizationIdentifierToDelete)) - // Log.Debug("ExampleTextToSpeech", "Failed to delete custom voice model!"); - - // Get Customization - //Log.Debug("ExampleTextToSpeech", "Attempting to get a customization"); - //string customizationIdentifierToGet = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //if (!m_TextToSpeech.GetCustomization(OnGetCustomization, customizationIdentifierToGet)) - // Log.Debug("ExampleTextToSpeech", "Failed to get custom voice model!"); - - // Update Customization - Log.Debug("ExampleTextToSpeech", "Attempting to update a customization"); - Word word0 = new Word(); - word0.word = "hello"; - word0.translation = "hullo"; - Word word1 = new Word(); - word1.word = "goodbye"; - word1.translation = "gbye"; - Word word2 = new Word(); - word2.word = "hi"; - word2.translation = "ohiooo"; - Word[] words = { word0, word1, word2 }; - CustomVoiceUpdate customVoiceUpdate = new CustomVoiceUpdate(); - customVoiceUpdate.words = words; - customVoiceUpdate.description = "My updated description"; - customVoiceUpdate.name = "My updated name"; - string customizationIdToUpdate = "1476ea80-5355-4911-ac99-ba39162a2d34"; - if (!m_TextToSpeech.UpdateCustomization(OnUpdateCustomization, customizationIdToUpdate, customVoiceUpdate)) - Log.Debug("ExampleTextToSpeech", "Failed to update customization!"); - - // Get Customization Words - //Log.Debug("ExampleTextToSpeech", "Attempting to get a customization's words"); - //string customIdentifierToGetWords = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //if (!m_TextToSpeech.GetCustomizationWords(OnGetCustomizationWords, customIdentifierToGetWords)) - // Log.Debug("ExampleTextToSpeech", "Failed to get {0} words!", customIdentifierToGetWords); - - // Add Customization Words - //Log.Debug("ExampleTextToSpeech", "Attempting to add words to a customization"); - //string customIdentifierToAddWords = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //Words words = new Words(); - //Word word0 = new Word(); - //word0.word = "bananna"; - //word0.translation = "bunanna"; - //Word word1 = new Word(); - //word1.word = "orange"; - //word1.translation = "arange"; - //Word word2 = new Word(); - //word2.word = "tomato"; - //word2.translation = "tomahto"; - //Word[] wordArray = { word0, word1, word2 }; - //words.words = wordArray; - //if (!m_TextToSpeech.AddCustomizationWords(OnAddCustomizationWords, customIdentifierToAddWords, words)) - // Log.Debug("ExampleTextToSpeech", "Failed to add words to {0}!", customIdentifierToAddWords); - - // Delete Customization Word - //Log.Debug("ExampleTextToSpeech", "Attempting to delete customization word from custom voice model."); - //string customIdentifierToDeleteWord = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //string wordToDelete = "goodbye"; - //if (!m_TextToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, customIdentifierToDeleteWord, wordToDelete)) - // Log.Debug("ExampleTextToSpeech", "Failed to delete {0} from {1}!", wordToDelete, customIdentifierToDeleteWord); - - // Get Customization Word - //Log.Debug("ExampleTextToSpeech", "Attempting to get the translation of a custom voice model's word."); - //string customIdentifierToGetWord = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //string customIdentifierWord = "hello"; - //if (!m_TextToSpeech.GetCustomizationWord(OnGetCustomizationWord, customIdentifierToGetWord, customIdentifierWord)) - // Log.Debug("ExampleTextToSpeech", "Failed to get the translation of {0} from {1}!", customIdentifierWord, customIdentifierToGetWord); - - // Add Customization Word - This is not working. The PUT method is not supported by Unity. - //Log.Debug("ExampleTextToSpeech", "Attempting to add a single word and translation to a custom voice model."); - //string customIdentifierToAddWordAndTranslation = "1476ea80-5355-4911-ac99-ba39162a2d34"; - //string word = "grasshopper"; - //string translation = "guhrasshoppe"; - //if (!m_TextToSpeech.AddCustomizationWord(OnAddCustomizationWord, customIdentifierToAddWordAndTranslation, word, translation)) - // Log.Debug("ExampleTextToSpeech", "Failed to add {0}/{1} to {2}!", word, translation, customIdentifierToAddWordAndTranslation); - - - //m_TextToSpeech.Voice = VoiceType.en_US_Allison; - //m_TextToSpeech.ToSpeech(m_TestString, HandleToSpeechCallback, true); - + TextToSpeech m_TextToSpeech = new TextToSpeech(); + string m_TestString = "I'm sorry. This is Text to Speech!I'm sorry. This is Text to Speech!"; + + + void Start() + { + LogSystem.InstallDefaultReactors(); + + //// Get Voices + //Log.Debug("ExampleTextToSpeech", "Attempting to get voices."); + //m_TextToSpeech.GetVoices(OnGetVoices); + + //// Get Voice + ////string selectedVoice = "en-US_AllisonVoice"; + //Log.Debug("ExampleTextToSpeech", "Attempting to get voice {0}.", VoiceType.en_US_Allison); + //m_TextToSpeech.GetVoice(OnGetVoice, VoiceType.en_US_Allison); + + //// Get Pronunciation + //string testWord = "Watson"; + //Log.Debug("ExampleTextToSpeech", "Attempting to get pronunciation of {0}", testWord); + //m_TextToSpeech.GetPronunciation(OnGetPronunciation, testWord, VoiceType.en_US_Allison); + + // Get Customizations + //Log.Debug("ExampleTextToSpeech", "Attempting to get a list of customizations"); + //m_TextToSpeech.GetCustomizations(OnGetCustomizations); + + // Create Customization + //Log.Debug("ExampleTextToSpeech", "Attempting to create a customization"); + //string customizationName = "unity-example-customization"; + //string customizationLanguage = "en-US"; + //string customizationDescription = "A text to speech voice customization created within Unity."; + //m_TextToSpeech.CreateCustomization(OnCreateCustomization, customizationName, customizationLanguage, customizationDescription); + + // Delete Customization + //Log.Debug("ExampleTextToSpeech", "Attempting to delete a customization"); + //string customizationIdentifierToDelete = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //if (!m_TextToSpeech.DeleteCustomization(OnDeleteCustomization, customizationIdentifierToDelete)) + // Log.Debug("ExampleTextToSpeech", "Failed to delete custom voice model!"); + + // Get Customization + //Log.Debug("ExampleTextToSpeech", "Attempting to get a customization"); + //string customizationIdentifierToGet = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //if (!m_TextToSpeech.GetCustomization(OnGetCustomization, customizationIdentifierToGet)) + // Log.Debug("ExampleTextToSpeech", "Failed to get custom voice model!"); + + // Update Customization + Log.Debug("ExampleTextToSpeech", "Attempting to update a customization"); + Word word0 = new Word(); + word0.word = "hello"; + word0.translation = "hullo"; + Word word1 = new Word(); + word1.word = "goodbye"; + word1.translation = "gbye"; + Word word2 = new Word(); + word2.word = "hi"; + word2.translation = "ohiooo"; + Word[] words = { word0, word1, word2 }; + CustomVoiceUpdate customVoiceUpdate = new CustomVoiceUpdate(); + customVoiceUpdate.words = words; + customVoiceUpdate.description = "My updated description"; + customVoiceUpdate.name = "My updated name"; + string customizationIdToUpdate = "1476ea80-5355-4911-ac99-ba39162a2d34"; + if (!m_TextToSpeech.UpdateCustomization(OnUpdateCustomization, customizationIdToUpdate, customVoiceUpdate)) + Log.Debug("ExampleTextToSpeech", "Failed to update customization!"); + + // Get Customization Words + //Log.Debug("ExampleTextToSpeech", "Attempting to get a customization's words"); + //string customIdentifierToGetWords = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //if (!m_TextToSpeech.GetCustomizationWords(OnGetCustomizationWords, customIdentifierToGetWords)) + // Log.Debug("ExampleTextToSpeech", "Failed to get {0} words!", customIdentifierToGetWords); + + // Add Customization Words + //Log.Debug("ExampleTextToSpeech", "Attempting to add words to a customization"); + //string customIdentifierToAddWords = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //Words words = new Words(); + //Word word0 = new Word(); + //word0.word = "bananna"; + //word0.translation = "bunanna"; + //Word word1 = new Word(); + //word1.word = "orange"; + //word1.translation = "arange"; + //Word word2 = new Word(); + //word2.word = "tomato"; + //word2.translation = "tomahto"; + //Word[] wordArray = { word0, word1, word2 }; + //words.words = wordArray; + //if (!m_TextToSpeech.AddCustomizationWords(OnAddCustomizationWords, customIdentifierToAddWords, words)) + // Log.Debug("ExampleTextToSpeech", "Failed to add words to {0}!", customIdentifierToAddWords); + + // Delete Customization Word + //Log.Debug("ExampleTextToSpeech", "Attempting to delete customization word from custom voice model."); + //string customIdentifierToDeleteWord = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //string wordToDelete = "goodbye"; + //if (!m_TextToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, customIdentifierToDeleteWord, wordToDelete)) + // Log.Debug("ExampleTextToSpeech", "Failed to delete {0} from {1}!", wordToDelete, customIdentifierToDeleteWord); + + // Get Customization Word + //Log.Debug("ExampleTextToSpeech", "Attempting to get the translation of a custom voice model's word."); + //string customIdentifierToGetWord = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //string customIdentifierWord = "hello"; + //if (!m_TextToSpeech.GetCustomizationWord(OnGetCustomizationWord, customIdentifierToGetWord, customIdentifierWord)) + // Log.Debug("ExampleTextToSpeech", "Failed to get the translation of {0} from {1}!", customIdentifierWord, customIdentifierToGetWord); + + // Add Customization Word - This is not working. The PUT method is not supported by Unity. + //Log.Debug("ExampleTextToSpeech", "Attempting to add a single word and translation to a custom voice model."); + //string customIdentifierToAddWordAndTranslation = "1476ea80-5355-4911-ac99-ba39162a2d34"; + //string word = "grasshopper"; + //string translation = "guhrasshoppe"; + //if (!m_TextToSpeech.AddCustomizationWord(OnAddCustomizationWord, customIdentifierToAddWordAndTranslation, word, translation)) + // Log.Debug("ExampleTextToSpeech", "Failed to add {0}/{1} to {2}!", word, translation, customIdentifierToAddWordAndTranslation); + + + //m_TextToSpeech.Voice = VoiceType.en_US_Allison; + //m_TextToSpeech.ToSpeech(m_TestString, HandleToSpeechCallback, true); + + } + + void HandleToSpeechCallback(AudioClip clip) + { + PlayClip(clip); + } + + private void PlayClip(AudioClip clip) + { + if (Application.isPlaying && clip != null) + { + GameObject audioObject = new GameObject("AudioObject"); + AudioSource source = audioObject.AddComponent(); + source.spatialBlend = 0.0f; + source.loop = false; + source.clip = clip; + source.Play(); + + GameObject.Destroy(audioObject, clip.length); } - - void HandleToSpeechCallback (AudioClip clip) - { - PlayClip(clip); - } - - private void PlayClip(AudioClip clip) - { - if (Application.isPlaying && clip != null) - { - GameObject audioObject = new GameObject("AudioObject"); - AudioSource source = audioObject.AddComponent(); - source.spatialBlend = 0.0f; - source.loop = false; - source.clip = clip; - source.Play(); - - GameObject.Destroy(audioObject, clip.length); - } - } - - private void OnGetVoices(Voices voices) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetVoices-----"); - foreach (Voice voice in voices.voices) - Log.Debug("ExampleTextToSpeech", "Voice | name: {0} | gender: {1} | language: {2} | customizable: {3} | description: {4}.", voice.name, voice.gender, voice.language, voice.customizable, voice.description); - Log.Debug("ExampleTextToSpeech", "-----OnGetVoices-----"); - } - - private void OnGetVoice(Voice voice) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetVoice-----"); - Log.Debug("ExampleTextToSpeech", "Voice | name: {0} | gender: {1} | language: {2} | customizable: {3} | description: {4}", voice.name, voice.gender, voice.language, voice.customizable, voice.description); - Log.Debug("ExampleTextToSpeech", "-----OnGetVoice-----"); - } - - private void OnGetPronunciation(Pronunciation pronunciation) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetPronunciation-----"); - Log.Debug("ExampleTextToSpeech", "Pronunciation: {0}.", pronunciation.pronunciation); - Log.Debug("ExampleTextToSpeech", "-----OnGetPronunciation-----"); - } - - private void OnGetCustomizations(Customizations customizations, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizations-----"); - if(data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - foreach (Customization customization in customizations.customizations) - Log.Debug("ExampleTextToSpeech", "Customization: name: {0} | customization_id: {1} | language: {2} | description: {3} | owner: {4} | created: {5} | last modified: {6}", customization.name, customization.customization_id, customization.language, customization.description, customization.owner, customization.created, customization.last_modified); - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizations-----"); - } - - private void OnCreateCustomization(CustomizationID customizationID, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnCreateCustomization-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "CustomizationID: id: {0}.", customizationID.customization_id); - Log.Debug("ExampleTextToSpeech", "-----OnCreateCustomization-----"); - } - - private void OnDeleteCustomization(bool success, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomization-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); - Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomization-----"); - } - - private void OnGetCustomization(Customization customization, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomization-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Customization: name: {0} | customization_id: {1} | language: {2} | description: {3} | owner: {4} | created: {5} | last modified: {6}", customization.name, customization.customization_id, customization.language, customization.description, customization.owner, customization.created, customization.last_modified); - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomization-----"); - } - - private void OnUpdateCustomization(bool success, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnUpdateCustomization-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); - Log.Debug("ExampleTextToSpeech", "-----OnUpdateCustomization-----"); - } - - private void OnGetCustomizationWords(Words words, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWords-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - foreach (Word word in words.words) - Log.Debug("ExampleTextToSpeech", "Word: {0} | Translation: {1}.", word.word, word.translation); - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWords-----"); - } - - private void OnAddCustomizationWords(bool success, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWords-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); - Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWords-----"); - } - - private void OnDeleteCustomizationWord(bool success, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomizationWord-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); - Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomizationWord-----"); - } - - private void OnGetCustomizationWord(Translation translation, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWord-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Translation: {0}.", translation.translation); - Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWord-----"); - } - - private void OnAddCustomizationWord(bool success, string data) - { - Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWord-----"); - if (data != default(string)) - Log.Debug("ExampleTextToSpeech", "data: {0}", data); - Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); - Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWord-----"); - } + } + + private void OnGetVoices(Voices voices) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetVoices-----"); + foreach (Voice voice in voices.voices) + Log.Debug("ExampleTextToSpeech", "Voice | name: {0} | gender: {1} | language: {2} | customizable: {3} | description: {4}.", voice.name, voice.gender, voice.language, voice.customizable, voice.description); + Log.Debug("ExampleTextToSpeech", "-----OnGetVoices-----"); + } + + private void OnGetVoice(Voice voice) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetVoice-----"); + Log.Debug("ExampleTextToSpeech", "Voice | name: {0} | gender: {1} | language: {2} | customizable: {3} | description: {4}", voice.name, voice.gender, voice.language, voice.customizable, voice.description); + Log.Debug("ExampleTextToSpeech", "-----OnGetVoice-----"); + } + + private void OnGetPronunciation(Pronunciation pronunciation) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetPronunciation-----"); + Log.Debug("ExampleTextToSpeech", "Pronunciation: {0}.", pronunciation.pronunciation); + Log.Debug("ExampleTextToSpeech", "-----OnGetPronunciation-----"); + } + + private void OnGetCustomizations(Customizations customizations, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizations-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + foreach (Customization customization in customizations.customizations) + Log.Debug("ExampleTextToSpeech", "Customization: name: {0} | customization_id: {1} | language: {2} | description: {3} | owner: {4} | created: {5} | last modified: {6}", customization.name, customization.customization_id, customization.language, customization.description, customization.owner, customization.created, customization.last_modified); + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizations-----"); + } + + private void OnCreateCustomization(CustomizationID customizationID, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnCreateCustomization-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "CustomizationID: id: {0}.", customizationID.customization_id); + Log.Debug("ExampleTextToSpeech", "-----OnCreateCustomization-----"); + } + + private void OnDeleteCustomization(bool success, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomization-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); + Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomization-----"); + } + + private void OnGetCustomization(Customization customization, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomization-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Customization: name: {0} | customization_id: {1} | language: {2} | description: {3} | owner: {4} | created: {5} | last modified: {6}", customization.name, customization.customization_id, customization.language, customization.description, customization.owner, customization.created, customization.last_modified); + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomization-----"); + } + + private void OnUpdateCustomization(bool success, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnUpdateCustomization-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); + Log.Debug("ExampleTextToSpeech", "-----OnUpdateCustomization-----"); + } + + private void OnGetCustomizationWords(Words words, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWords-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + foreach (Word word in words.words) + Log.Debug("ExampleTextToSpeech", "Word: {0} | Translation: {1}.", word.word, word.translation); + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWords-----"); + } + + private void OnAddCustomizationWords(bool success, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWords-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); + Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWords-----"); + } + + private void OnDeleteCustomizationWord(bool success, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomizationWord-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); + Log.Debug("ExampleTextToSpeech", "-----OnDeleteCustomizationWord-----"); + } + + private void OnGetCustomizationWord(Translation translation, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWord-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Translation: {0}.", translation.translation); + Log.Debug("ExampleTextToSpeech", "-----OnGetCustomizationWord-----"); + } + + private void OnAddCustomizationWord(bool success, string data) + { + Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWord-----"); + if (data != default(string)) + Log.Debug("ExampleTextToSpeech", "data: {0}", data); + Log.Debug("ExampleTextToSpeech", "Success: {0}.", success); + Log.Debug("ExampleTextToSpeech", "-----OnAddCustomizationWord-----"); + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleToneAnalyzer.cs b/Examples/ServiceExamples/Scripts/ExampleToneAnalyzer.cs old mode 100644 new mode 100755 index 1bf2c5c2c..f155b835d --- a/Examples/ServiceExamples/Scripts/ExampleToneAnalyzer.cs +++ b/Examples/ServiceExamples/Scripts/ExampleToneAnalyzer.cs @@ -19,16 +19,18 @@ using System.Collections; using IBM.Watson.DeveloperCloud.Services.ToneAnalyzer.v3; -public class ExampleToneAnalyzer : MonoBehaviour { - ToneAnalyzer m_ToneAnalyzer = new ToneAnalyzer(); - string m_StringToTestTone = "This service enables people to discover and understand, and revise the impact of tone in their content. It uses linguistic analysis to detect and interpret emotional, social, and language cues found in text."; +public class ExampleToneAnalyzer : MonoBehaviour +{ + ToneAnalyzer m_ToneAnalyzer = new ToneAnalyzer(); + string m_StringToTestTone = "This service enables people to discover and understand, and revise the impact of tone in their content. It uses linguistic analysis to detect and interpret emotional, social, and language cues found in text."; - void Start () { - m_ToneAnalyzer.GetToneAnalyze( OnGetToneAnalyze, m_StringToTestTone, "TEST"); - } - - private void OnGetToneAnalyze( ToneAnalyzerResponse resp , string data) - { - Debug.Log("Response: " +resp + " - " + data); - } + void Start() + { + m_ToneAnalyzer.GetToneAnalyze(OnGetToneAnalyze, m_StringToTestTone, "TEST"); + } + + private void OnGetToneAnalyze(ToneAnalyzerResponse resp, string data) + { + Debug.Log("Response: " + resp + " - " + data); + } } diff --git a/Examples/ServiceExamples/Scripts/ExampleTradeoffAnalytics.cs b/Examples/ServiceExamples/Scripts/ExampleTradeoffAnalytics.cs old mode 100644 new mode 100755 index 335af4aa0..0ca8b04e5 --- a/Examples/ServiceExamples/Scripts/ExampleTradeoffAnalytics.cs +++ b/Examples/ServiceExamples/Scripts/ExampleTradeoffAnalytics.cs @@ -20,107 +20,109 @@ using System.Collections.Generic; using IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1; -public class ExampleTradeoffAnalytics : MonoBehaviour { - TradeoffAnalytics m_TradeoffAnalytics = new TradeoffAnalytics(); - - void Start () { - Problem problemToSolve = new Problem(); - problemToSolve.subject = "Test Subject"; - - List listColumn = new List(); - Column columnPrice = new Column(); - columnPrice.description = "Price Column to minimize"; - columnPrice.range = new ValueRange(); - ((ValueRange)columnPrice.range).high = 600; - ((ValueRange)columnPrice.range).low = 0; - columnPrice.type = "numeric"; - columnPrice.key = "price"; - columnPrice.full_name = "Price"; - columnPrice.goal = "min"; - columnPrice.is_objective = true; - columnPrice.format = "$####0.00"; - - Column columnWeight = new Column(); - columnWeight.description = "Weight Column to minimize"; - columnWeight.type = "numeric"; - columnWeight.key = "weight"; - columnWeight.full_name = "Weight"; - columnWeight.goal = "min"; - columnWeight.is_objective = true; - columnWeight.format = "####0 g"; - - Column columnBrandName = new Column(); - columnBrandName.description = "All Brand Names"; - columnBrandName.type = "categorical"; - columnBrandName.key = "brand"; - columnBrandName.full_name = "Brand"; - columnBrandName.goal = "max"; - columnBrandName.is_objective = true; - columnBrandName.preference = new string[]{"Samsung", "Apple", "HTC"}; - columnBrandName.range = new CategoricalRange(); - ((CategoricalRange)columnBrandName.range).keys = new string[]{"Samsung", "Apple", "HTC"}; - - listColumn.Add(columnPrice); - listColumn.Add(columnWeight); - // listColumn.Add(columnBrandName); - - problemToSolve.columns = listColumn.ToArray(); - - - List public class WebCamRecognition : MonoBehaviour { - #region Private Data - [SerializeField] - private WebCamWidget m_WebCamWidget; - [SerializeField] - private WebCamDisplayWidget m_WebCamDisplayWidget; + #region Private Data + [SerializeField] + private WebCamWidget m_WebCamWidget; + [SerializeField] + private WebCamDisplayWidget m_WebCamDisplayWidget; - VisualRecognition m_VisualRecognition; - #endregion + VisualRecognition m_VisualRecognition; + #endregion + + void Start() + { + m_VisualRecognition = new VisualRecognition(); + } + + #region Public Functions + public void SaveFile() + { + Log.Debug("WebCamRecognition", "Attempting to save file!"); + Runnable.Run(SaveImageFile()); + } + + public void SaveFile(string filePath = default(string), string fileName = default(string)) + { + Log.Debug("WebCamRecognition", "Attempting to save file!"); + Runnable.Run(SaveImageFile(filePath, fileName)); + } + + public void Classify() + { + Log.Debug("WebCamRecognition", "Attempting to classify image!"); + Runnable.Run(ClassifyImage()); + } + + public void DetectFaces() + { + Log.Debug("WebCamRecognition", "Attempting to detect faces!"); + Runnable.Run(DetectFacesInImage()); + } + + public void RecognizeText() + { + Log.Debug("WebCamRecognition", "Attempting to recognize text!"); + Runnable.Run(RecognizeTextInImage()); + } + #endregion + + + #region Private Functions + private IEnumerator SaveImageFile(string filePath = default(string), string fileName = default(string)) + { + yield return new WaitForEndOfFrame(); + + if (filePath == default(string)) + filePath = Application.dataPath + "/../"; + if (fileName == default(string)) + fileName = "WebCamImage.png"; + Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); + image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); + image.Apply(); + + File.WriteAllBytes(filePath + fileName, image.EncodeToPNG()); + + Log.Debug("WebCamRecognition", "File writeen to {0}{1}", filePath, fileName); + } + + private IEnumerator ClassifyImage() + { + yield return new WaitForEndOfFrame(); + + //Color32[] colors = m_WebCamWidget.WebCamTexture.GetPixels32(); + //byte[] rawImageData = Utility.Color32ArrayToByteArray(colors); + + Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); + image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); + + byte[] imageData = image.EncodeToPNG(); + + m_VisualRecognition.Classify(OnClassify, imageData); + } + + private IEnumerator DetectFacesInImage() + { + yield return new WaitForEndOfFrame(); + + Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); + image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); + + byte[] imageData = image.EncodeToPNG(); + + m_VisualRecognition.DetectFaces(OnDetectFaces, imageData); + } + + private IEnumerator RecognizeTextInImage() + { + yield return new WaitForEndOfFrame(); + + Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); + image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); + + byte[] imageData = image.EncodeToPNG(); + + m_VisualRecognition.RecognizeText(OnRecognizeText, imageData); + } + #endregion - void Start() + #region Event Handlers + private void OnClassify(ClassifyTopLevelMultiple classify, string data) + { + if (classify != null) { - m_VisualRecognition = new VisualRecognition(); - } - - #region Public Functions - public void SaveFile() - { - Log.Debug("WebCamRecognition", "Attempting to save file!"); - Runnable.Run(SaveImageFile()); - } - - public void SaveFile(string filePath = default(string), string fileName = default(string)) - { - Log.Debug("WebCamRecognition", "Attempting to save file!"); - Runnable.Run(SaveImageFile(filePath, fileName)); - } - - public void Classify() - { - Log.Debug("WebCamRecognition", "Attempting to classify image!"); - Runnable.Run(ClassifyImage()); - } - - public void DetectFaces() - { - Log.Debug("WebCamRecognition", "Attempting to detect faces!"); - Runnable.Run(DetectFacesInImage()); - } - - public void RecognizeText() - { - Log.Debug("WebCamRecognition", "Attempting to recognize text!"); - Runnable.Run(RecognizeTextInImage()); - } - #endregion - - - #region Private Functions - private IEnumerator SaveImageFile(string filePath = default(string), string fileName = default(string)) - { - yield return new WaitForEndOfFrame(); - - if (filePath == default(string)) - filePath = Application.dataPath + "/../"; - if (fileName == default(string)) - fileName = "WebCamImage.png"; - Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); - image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); - image.Apply(); - - File.WriteAllBytes(filePath + fileName, image.EncodeToPNG()); - - Log.Debug("WebCamRecognition", "File writeen to {0}{1}", filePath, fileName); - } - - private IEnumerator ClassifyImage() - { - yield return new WaitForEndOfFrame(); - - //Color32[] colors = m_WebCamWidget.WebCamTexture.GetPixels32(); - //byte[] rawImageData = Utility.Color32ArrayToByteArray(colors); - - Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); - image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); - - byte[] imageData = image.EncodeToPNG(); - - m_VisualRecognition.Classify(OnClassify, imageData); - } - - private IEnumerator DetectFacesInImage() - { - yield return new WaitForEndOfFrame(); - - Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); - image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); - - byte[] imageData = image.EncodeToPNG(); - - m_VisualRecognition.DetectFaces(OnDetectFaces, imageData); + Log.Debug("WebCamRecognition", "images processed: " + classify.images_processed); + foreach (ClassifyTopLevelSingle image in classify.images) + { + Log.Debug("WebCamRecognition", "\tsource_url: " + image.source_url + ", resolved_url: " + image.resolved_url); + foreach (ClassifyPerClassifier classifier in image.classifiers) + { + Log.Debug("WebCamRecognition", "\t\tclassifier_id: " + classifier.classifier_id + ", name: " + classifier.name); + foreach (ClassResult classResult in classifier.classes) + Log.Debug("WebCamRecognition", "\t\t\tclass: " + classResult.m_class + ", score: " + classResult.score + ", type_hierarchy: " + classResult.type_hierarchy); + } + } } - - private IEnumerator RecognizeTextInImage() + else { - yield return new WaitForEndOfFrame(); - - Texture2D image = new Texture2D(m_WebCamWidget.WebCamTexture.width, m_WebCamWidget.WebCamTexture.height, TextureFormat.RGB24, false); - image.SetPixels32(m_WebCamWidget.WebCamTexture.GetPixels32()); - - byte[] imageData = image.EncodeToPNG(); - - m_VisualRecognition.RecognizeText(OnRecognizeText, imageData); + Log.Debug("WebCamRecognition", "Classification failed!"); } - #endregion + } - #region Event Handlers - private void OnClassify(ClassifyTopLevelMultiple classify, string data) + private void OnDetectFaces(FacesTopLevelMultiple multipleImages, string data) + { + if (multipleImages != null) { - if (classify != null) - { - Log.Debug("WebCamRecognition", "images processed: " + classify.images_processed); - foreach (ClassifyTopLevelSingle image in classify.images) - { - Log.Debug("WebCamRecognition", "\tsource_url: " + image.source_url + ", resolved_url: " + image.resolved_url); - foreach (ClassifyPerClassifier classifier in image.classifiers) - { - Log.Debug("WebCamRecognition", "\t\tclassifier_id: " + classifier.classifier_id + ", name: " + classifier.name); - foreach (ClassResult classResult in classifier.classes) - Log.Debug("WebCamRecognition", "\t\t\tclass: " + classResult.m_class + ", score: " + classResult.score + ", type_hierarchy: " + classResult.type_hierarchy); - } - } - } - else + Log.Debug("WebCamRecognition", "images processed: {0}", multipleImages.images_processed); + foreach (FacesTopLevelSingle faces in multipleImages.images) + { + Log.Debug("WebCamRecognition", "\tsource_url: {0}, resolved_url: {1}", faces.source_url, faces.resolved_url); + foreach (OneFaceResult face in faces.faces) { - Log.Debug("WebCamRecognition", "Classification failed!"); + if (face.face_location != null) + Log.Debug("WebCamRecognition", "\t\tFace location: {0}, {1}, {2}, {3}", face.face_location.left, face.face_location.top, face.face_location.width, face.face_location.height); + if (face.gender != null) + Log.Debug("WebCamRecognition", "\t\tGender: {0}, Score: {1}", face.gender.gender, face.gender.score); + if (face.age != null) + Log.Debug("WebCamRecognition", "\t\tAge Min: {0}, Age Max: {1}, Score: {2}", face.age.min, face.age.max, face.age.score); + + if (face.identity != null) + Log.Debug("WebCamRecognition", "\t\tName: {0}, Score: {1}, Type Heiarchy: {2}", face.identity.name, face.identity.score, face.identity.type_hierarchy); } + } } - - private void OnDetectFaces(FacesTopLevelMultiple multipleImages, string data) + else { - if (multipleImages != null) - { - Log.Debug("WebCamRecognition", "images processed: {0}", multipleImages.images_processed); - foreach (FacesTopLevelSingle faces in multipleImages.images) - { - Log.Debug("WebCamRecognition", "\tsource_url: {0}, resolved_url: {1}", faces.source_url, faces.resolved_url); - foreach (OneFaceResult face in faces.faces) - { - if(face.face_location != null) - Log.Debug("WebCamRecognition", "\t\tFace location: {0}, {1}, {2}, {3}", face.face_location.left, face.face_location.top, face.face_location.width, face.face_location.height); - if(face.gender != null) - Log.Debug("WebCamRecognition", "\t\tGender: {0}, Score: {1}", face.gender.gender, face.gender.score); - if(face.age != null) - Log.Debug("WebCamRecognition", "\t\tAge Min: {0}, Age Max: {1}, Score: {2}", face.age.min, face.age.max, face.age.score); - - if(face.identity != null) - Log.Debug("WebCamRecognition", "\t\tName: {0}, Score: {1}, Type Heiarchy: {2}", face.identity.name, face.identity.score, face.identity.type_hierarchy); - } - } - } - else - { - Log.Debug("WebCamRecognition", "Detect faces failed!"); - } + Log.Debug("WebCamRecognition", "Detect faces failed!"); } + } - private void OnRecognizeText(TextRecogTopLevelMultiple multipleImages, string data) + private void OnRecognizeText(TextRecogTopLevelMultiple multipleImages, string data) + { + if (multipleImages != null) { - if (multipleImages != null) - { - Log.Debug("WebCamRecognition", "images processed: {0}", multipleImages.images_processed); - foreach (TextRecogTopLevelSingle texts in multipleImages.images) - { - Log.Debug("WebCamRecognition", "\tsource_url: {0}, resolved_url: {1}", texts.source_url, texts.resolved_url); - Log.Debug("WebCamRecognition", "\ttext: {0}", texts.text); - foreach (TextRecogOneWord text in texts.words) - { - Log.Debug("WebCamRecognition", "\t\ttext location: {0}, {1}, {2}, {3}", text.location.left, text.location.top, text.location.width, text.location.height); - Log.Debug("WebCamRecognition", "\t\tLine number: {0}", text.line_number); - Log.Debug("WebCamRecognition", "\t\tword: {0}, Score: {1}", text.word, text.score); - } - } - } - else + Log.Debug("WebCamRecognition", "images processed: {0}", multipleImages.images_processed); + foreach (TextRecogTopLevelSingle texts in multipleImages.images) + { + Log.Debug("WebCamRecognition", "\tsource_url: {0}, resolved_url: {1}", texts.source_url, texts.resolved_url); + Log.Debug("WebCamRecognition", "\ttext: {0}", texts.text); + foreach (TextRecogOneWord text in texts.words) { - Log.Debug("WebCamRecognition", "RecognizeText failed!"); + Log.Debug("WebCamRecognition", "\t\ttext location: {0}, {1}, {2}, {3}", text.location.left, text.location.top, text.location.width, text.location.height); + Log.Debug("WebCamRecognition", "\t\tLine number: {0}", text.line_number); + Log.Debug("WebCamRecognition", "\t\tword: {0}, Score: {1}", text.word, text.score); } + } + } + else + { + Log.Debug("WebCamRecognition", "RecognizeText failed!"); } - #endregion + } + #endregion } diff --git a/Scenes/UnitTests/Scripts/ConfigLoader.cs b/Scenes/UnitTests/Scripts/ConfigLoader.cs old mode 100644 new mode 100755 index fefff982e..acfa6bf83 --- a/Scenes/UnitTests/Scripts/ConfigLoader.cs +++ b/Scenes/UnitTests/Scripts/ConfigLoader.cs @@ -1,51 +1,68 @@ -using UnityEngine; +/** +* Copyright 2015 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 UnityEngine; using System.Collections; using IBM.Watson.DeveloperCloud.Utilities; //! This helper class makes sure the Watson configuration is fully loaded before we try to access any of the services. public class ConfigLoader : MonoBehaviour { - [SerializeField] - private GameObject m_Prefab = null; - private GameObject m_CreatedObject = null; + [SerializeField] + private GameObject m_Prefab = null; + private GameObject m_CreatedObject = null; - #region OnEnable / OnDisable - Registering events - void OnEnable() - { - EventManager.Instance.RegisterEventReceiver("OnUserToLogout", OnUserLogOut); - } + #region OnEnable / OnDisable - Registering events + void OnEnable() + { + EventManager.Instance.RegisterEventReceiver("OnUserToLogout", OnUserLogOut); + } - void OnDisable() - { - EventManager.Instance.UnregisterEventReceiver("OnUserToLogout", OnUserLogOut); - } - #endregion + void OnDisable() + { + EventManager.Instance.UnregisterEventReceiver("OnUserToLogout", OnUserLogOut); + } + #endregion - IEnumerator Start() - { - // wait for the configuration to be loaded first.. - while (!Config.Instance.ConfigLoaded) - yield return null; + IEnumerator Start() + { + // wait for the configuration to be loaded first.. + while (!Config.Instance.ConfigLoaded) + yield return null; - // then initiate a prefab after we are done loading the config. - m_CreatedObject = GameObject.Instantiate(m_Prefab); - } + // then initiate a prefab after we are done loading the config. + m_CreatedObject = GameObject.Instantiate(m_Prefab); + } - /// - /// Handler for user logout - /// - /// - public void OnUserLogOut(System.Object[] args) + /// + /// Handler for user logout + /// + /// + public void OnUserLogOut(System.Object[] args) + { + if (m_CreatedObject != null) { - if (m_CreatedObject != null) - { - if (!m_CreatedObject.activeSelf) - m_CreatedObject.SetActive(true); - - m_CreatedObject.SendMessage("DestroyCreatedObject", SendMessageOptions.DontRequireReceiver); - } - StartCoroutine(Start()); + if (!m_CreatedObject.activeSelf) + m_CreatedObject.SetActive(true); + + m_CreatedObject.SendMessage("DestroyCreatedObject", SendMessageOptions.DontRequireReceiver); } + StartCoroutine(Start()); + } } diff --git a/Scenes/UnitTests/Scripts/LogSystemInitilization.cs b/Scenes/UnitTests/Scripts/LogSystemInitilization.cs old mode 100644 new mode 100755 index c1921a2fa..196fa265b --- a/Scenes/UnitTests/Scripts/LogSystemInitilization.cs +++ b/Scenes/UnitTests/Scripts/LogSystemInitilization.cs @@ -19,27 +19,27 @@ namespace IBM.Watson.DeveloperCloud.Logging { + /// + /// Helper class to install default Log Reactor on Awawke + /// + public class LogSystemInitilization : MonoBehaviour + { + /// - /// Helper class to install default Log Reactor on Awawke + /// Days of Log store on file system /// - public class LogSystemInitilization : MonoBehaviour - { - - /// - /// Days of Log store on file system - /// - [SerializeField] - private int m_LogHistory = 2; + [SerializeField] + private int m_LogHistory = 2; - /// - /// Log level definition to store on file. - /// - [SerializeField] - private LogLevel m_LogLevelOnFile = LogLevel.STATUS; + /// + /// Log level definition to store on file. + /// + [SerializeField] + private LogLevel m_LogLevelOnFile = LogLevel.STATUS; - void Awake() - { - LogSystem.InstallDefaultReactors(m_LogHistory, m_LogLevelOnFile); - } + void Awake() + { + LogSystem.InstallDefaultReactors(m_LogHistory, m_LogLevelOnFile); } + } } \ No newline at end of file diff --git a/Scenes/UnitTests/Scripts/MainUI.cs b/Scenes/UnitTests/Scripts/MainUI.cs old mode 100644 new mode 100755 index d9d22a8a5..483713814 --- a/Scenes/UnitTests/Scripts/MainUI.cs +++ b/Scenes/UnitTests/Scripts/MainUI.cs @@ -15,7 +15,6 @@ * */ - using IBM.Watson.DeveloperCloud.Logging; using IBM.Watson.DeveloperCloud.Utilities; using System.Collections; @@ -32,26 +31,26 @@ [System.Serializable] public class MenuScene { - /// - /// The name of the scene. - /// - public string m_SceneName; - /// - /// the description of the scene. - /// - public string m_SceneDesc; - /// - /// Back button position for this scene. - /// - public Vector3 m_CustomBackButtonPosition = Vector3.zero; - /// - /// Back button scale for this scene. - /// - public Vector2 m_CustomBackButtonScale = Vector2.zero; - /// - /// Is the back button visible. - /// - public bool m_IsVisibleBackButton = true; + /// + /// The name of the scene. + /// + public string m_SceneName; + /// + /// the description of the scene. + /// + public string m_SceneDesc; + /// + /// Back button position for this scene. + /// + public Vector3 m_CustomBackButtonPosition = Vector3.zero; + /// + /// Back button scale for this scene. + /// + public Vector2 m_CustomBackButtonScale = Vector2.zero; + /// + /// Is the back button visible. + /// + public bool m_IsVisibleBackButton = true; } /// @@ -59,246 +58,246 @@ public class MenuScene /// public class MainUI : MonoBehaviour { - [SerializeField] - private LayoutGroup m_ButtonLayout = null; - [SerializeField] - private Button m_ButtonPrefab = null; - [SerializeField] - private GameObject m_BackgroundUI = null; - [SerializeField] - private RectTransform m_ButtonBack = null; - private Vector3 m_InitialBackButtonPosition; - private Vector3 m_InitialBackButtonScale; - private Color m_InitialBackButtonColor; - - [SerializeField] - private MenuScene[] m_Scenes = null; - - private const string MAIN_SCENE = "Main"; + [SerializeField] + private LayoutGroup m_ButtonLayout = null; + [SerializeField] + private Button m_ButtonPrefab = null; + [SerializeField] + private GameObject m_BackgroundUI = null; + [SerializeField] + private RectTransform m_ButtonBack = null; + private Vector3 m_InitialBackButtonPosition; + private Vector3 m_InitialBackButtonScale; + private Color m_InitialBackButtonColor; + + [SerializeField] + private MenuScene[] m_Scenes = null; + + private const string MAIN_SCENE = "Main"; #if UNITY_EDITOR - [UnityEditor.MenuItem("CONTEXT/MainUI/Update Scene Names")] - private static void UpdateNames(UnityEditor.MenuCommand command) + [UnityEditor.MenuItem("CONTEXT/MainUI/Update Scene Names")] + private static void UpdateNames(UnityEditor.MenuCommand command) + { + MainUI context = (MainUI)command.context; + List scenes = new List(); + foreach (UnityEditor.EditorBuildSettingsScene scene in UnityEditor.EditorBuildSettings.scenes) { - MainUI context = (MainUI)command.context; - List scenes = new List(); - foreach (UnityEditor.EditorBuildSettingsScene scene in UnityEditor.EditorBuildSettings.scenes) - { - if (scene == null || !scene.enabled) - continue; + if (scene == null || !scene.enabled) + continue; - string name = Path.GetFileNameWithoutExtension(scene.path); - if (name == MAIN_SCENE) - continue; + string name = Path.GetFileNameWithoutExtension(scene.path); + if (name == MAIN_SCENE) + continue; - scenes.Add(name); - } - scenes.Sort(); - context.m_Scenes = new MenuScene[scenes.Count]; - for (int i = 0; i < scenes.Count; i++) - { - context.m_Scenes[i] = new MenuScene(); - context.m_Scenes[i].m_SceneName = scenes[i]; - context.m_Scenes[i].m_SceneDesc = scenes[i]; - } + scenes.Add(name); } -#endif - - private IEnumerator Start() + scenes.Sort(); + context.m_Scenes = new MenuScene[scenes.Count]; + for (int i = 0; i < scenes.Count; i++) { - if (m_BackgroundUI == null) - throw new WatsonException("m_BackgroundUI is null."); - if (m_ButtonLayout == null) - throw new WatsonException("m_ButtonLayout is null."); - if (m_ButtonPrefab == null) - throw new WatsonException("m_ButtonPrefab is null."); - if (m_ButtonBack == null) - throw new WatsonException("m_ButtonBack is null."); - else - { - if (m_ButtonBack.GetComponent() != null) - { - m_InitialBackButtonPosition = m_ButtonBack.GetComponent().anchoredPosition3D; - m_InitialBackButtonScale = m_ButtonBack.GetComponent().sizeDelta; - } - else - { - throw new WatsonException("m_ButtonBack doesn't have RectTransform"); - } - - if (m_ButtonBack.GetComponent() != null) - { - m_InitialBackButtonColor = m_ButtonBack.GetComponentInChildren().color; - } - else - { - throw new WatsonException("m_ButtonBack doesn't have Image"); - } - - } - // wait for the configuration to be loaded first.. - while (!Config.Instance.ConfigLoaded) - yield return null; - - // create the buttons.. - UpdateButtons(); + context.m_Scenes[i] = new MenuScene(); + context.m_Scenes[i].m_SceneName = scenes[i]; + context.m_Scenes[i].m_SceneDesc = scenes[i]; } + } +#endif - private void OnLevelWasLoaded(int level) + private IEnumerator Start() + { + if (m_BackgroundUI == null) + throw new WatsonException("m_BackgroundUI is null."); + if (m_ButtonLayout == null) + throw new WatsonException("m_ButtonLayout is null."); + if (m_ButtonPrefab == null) + throw new WatsonException("m_ButtonPrefab is null."); + if (m_ButtonBack == null) + throw new WatsonException("m_ButtonBack is null."); + else { - UpdateButtons(); - } + if (m_ButtonBack.GetComponent() != null) + { + m_InitialBackButtonPosition = m_ButtonBack.GetComponent().anchoredPosition3D; + m_InitialBackButtonScale = m_ButtonBack.GetComponent().sizeDelta; + } + else + { + throw new WatsonException("m_ButtonBack doesn't have RectTransform"); + } + + if (m_ButtonBack.GetComponent() != null) + { + m_InitialBackButtonColor = m_ButtonBack.GetComponentInChildren().color; + } + else + { + throw new WatsonException("m_ButtonBack doesn't have Image"); + } - private void UpdateButtons() + } + // wait for the configuration to be loaded first.. + while (!Config.Instance.ConfigLoaded) + yield return null; + + // create the buttons.. + UpdateButtons(); + } + + private void OnLevelWasLoaded(int level) + { + UpdateButtons(); + } + + private void UpdateButtons() + { + while (m_ButtonLayout.transform.childCount > 0) + DestroyImmediate(m_ButtonLayout.transform.GetChild(0).gameObject); + + //Log.Debug( "MainUI", "UpdateBottons, level = {0}", Application.loadedLevelName ); + if (SceneManager.GetActiveScene().name == MAIN_SCENE) { - while (m_ButtonLayout.transform.childCount > 0) - DestroyImmediate(m_ButtonLayout.transform.GetChild(0).gameObject); - - //Log.Debug( "MainUI", "UpdateBottons, level = {0}", Application.loadedLevelName ); - if (SceneManager.GetActiveScene().name == MAIN_SCENE) - { - m_BackgroundUI.SetActive(true); + m_BackgroundUI.SetActive(true); - foreach (var scene in m_Scenes) - { - if (string.IsNullOrEmpty(scene.m_SceneName)) - continue; + foreach (var scene in m_Scenes) + { + if (string.IsNullOrEmpty(scene.m_SceneName)) + continue; - GameObject buttonObj = GameObject.Instantiate(m_ButtonPrefab.gameObject); - buttonObj.transform.SetParent(m_ButtonLayout.transform, false); + GameObject buttonObj = GameObject.Instantiate(m_ButtonPrefab.gameObject); + buttonObj.transform.SetParent(m_ButtonLayout.transform, false); - Text buttonText = buttonObj.GetComponentInChildren(); - if (buttonText != null) - buttonText.text = scene.m_SceneDesc; - Button button = buttonObj.GetComponentInChildren public static class RunUnitTest { - /// - /// Public functions invoked from the command line to run all UnitTest objects. - /// - static public void All() - { + /// + /// Public functions invoked from the command line to run all UnitTest objects. + /// + static public void All() + { #if UNITY_EDITOR - Runnable.EnableRunnableInEditor(); + Runnable.EnableRunnableInEditor(); #endif - string ProjectToTest = ""; - string[] args = Environment.GetCommandLineArgs(); - for (int i = 0; i < args.Length; ++i) + string ProjectToTest = ""; + string[] args = Environment.GetCommandLineArgs(); + for (int i = 0; i < args.Length; ++i) + { + if (args[i] == "-packageOptions" && (i + 1) < args.Length) + { + string[] options = args[i + 1].Split(','); + foreach (string option in options) { - if (args[i] == "-packageOptions" && (i + 1) < args.Length) - { - string[] options = args[i + 1].Split(','); - foreach (string option in options) - { - if (string.IsNullOrEmpty(option)) - continue; + if (string.IsNullOrEmpty(option)) + continue; - string[] kv = option.Split('='); - if (kv[0] == "ProjectName") - { - ProjectToTest = kv.Length > 1 ? kv[1] : ""; - Log.Status("RunUnitTest", "AutoLunchOptions ProjectToTest:{0}", ProjectToTest); - break; - } - } - } + string[] kv = option.Split('='); + if (kv[0] == "ProjectName") + { + ProjectToTest = kv.Length > 1 ? kv[1] : ""; + Log.Status("RunUnitTest", "AutoLunchOptions ProjectToTest:{0}", ProjectToTest); + break; + } } - - IBM.Watson.DeveloperCloud.Editor.UnitTestManager.ProjectToTest = ProjectToTest; - IBM.Watson.DeveloperCloud.Editor.UnitTestManager instance = IBM.Watson.DeveloperCloud.Editor.UnitTestManager.Instance; - instance.QuitOnTestsComplete = true; - instance.OnTestCompleteCallback = OnTestsComplete; - instance.QueueTests(Utility.FindAllDerivedTypes(typeof(UnitTest)), true); + } } + IBM.Watson.DeveloperCloud.Editor.UnitTestManager.ProjectToTest = ProjectToTest; + IBM.Watson.DeveloperCloud.Editor.UnitTestManager instance = IBM.Watson.DeveloperCloud.Editor.UnitTestManager.Instance; + instance.QuitOnTestsComplete = true; + instance.OnTestCompleteCallback = OnTestsComplete; + instance.QueueTests(Utility.FindAllDerivedTypes(typeof(UnitTest)), true); + } + #if UNITY_EDITOR - /// - /// Menu item handler for running all unit tests. - /// - [MenuItem("Watson/Run All UnitTests",false, 50)] - static public void AllNoQuit() - { - Runnable.EnableRunnableInEditor(); + /// + /// Menu item handler for running all unit tests. + /// + [MenuItem("Watson/Run All UnitTests", false, 50)] + static public void AllNoQuit() + { + Runnable.EnableRunnableInEditor(); - IBM.Watson.DeveloperCloud.Editor.UnitTestManager.ProjectToTest = Config.Instance.GetVariableValue("PACKAGE_PREFIX"); - IBM.Watson.DeveloperCloud.Editor.UnitTestManager instance = IBM.Watson.DeveloperCloud.Editor.UnitTestManager.Instance; - instance.OnTestCompleteCallback = OnTestsComplete; - instance.QueueTests(Utility.FindAllDerivedTypes(typeof(UnitTest)), true); - } + IBM.Watson.DeveloperCloud.Editor.UnitTestManager.ProjectToTest = Config.Instance.GetVariableValue("PACKAGE_PREFIX"); + IBM.Watson.DeveloperCloud.Editor.UnitTestManager instance = IBM.Watson.DeveloperCloud.Editor.UnitTestManager.Instance; + instance.OnTestCompleteCallback = OnTestsComplete; + instance.QueueTests(Utility.FindAllDerivedTypes(typeof(UnitTest)), true); + } #endif - static void OnTestsComplete() - {} + static void OnTestsComplete() + { } } From 7d07646236d2bf1c5134e0a79b0d2750fc851e73 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Wed, 26 Oct 2016 11:55:53 -0500 Subject: [PATCH 22/28] format utils --- Scripts/Utilities/AudioClipUtil.cs | 148 +- Scripts/Utilities/Config.cs | 744 ++-- Scripts/Utilities/Constants.cs | 92 +- Scripts/Utilities/Credentials.cs | 84 +- Scripts/Utilities/DataCache.cs | 405 ++- Scripts/Utilities/EventManager.cs | 257 +- Scripts/Utilities/FrameRateCounter.cs | 56 +- Scripts/Utilities/KeyEventManager.cs | 284 +- Scripts/Utilities/NestedPrefabs.cs | 72 +- Scripts/Utilities/Runnable.cs | 248 +- Scripts/Utilities/SerializedDelegate.cs | 84 +- Scripts/Utilities/Singleton.cs | 94 +- Scripts/Utilities/TimedDestroy.cs | 174 +- Scripts/Utilities/TouchEventManager.cs | 4093 ++++++++++++----------- Scripts/Utilities/UnityObjectUtil.cs | 119 +- Scripts/Utilities/Utility.cs | 798 ++--- Scripts/Utilities/WatsonException.cs | 24 +- Scripts/Utilities/WaveFile.cs | 434 +-- 18 files changed, 4114 insertions(+), 4096 deletions(-) mode change 100644 => 100755 Scripts/Utilities/AudioClipUtil.cs mode change 100644 => 100755 Scripts/Utilities/Credentials.cs mode change 100644 => 100755 Scripts/Utilities/DataCache.cs mode change 100644 => 100755 Scripts/Utilities/EventManager.cs mode change 100644 => 100755 Scripts/Utilities/FrameRateCounter.cs mode change 100644 => 100755 Scripts/Utilities/KeyEventManager.cs mode change 100644 => 100755 Scripts/Utilities/NestedPrefabs.cs mode change 100644 => 100755 Scripts/Utilities/Runnable.cs mode change 100644 => 100755 Scripts/Utilities/SerializedDelegate.cs mode change 100644 => 100755 Scripts/Utilities/Singleton.cs mode change 100644 => 100755 Scripts/Utilities/TimedDestroy.cs mode change 100644 => 100755 Scripts/Utilities/TouchEventManager.cs mode change 100644 => 100755 Scripts/Utilities/UnityObjectUtil.cs mode change 100644 => 100755 Scripts/Utilities/WatsonException.cs mode change 100644 => 100755 Scripts/Utilities/WaveFile.cs diff --git a/Scripts/Utilities/AudioClipUtil.cs b/Scripts/Utilities/AudioClipUtil.cs old mode 100644 new mode 100755 index d4e6505bf..d5b85ab59 --- a/Scripts/Utilities/AudioClipUtil.cs +++ b/Scripts/Utilities/AudioClipUtil.cs @@ -17,95 +17,93 @@ using IBM.Watson.DeveloperCloud.Logging; using System; -using System.Collections; -using System.Collections.Generic; using System.IO; using UnityEngine; namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// AudioClip helper functions. + /// + public static class AudioClipUtil + { /// - /// AudioClip helper functions. + /// This function will combine any number of AudioClips into a single AudioClip. The clips must be the same number of channels + /// and frequency. /// - public static class AudioClipUtil + /// Variable number of AudioClip objects may be provided. + /// Returns the resulting AudioClip. + public static AudioClip Combine(params AudioClip[] clips) { - /// - /// This function will combine any number of AudioClips into a single AudioClip. The clips must be the same number of channels - /// and frequency. - /// - /// Variable number of AudioClip objects may be provided. - /// Returns the resulting AudioClip. - public static AudioClip Combine(params AudioClip[] clips) + if (clips == null || clips.Length == 0) + return null; + + AudioClip firstClip = null; + + int length = 0; + for (int i = 0; i < clips.Length; i++) + { + if (clips[i] == null) + continue; + + if (firstClip != null) { - if (clips == null || clips.Length == 0) - return null; - - AudioClip firstClip = null; - - int length = 0; - for (int i = 0; i < clips.Length; i++) - { - if (clips[i] == null) - continue; - - if (firstClip != null) - { - if (firstClip.channels != clips[i].channels - || firstClip.frequency != clips[i].frequency) - { - Log.Error("AudioClipUtil", "Combine() requires clips to have the sample number of channels and same frequency."); - return null; - } - } - else - firstClip = clips[i]; - - length += clips[i].samples * clips[i].channels; - } - - float[] data = new float[length]; - length = 0; - for (int i = 0; i < clips.Length; i++) - { - if (clips[i] == null) - continue; - - float[] buffer = new float[clips[i].samples * clips[i].channels]; - clips[i].GetData(buffer, 0); - buffer.CopyTo(data, length); - length += buffer.Length; - } - - if (length == 0) - return null; - - AudioClip result = AudioClip.Create(firstClip.name, length / firstClip.channels, firstClip.channels, firstClip.frequency, false); - result.SetData(data, 0); - - return result; + if (firstClip.channels != clips[i].channels + || firstClip.frequency != clips[i].frequency) + { + Log.Error("AudioClipUtil", "Combine() requires clips to have the sample number of channels and same frequency."); + return null; + } } + else + firstClip = clips[i]; - /// - /// Returns linear 16-bit audio data for the given AudioClip object. - /// - /// The AudioClip object. - /// A byte array of 16-bit audio data. - public static byte[] GetL16(AudioClip clip) - { - MemoryStream stream = new MemoryStream(); - BinaryWriter writer = new BinaryWriter(stream); + length += clips[i].samples * clips[i].channels; + } - float[] samples = new float[clip.samples * clip.channels]; - clip.GetData(samples, 0); + float[] data = new float[length]; + length = 0; + for (int i = 0; i < clips.Length; i++) + { + if (clips[i] == null) + continue; - float divisor = (1 << 15); - for (int i = 0; i < samples.Length; ++i) - writer.Write((short)(samples[i] * divisor)); + float[] buffer = new float[clips[i].samples * clips[i].channels]; + clips[i].GetData(buffer, 0); + buffer.CopyTo(data, length); + length += buffer.Length; + } - byte[] data = new byte[samples.Length * 2]; - Array.Copy(stream.GetBuffer(), data, data.Length); + if (length == 0) + return null; - return data; - } + AudioClip result = AudioClip.Create(firstClip.name, length / firstClip.channels, firstClip.channels, firstClip.frequency, false); + result.SetData(data, 0); + + return result; + } + + /// + /// Returns linear 16-bit audio data for the given AudioClip object. + /// + /// The AudioClip object. + /// A byte array of 16-bit audio data. + public static byte[] GetL16(AudioClip clip) + { + MemoryStream stream = new MemoryStream(); + BinaryWriter writer = new BinaryWriter(stream); + + float[] samples = new float[clip.samples * clip.channels]; + clip.GetData(samples, 0); + + float divisor = (1 << 15); + for (int i = 0; i < samples.Length; ++i) + writer.Write((short)(samples[i] * divisor)); + + byte[] data = new byte[samples.Length * 2]; + Array.Copy(stream.GetBuffer(), data, data.Length); + + return data; } + } } diff --git a/Scripts/Utilities/Config.cs b/Scripts/Utilities/Config.cs index b4f8db653..785609e05 100755 --- a/Scripts/Utilities/Config.cs +++ b/Scripts/Utilities/Config.cs @@ -26,408 +26,408 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// This class is used to hold configuration data for SDK. + /// + public class Config + { /// - /// This class is used to hold configuration data for SDK. + /// Serialized class for holding generic key/value pairs. /// - public class Config + [fsObject] + public class Variable { - /// - /// Serialized class for holding generic key/value pairs. - /// - [fsObject] - public class Variable - { - /// - /// The key name. - /// - public string Key { get; set; } - /// - /// The value referenced by the key. - /// - public string Value { get; set; } - }; - - /// - /// Serialized class for holding the user credentials for a service. - /// - [fsObject] - public class CredentialInfo - { - /// - /// The ID of the service this is the credentials. - /// - public string m_ServiceID; - /// - /// The URL for these credentials. - /// - public string m_URL; - /// - /// The user name for these credentials. - /// - public string m_User; - /// - /// The password for these credentials. - /// - public string m_Password; - /// - /// The API key for this service. - /// - public string m_Apikey; - /// - /// A note for the applied service. - /// - public string m_Note; - - /// - /// Generate JSON credentials. - /// - /// Returns a string of the JSON. - public string MakeJSON() - { - return "{\n\t\"credentials\": {\n\t\t\"url\": \"" + m_URL + "\",\n\t\t\"username\": \"" + m_User + "\",\n\t\t\"password\": \"" + m_Password + "\",\n\t\t\"apikey\": \"" + m_Apikey + "\",\n\t\t\"note\": \"" + m_Note + "\"\n\t}\n}"; - } - - /// - /// Parses a BlueMix json credentials into this object. - /// - /// The JSON data to parse. - /// Returns true on success. - public bool ParseJSON(string json) - { - try - { - IDictionary iParse = Json.Deserialize(json) as IDictionary; - IDictionary iCredentials = iParse["credentials"] as IDictionary; - m_URL = (string)iCredentials["url"]; - m_User = (string)iCredentials["username"]; - m_Password = (string)iCredentials["password"]; - m_Note = (string)iCredentials["note"]; - if(!string.IsNullOrEmpty((string)iCredentials["apikey"])) - m_Apikey = (string)iCredentials["apikey"]; - if(!string.IsNullOrEmpty((string)iCredentials["api_key"])) - m_Apikey = (string)iCredentials["api_key"]; - - return true; - } - catch (Exception e) - { - try - { - IDictionary iParse = Json.Deserialize(json) as IDictionary; - m_URL = (string)iParse["url"]; - m_User = (string)iParse["username"]; - m_Password = (string)iParse["password"]; - m_Note = (string)iParse["note"]; - if (!string.IsNullOrEmpty((string)iParse["apikey"])) - m_Apikey = (string)iParse["apikey"]; - if (!string.IsNullOrEmpty((string)iParse["api_key"])) - m_Apikey = (string)iParse["api_key"]; - - return true; - } - catch - { - Log.Error("Config", "Caught Exception: {0}", e.ToString()); - } - Log.Error("Config", "Caught Exception: {0}", e.ToString()); - } - - return false; - } - - /// - /// Determines whether this instance has credentials. - /// - /// true if this instance has credentials; otherwise, false. - public bool HasCredentials() - { - return (!string.IsNullOrEmpty(m_User) && !string.IsNullOrEmpty(m_Password)); - } - - /// - /// Determines whether this instance has API key. - /// - /// true if this instance has API key; otherwise, false. - public bool HasAPIKey() - { - return !string.IsNullOrEmpty(m_Apikey); - } - } + /// + /// The key name. + /// + public string Key { get; set; } + /// + /// The value referenced by the key. + /// + public string Value { get; set; } + }; - #region Private Data - [fsProperty] - private string m_ClassifierDirectory = "Watson/Scripts/Editor/Classifiers/"; - [fsProperty] - private float m_TimeOut = 30.0f; - [fsProperty] - private int m_MaxRestConnections = 5; - [fsProperty] - private List m_Credentials = new List(); - [fsProperty] - private List m_Variables = new List(); - - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Public Properties - /// - /// Returns true if the configuration is loaded or not. - /// - [fsIgnore] - public bool ConfigLoaded { get; set; } - /// - /// Returns the singleton instance. - /// - public static Config Instance { get { return Singleton.Instance; } } - /// - /// Returns the location of the classifiers - /// - public string ClassifierDirectory { get { return m_ClassifierDirectory; } set { m_ClassifierDirectory = value; } } - /// - /// Returns the Timeout for requests made to the server. - /// - public float TimeOut { get { return m_TimeOut; } set { m_TimeOut = value; } } - /// - /// Maximum number of connections Watson will make to the server back-end at any one time. - /// - public int MaxRestConnections { get { return m_MaxRestConnections; } set { m_MaxRestConnections = value; } } - /// - /// Returns the list of credentials used to login to the various services. - /// - public List Credentials { get { return m_Credentials; } set { m_Credentials = value; } } - /// - /// Returns a list of variables which can hold key/value data. - /// - public List Variables { get { return m_Variables; } set { m_Variables = value; } } - #endregion - - /// - /// Default constructor will call LoadConfig() automatically. - /// - public Config() + /// + /// Serialized class for holding the user credentials for a service. + /// + [fsObject] + public class CredentialInfo + { + /// + /// The ID of the service this is the credentials. + /// + public string m_ServiceID; + /// + /// The URL for these credentials. + /// + public string m_URL; + /// + /// The user name for these credentials. + /// + public string m_User; + /// + /// The password for these credentials. + /// + public string m_Password; + /// + /// The API key for this service. + /// + public string m_Apikey; + /// + /// A note for the applied service. + /// + public string m_Note; + + /// + /// Generate JSON credentials. + /// + /// Returns a string of the JSON. + public string MakeJSON() + { + return "{\n\t\"credentials\": {\n\t\t\"url\": \"" + m_URL + "\",\n\t\t\"username\": \"" + m_User + "\",\n\t\t\"password\": \"" + m_Password + "\",\n\t\t\"apikey\": \"" + m_Apikey + "\",\n\t\t\"note\": \"" + m_Note + "\"\n\t}\n}"; + } + + /// + /// Parses a BlueMix json credentials into this object. + /// + /// The JSON data to parse. + /// Returns true on success. + public bool ParseJSON(string json) + { + try { - LoadConfig(); + IDictionary iParse = Json.Deserialize(json) as IDictionary; + IDictionary iCredentials = iParse["credentials"] as IDictionary; + m_URL = (string)iCredentials["url"]; + m_User = (string)iCredentials["username"]; + m_Password = (string)iCredentials["password"]; + m_Note = (string)iCredentials["note"]; + if (!string.IsNullOrEmpty((string)iCredentials["apikey"])) + m_Apikey = (string)iCredentials["apikey"]; + if (!string.IsNullOrEmpty((string)iCredentials["api_key"])) + m_Apikey = (string)iCredentials["api_key"]; + + return true; } - - /// - /// Find BlueMix credentials by the service ID. - /// - /// The ID of the service to find. - /// Returns null if the credentials cannot be found. - public CredentialInfo FindCredentials(string serviceID) + catch (Exception e) { - foreach (var info in m_Credentials) - if (info.m_ServiceID == serviceID) - return info; - return null; + try + { + IDictionary iParse = Json.Deserialize(json) as IDictionary; + m_URL = (string)iParse["url"]; + m_User = (string)iParse["username"]; + m_Password = (string)iParse["password"]; + m_Note = (string)iParse["note"]; + if (!string.IsNullOrEmpty((string)iParse["apikey"])) + m_Apikey = (string)iParse["apikey"]; + if (!string.IsNullOrEmpty((string)iParse["api_key"])) + m_Apikey = (string)iParse["api_key"]; + + return true; + } + catch + { + Log.Error("Config", "Caught Exception: {0}", e.ToString()); + } + Log.Error("Config", "Caught Exception: {0}", e.ToString()); } - /// - /// Invoking this function will start the co-routine to load the configuration. The user should check the - /// ConfigLoaded property to check when the configuration is actually loaded. - /// - public void LoadConfig() - { + return false; + } + + /// + /// Determines whether this instance has credentials. + /// + /// true if this instance has credentials; otherwise, false. + public bool HasCredentials() + { + return (!string.IsNullOrEmpty(m_User) && !string.IsNullOrEmpty(m_Password)); + } + + /// + /// Determines whether this instance has API key. + /// + /// true if this instance has API key; otherwise, false. + public bool HasAPIKey() + { + return !string.IsNullOrEmpty(m_Apikey); + } + } + + #region Private Data + [fsProperty] + private string m_ClassifierDirectory = "Watson/Scripts/Editor/Classifiers/"; + [fsProperty] + private float m_TimeOut = 30.0f; + [fsProperty] + private int m_MaxRestConnections = 5; + [fsProperty] + private List m_Credentials = new List(); + [fsProperty] + private List m_Variables = new List(); + + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Public Properties + /// + /// Returns true if the configuration is loaded or not. + /// + [fsIgnore] + public bool ConfigLoaded { get; set; } + /// + /// Returns the singleton instance. + /// + public static Config Instance { get { return Singleton.Instance; } } + /// + /// Returns the location of the classifiers + /// + public string ClassifierDirectory { get { return m_ClassifierDirectory; } set { m_ClassifierDirectory = value; } } + /// + /// Returns the Timeout for requests made to the server. + /// + public float TimeOut { get { return m_TimeOut; } set { m_TimeOut = value; } } + /// + /// Maximum number of connections Watson will make to the server back-end at any one time. + /// + public int MaxRestConnections { get { return m_MaxRestConnections; } set { m_MaxRestConnections = value; } } + /// + /// Returns the list of credentials used to login to the various services. + /// + public List Credentials { get { return m_Credentials; } set { m_Credentials = value; } } + /// + /// Returns a list of variables which can hold key/value data. + /// + public List Variables { get { return m_Variables; } set { m_Variables = value; } } + #endregion + + /// + /// Default constructor will call LoadConfig() automatically. + /// + public Config() + { + LoadConfig(); + } + + /// + /// Find BlueMix credentials by the service ID. + /// + /// The ID of the service to find. + /// Returns null if the credentials cannot be found. + public CredentialInfo FindCredentials(string serviceID) + { + foreach (var info in m_Credentials) + if (info.m_ServiceID == serviceID) + return info; + return null; + } + + /// + /// Invoking this function will start the co-routine to load the configuration. The user should check the + /// ConfigLoaded property to check when the configuration is actually loaded. + /// + public void LoadConfig() + { #if !UNITY_ANDROID || UNITY_EDITOR - try - { - if (!Directory.Exists(Application.streamingAssetsPath)) - Directory.CreateDirectory(Application.streamingAssetsPath); - LoadConfig(System.IO.File.ReadAllText(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE)); - } - catch (System.IO.FileNotFoundException) - { - // mark as loaded anyway, so we don't keep retrying.. - Log.Error("Config", "Failed to load config file."); - ConfigLoaded = true; - } + try + { + if (!Directory.Exists(Application.streamingAssetsPath)) + Directory.CreateDirectory(Application.streamingAssetsPath); + LoadConfig(System.IO.File.ReadAllText(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE)); + } + catch (System.IO.FileNotFoundException) + { + // mark as loaded anyway, so we don't keep retrying.. + Log.Error("Config", "Failed to load config file."); + ConfigLoaded = true; + } #else Runnable.Run(LoadConfigCR()); #endif - } + } - /// - /// Load the configuration from the given JSON data. - /// - /// The string containing the configuration JSON data. - /// - public bool LoadConfig(string json) + /// + /// Load the configuration from the given JSON data. + /// + /// The string containing the configuration JSON data. + /// + public bool LoadConfig(string json) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(json, out data); + if (!r.Succeeded) { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(json, out data); - if (!r.Succeeded) - { - Log.Error("Config", "Failed to parse Config.json: {0}", r.ToString()); - return false; - } - - object obj = this; - r = sm_Serializer.TryDeserialize(data, GetType(), ref obj); - if (!r.Succeeded) - { - Log.Error("Config", "Failed to parse Config.json: {0}", r.ToString()); - return false; - } - - ConfigLoaded = true; - return true; - } - catch (Exception e) - { - Log.Error("Config", "Failed to load config: {0}", e.ToString()); - } - - ConfigLoaded = true; - return false; + Log.Error("Config", "Failed to parse Config.json: {0}", r.ToString()); + return false; } - /// - /// Save this COnfig into JSON. - /// - /// If true, then the json data will be formatted for readability. - /// - public string SaveConfig(bool pretty = true) + object obj = this; + r = sm_Serializer.TryDeserialize(data, GetType(), ref obj); + if (!r.Succeeded) { - fsData data = null; - sm_Serializer.TrySerialize(GetType(), this, out data); + Log.Error("Config", "Failed to parse Config.json: {0}", r.ToString()); + return false; + } - if (!System.IO.Directory.Exists(Application.streamingAssetsPath)) - System.IO.Directory.CreateDirectory(Application.streamingAssetsPath); + ConfigLoaded = true; + return true; + } + catch (Exception e) + { + Log.Error("Config", "Failed to load config: {0}", e.ToString()); + } - if (pretty) - return fsJsonPrinter.PrettyJson(data); + ConfigLoaded = true; + return false; + } - return fsJsonPrinter.CompressedJson(data); - } + /// + /// Save this COnfig into JSON. + /// + /// If true, then the json data will be formatted for readability. + /// + public string SaveConfig(bool pretty = true) + { + fsData data = null; + sm_Serializer.TrySerialize(GetType(), this, out data); - /// - /// Save this config to fileSystem - /// - public bool SaveConfigToFileSystem() - { - bool success = true; - try - { - File.WriteAllText(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE, SaveConfig(true)); - } - catch (Exception ex) - { - success = false; - Log.Error("Config", "Exception on SaveConfigToFileSystem. {0}", ex.Message); - } - - return success; - } + if (!System.IO.Directory.Exists(Application.streamingAssetsPath)) + System.IO.Directory.CreateDirectory(Application.streamingAssetsPath); - /// - /// Finds a variable name and returns the Variable object - /// - /// The name of the variable to find. - /// Returns the Variable object or null if not found. - public Variable GetVariable(string key) - { - foreach (var var in m_Variables) - if (var.Key == key) - return var; + if (pretty) + return fsJsonPrinter.PrettyJson(data); - return null; - } + return fsJsonPrinter.CompressedJson(data); + } - /// - /// Gets an API key by service ID if it exists. - /// - /// - /// - public string GetAPIKey(string serviceID) - { - foreach (var info in m_Credentials) - if (info.m_ServiceID == serviceID) - return info.m_Apikey; - return null; - } + /// + /// Save this config to fileSystem + /// + public bool SaveConfigToFileSystem() + { + bool success = true; + try + { + File.WriteAllText(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE, SaveConfig(true)); + } + catch (Exception ex) + { + success = false; + Log.Error("Config", "Exception on SaveConfigToFileSystem. {0}", ex.Message); + } + + return success; + } - /// - /// Gets the variable value. - /// - /// The variable value. - /// Key. - public string GetVariableValue(string key) - { - Variable v = GetVariable(key); - if (v != null) - return v.Value; + /// + /// Finds a variable name and returns the Variable object + /// + /// The name of the variable to find. + /// Returns the Variable object or null if not found. + public Variable GetVariable(string key) + { + foreach (var var in m_Variables) + if (var.Key == key) + return var; - return null; - } + return null; + } - /// - /// Sets the variable value. - /// - /// true, if variable value was set, false otherwise. - /// Key. - /// Value. - public bool SetVariableValue(string key, string value, bool bAdd = false) - { - Variable v = GetVariable(key); - if (v == null) - { - if (!bAdd) - return false; - - v = new Variable(); - v.Key = key; - m_Variables.Add(v); - } - - v.Value = value; - return true; - } + /// + /// Gets an API key by service ID if it exists. + /// + /// + /// + public string GetAPIKey(string serviceID) + { + foreach (var info in m_Credentials) + if (info.m_ServiceID == serviceID) + return info.m_Apikey; + return null; + } - /// - /// Resolves any variables found in the input string and returns the variable values in the returned string. - /// - /// A string containing variables. - /// Returns the string with all variables resolved to their actual values. Any missing variables are removed from the string. - public string ResolveVariables(string input, bool recursive = true) - { - string output = input; - foreach (var var in m_Variables) - { - string value = var.Value; - if (recursive && value.Contains("${")) - value = ResolveVariables(value, false); - - output = output.Replace("${" + var.Key + "}", value); - } - - // remove any variables still in the string.. - int variableIndex = output.IndexOf("${"); - while (variableIndex >= 0) - { - int endVariable = output.IndexOf("}", variableIndex); - if (endVariable < 0) - break; // end not found.. - - output = output.Remove(variableIndex, (endVariable - variableIndex) + 1); - - // next.. - variableIndex = output.IndexOf("${"); - } - - return output; - } + /// + /// Gets the variable value. + /// + /// The variable value. + /// Key. + public string GetVariableValue(string key) + { + Variable v = GetVariable(key); + if (v != null) + return v.Value; - private IEnumerator LoadConfigCR() - { - // load the config using WWW, since this works on all platforms.. - WWW request = new WWW(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE); - while (!request.isDone) - yield return null; + return null; + } - LoadConfig(request.text); - yield break; - } + /// + /// Sets the variable value. + /// + /// true, if variable value was set, false otherwise. + /// Key. + /// Value. + public bool SetVariableValue(string key, string value, bool bAdd = false) + { + Variable v = GetVariable(key); + if (v == null) + { + if (!bAdd) + return false; + + v = new Variable(); + v.Key = key; + m_Variables.Add(v); + } + + v.Value = value; + return true; + } + + /// + /// Resolves any variables found in the input string and returns the variable values in the returned string. + /// + /// A string containing variables. + /// Returns the string with all variables resolved to their actual values. Any missing variables are removed from the string. + public string ResolveVariables(string input, bool recursive = true) + { + string output = input; + foreach (var var in m_Variables) + { + string value = var.Value; + if (recursive && value.Contains("${")) + value = ResolveVariables(value, false); + + output = output.Replace("${" + var.Key + "}", value); + } + + // remove any variables still in the string.. + int variableIndex = output.IndexOf("${"); + while (variableIndex >= 0) + { + int endVariable = output.IndexOf("}", variableIndex); + if (endVariable < 0) + break; // end not found.. + + output = output.Remove(variableIndex, (endVariable - variableIndex) + 1); + + // next.. + variableIndex = output.IndexOf("${"); + } + + return output; + } + + private IEnumerator LoadConfigCR() + { + // load the config using WWW, since this works on all platforms.. + WWW request = new WWW(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE); + while (!request.isDone) + yield return null; + + LoadConfig(request.text); + yield break; } + } } diff --git a/Scripts/Utilities/Constants.cs b/Scripts/Utilities/Constants.cs index ae64d78d5..9d7d9fbb1 100755 --- a/Scripts/Utilities/Constants.cs +++ b/Scripts/Utilities/Constants.cs @@ -15,60 +15,56 @@ * */ -using UnityEngine; -using System.Collections; -using UnityEngine.Serialization; - namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// This class wraps all constants. + /// + public static class Constants + { /// - /// This class wraps all constants. + /// All constant path variables liste here. Exp. Configuration file /// - public static class Constants + public static class Path { - /// - /// All constant path variables liste here. Exp. Configuration file - /// - public static class Path - { - /// - /// Configuration file name. - /// - public const string CONFIG_FILE = "/Config.json"; - /// - /// Cache folder to customize a parent folder for cache directory - /// - public static string CACHE_FOLDER = ""; //It needs to start with / - /// - /// Log folder to customize a parent folder for logs - /// - public static string LOG_FOLDER = ""; //It needs to start with / - } + /// + /// Configuration file name. + /// + public const string CONFIG_FILE = "/Config.json"; + /// + /// Cache folder to customize a parent folder for cache directory + /// + public static string CACHE_FOLDER = ""; //It needs to start with / + /// + /// Log folder to customize a parent folder for logs + /// + public static string LOG_FOLDER = ""; //It needs to start with / + } - /// - /// All resources (files names under resource directory) used in the SDK listed here. Exp. Watson Logo - /// - public static class Resources - { - /// - /// Watson icon. - /// - public const string WATSON_ICON = "watsonSpriteIcon-32x32"; - /// - /// Watson logo. - /// - public const string WATSON_LOGO = "watsonSpriteLogo-506x506"; - } + /// + /// All resources (files names under resource directory) used in the SDK listed here. Exp. Watson Logo + /// + public static class Resources + { + /// + /// Watson icon. + /// + public const string WATSON_ICON = "watsonSpriteIcon-32x32"; + /// + /// Watson logo. + /// + public const string WATSON_LOGO = "watsonSpriteLogo-506x506"; + } - /// - /// All string variables or string formats used in the SDK listed here. Exp. Quality Debug Format = Quality {0} - /// - public static class String - { - /// - public const string VERSION = "watson-developer-cloud-unity-sdk-0.11.0"; - /// - public const string DEBUG_DISPLAY_QUALITY = "Quality: {0}"; - } + /// + /// All string variables or string formats used in the SDK listed here. Exp. Quality Debug Format = Quality {0} + /// + public static class String + { + /// + public const string VERSION = "watson-developer-cloud-unity-sdk-0.11.0"; + /// + public const string DEBUG_DISPLAY_QUALITY = "Quality: {0}"; } + } } diff --git a/Scripts/Utilities/Credentials.cs b/Scripts/Utilities/Credentials.cs old mode 100644 new mode 100755 index a1edc70b8..0ea07d5c3 --- a/Scripts/Utilities/Credentials.cs +++ b/Scripts/Utilities/Credentials.cs @@ -20,52 +20,52 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Helper class for holding a user and password, used by both the WSCOnnector and RESTConnector. + /// + public class Credentials + { /// - /// Helper class for holding a user and password, used by both the WSCOnnector and RESTConnector. + /// Default constructor. /// - public class Credentials + public Credentials() + { } + /// + /// Constructor that takes the user name and password. + /// + /// The string containing the user name. + /// A string containing the password. + public Credentials(string user, string password) { - /// - /// Default constructor. - /// - public Credentials() - { } - /// - /// Constructor that takes the user name and password. - /// - /// The string containing the user name. - /// A string containing the password. - public Credentials(string user, string password) - { - User = user; - Password = password; - } + User = user; + Password = password; + } - /// - /// The user name. - /// - public string User { get; set; } - /// - /// The password. - /// - public string Password { get; set; } + /// + /// The user name. + /// + public string User { get; set; } + /// + /// The password. + /// + public string Password { get; set; } - /// - /// Create basic authentication header data for REST requests. - /// - /// The authentication data base64 encoded. - public string CreateAuthorization() - { - return "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(User + ":" + Password)); - } + /// + /// Create basic authentication header data for REST requests. + /// + /// The authentication data base64 encoded. + public string CreateAuthorization() + { + return "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(User + ":" + Password)); + } - /// - /// Do we have credentials? - /// - /// - public bool HasCredentials() - { - return !string.IsNullOrEmpty(User) && !string.IsNullOrEmpty(Password); - } - }; + /// + /// Do we have credentials? + /// + /// + public bool HasCredentials() + { + return !string.IsNullOrEmpty(User) && !string.IsNullOrEmpty(Password); + } + }; } diff --git a/Scripts/Utilities/DataCache.cs b/Scripts/Utilities/DataCache.cs old mode 100644 new mode 100755 index 781acaf35..ec540571a --- a/Scripts/Utilities/DataCache.cs +++ b/Scripts/Utilities/DataCache.cs @@ -15,7 +15,6 @@ * */ - using System; using System.Collections.Generic; using System.IO; @@ -25,239 +24,239 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// This class manages a cache of binary data by ID. + /// + public class DataCache + { + #region Private Data + private string m_CachePath = null; + private long m_MaxCacheSize = -1; + private double m_MaxCacheAge = 0; + private long m_CurrentCacheSize = 0; + + private class CacheItem + { + public string Path { get; set; } + public string Id { get; set; } + public DateTime Time { get; set; } + public byte[] Data { get; set; } + }; + private Dictionary m_Cache = new Dictionary(); + #endregion + /// - /// This class manages a cache of binary data by ID. + /// DataCache constructor. /// - public class DataCache + /// The name of the cache. + /// Maximum cache size in bytes. + /// Maximum age of a cache item in hours. + public DataCache(string cacheName, long maxCacheSize = 1024 * 1024 * 50, double maxCacheAge = 24 * 7) { - #region Private Data - private string m_CachePath = null; - private long m_MaxCacheSize = -1; - private double m_MaxCacheAge = 0; - private long m_CurrentCacheSize = 0; + Initialize(cacheName, maxCacheSize, maxCacheAge); + } - private class CacheItem - { - public string Path { get; set; } - public string Id { get; set; } - public DateTime Time { get; set; } - public byte[] Data { get; set; } - }; - private Dictionary m_Cache = new Dictionary(); - #endregion - - /// - /// DataCache constructor. - /// - /// The name of the cache. - /// Maximum cache size in bytes. - /// Maximum age of a cache item in hours. - public DataCache(string cacheName, long maxCacheSize = 1024 * 1024 * 50, double maxCacheAge = 24 * 7) + /// + /// Initializes this DataCache object. + /// + /// The name of the cache. + /// Maximum cache size in bytes. + /// Maximum age of a cache item in hours. + public void Initialize(string cacheName, long maxCacheSize, double maxCacheAge) + { + if (string.IsNullOrEmpty(cacheName)) + throw new ArgumentNullException("cacheName"); + cacheName = cacheName.Replace('/', '_'); + + m_MaxCacheSize = maxCacheSize; + m_MaxCacheAge = maxCacheAge; + + m_CachePath = Application.persistentDataPath + Constants.Path.CACHE_FOLDER + "/" + cacheName + "/"; + if (!Directory.Exists(m_CachePath)) + Directory.CreateDirectory(m_CachePath); + + foreach (var f in Directory.GetFiles(m_CachePath)) + { + DateTime lastWrite = File.GetLastAccessTime(f); + double age = (DateTime.Now - lastWrite).TotalHours; + if (age < m_MaxCacheAge) { - Initialize(cacheName, maxCacheSize, maxCacheAge); + CacheItem item = new CacheItem(); + item.Path = f; + item.Id = Path.GetFileNameWithoutExtension(f); + item.Time = lastWrite; + item.Data = null; + + m_Cache[item.Id] = item; + m_CurrentCacheSize += (new FileInfo(f)).Length; } - - /// - /// Initializes this DataCache object. - /// - /// The name of the cache. - /// Maximum cache size in bytes. - /// Maximum age of a cache item in hours. - public void Initialize(string cacheName, long maxCacheSize, double maxCacheAge) + else { - if (string.IsNullOrEmpty(cacheName)) - throw new ArgumentNullException("cacheName"); - cacheName = cacheName.Replace('/', '_'); - - m_MaxCacheSize = maxCacheSize; - m_MaxCacheAge = maxCacheAge; - - m_CachePath = Application.persistentDataPath + Constants.Path.CACHE_FOLDER + "/" + cacheName + "/"; - if (!Directory.Exists(m_CachePath)) - Directory.CreateDirectory(m_CachePath); - - foreach (var f in Directory.GetFiles(m_CachePath)) - { - DateTime lastWrite = File.GetLastAccessTime(f); - double age = (DateTime.Now - lastWrite).TotalHours; - if (age < m_MaxCacheAge) - { - CacheItem item = new CacheItem(); - item.Path = f; - item.Id = Path.GetFileNameWithoutExtension(f); - item.Time = lastWrite; - item.Data = null; - - m_Cache[item.Id] = item; - m_CurrentCacheSize += (new FileInfo(f)).Length; - } - else - { - Log.Debug("DataCache", "Removing aged cache item {0}", f); - File.Delete(f); - } - } + Log.Debug("DataCache", "Removing aged cache item {0}", f); + File.Delete(f); } + } + } - /// - /// Find a data object by ID. - /// - /// The ID to find. - /// The cached data, or null if not found. - public byte[] Find(string id) - { - if (!string.IsNullOrEmpty(id)) - { - id = id.Replace('/', '_'); + /// + /// Find a data object by ID. + /// + /// The ID to find. + /// The cached data, or null if not found. + public byte[] Find(string id) + { + if (!string.IsNullOrEmpty(id)) + { + id = id.Replace('/', '_'); - CacheItem item = null; - if (m_Cache.TryGetValue(id, out item)) - { + CacheItem item = null; + if (m_Cache.TryGetValue(id, out item)) + { #if !UNITY_ANDROID - item.Time = DateTime.Now; + item.Time = DateTime.Now; - File.SetLastWriteTime(item.Path, item.Time); + File.SetLastWriteTime(item.Path, item.Time); #endif - if (item.Data == null) - { - item.Data = File.ReadAllBytes(item.Path); - } - - return item.Data; - } - } + if (item.Data == null) + { + item.Data = File.ReadAllBytes(item.Path); + } - return null; + return item.Data; } + } - /// - /// Is the data cached? - /// - /// - /// - public bool IsCached(string id) - { - bool isCached = false; + return null; + } - if (!string.IsNullOrEmpty(id)) - { - id = id.Replace('/', '_'); + /// + /// Is the data cached? + /// + /// + /// + public bool IsCached(string id) + { + bool isCached = false; - CacheItem item = null; - if (m_Cache.TryGetValue(id, out item)) - { - isCached = File.Exists(item.Path); - } - } + if (!string.IsNullOrEmpty(id)) + { + id = id.Replace('/', '_'); - return isCached; + CacheItem item = null; + if (m_Cache.TryGetValue(id, out item)) + { + isCached = File.Exists(item.Path); } + } + + return isCached; + } + + /// + /// Save data into the cache by ID. + /// + /// The ID to save. + /// The data of the object to save. + public void Save(string id, byte[] data) + { + if (data != null && data.Length > 0) + { + id = id.Replace('/', '_'); - /// - /// Save data into the cache by ID. - /// - /// The ID to save. - /// The data of the object to save. - public void Save(string id, byte[] data) + if (m_Cache.ContainsKey(id)) { - if (data != null && data.Length > 0) - { - id = id.Replace('/', '_'); - - if (m_Cache.ContainsKey(id)) - { - Log.Debug("DataCache", "Has same key in the cache. Flushing old one: {0}", id); - Flush(id); - } - - CacheItem item = new CacheItem(); - item.Path = m_CachePath + id + ".bytes"; - item.Id = id; - item.Time = DateTime.Now; - item.Data = data; - - File.WriteAllBytes(item.Path, data); - m_CurrentCacheSize += item.Data.Length; - - m_Cache[id] = item; - - while (m_CurrentCacheSize > m_MaxCacheSize) - FlushOldest(); - } - else - { - Log.Error("DataCache", "Empty data came to the cache, couldn't cache any null data"); - } + Log.Debug("DataCache", "Has same key in the cache. Flushing old one: {0}", id); + Flush(id); } - /// - /// Flush a specific item from the cache. - /// - /// The ID of the object to flush. - public void Flush(string id) - { - id = id.Replace('/', '_'); + CacheItem item = new CacheItem(); + item.Path = m_CachePath + id + ".bytes"; + item.Id = id; + item.Time = DateTime.Now; + item.Data = data; - CacheItem item = null; - if (m_Cache.TryGetValue(id, out item)) - { - Log.Debug("DataCache", "Flushing {0} from cache.", item.Path); + File.WriteAllBytes(item.Path, data); + m_CurrentCacheSize += item.Data.Length; - if (item.Data != null) - m_CurrentCacheSize -= item.Data.Length; - else - m_CurrentCacheSize -= (new FileInfo(item.Path)).Length; + m_Cache[id] = item; - File.Delete(item.Path); + while (m_CurrentCacheSize > m_MaxCacheSize) + FlushOldest(); + } + else + { + Log.Error("DataCache", "Empty data came to the cache, couldn't cache any null data"); + } + } - m_Cache.Remove(id); - } - } + /// + /// Flush a specific item from the cache. + /// + /// The ID of the object to flush. + public void Flush(string id) + { + id = id.Replace('/', '_'); - /// - /// Flush any aged out data from the cache. - /// - public void FlushAged() - { - List flush = new List(); - foreach (var kp in m_Cache) - { - double age = (DateTime.Now - kp.Value.Time).TotalHours; - if (age > m_MaxCacheAge) - flush.Add(kp.Value); - } - - foreach (var item in flush) - Flush(item.Id); - } + CacheItem item = null; + if (m_Cache.TryGetValue(id, out item)) + { + Log.Debug("DataCache", "Flushing {0} from cache.", item.Path); - /// - /// Flush the oldest item from the cache. - /// - public void FlushOldest() - { - CacheItem oldest = null; - foreach (var kp in m_Cache) - { - if (oldest == null || kp.Value.Time < oldest.Time) - oldest = kp.Value; - } - - if (oldest != null) - { - Flush(oldest.Id); - } - } + if (item.Data != null) + m_CurrentCacheSize -= item.Data.Length; + else + m_CurrentCacheSize -= (new FileInfo(item.Path)).Length; - /// - /// Flush all data from the cache. - /// - public void Flush() - { - foreach (var kp in m_Cache) - File.Delete(kp.Value.Path); - m_Cache.Clear(); - } + File.Delete(item.Path); + + m_Cache.Remove(id); + } + } + + /// + /// Flush any aged out data from the cache. + /// + public void FlushAged() + { + List flush = new List(); + foreach (var kp in m_Cache) + { + double age = (DateTime.Now - kp.Value.Time).TotalHours; + if (age > m_MaxCacheAge) + flush.Add(kp.Value); + } + + foreach (var item in flush) + Flush(item.Id); + } + + /// + /// Flush the oldest item from the cache. + /// + public void FlushOldest() + { + CacheItem oldest = null; + foreach (var kp in m_Cache) + { + if (oldest == null || kp.Value.Time < oldest.Time) + oldest = kp.Value; + } + + if (oldest != null) + { + Flush(oldest.Id); + } + } + + /// + /// Flush all data from the cache. + /// + public void Flush() + { + foreach (var kp in m_Cache) + File.Delete(kp.Value.Path); + m_Cache.Clear(); } + } } diff --git a/Scripts/Utilities/EventManager.cs b/Scripts/Utilities/EventManager.cs old mode 100644 new mode 100755 index d116648a9..bf607ded0 --- a/Scripts/Utilities/EventManager.cs +++ b/Scripts/Utilities/EventManager.cs @@ -15,7 +15,6 @@ * */ - using IBM.Watson.DeveloperCloud.Logging; using System; using System.Collections; @@ -23,149 +22,149 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Singleton class for sending and receiving events. + /// + public class EventManager + { + #region Public Properties + /// + /// Returns the singleton event manager instance. + /// + public static EventManager Instance { get { return Singleton.Instance; } } + #endregion + + #region Public Types + /// + /// The delegate for an event receiver. + /// + /// The arguments passed into SendEvent(). + public delegate void OnReceiveEvent(object[] args); + #endregion + + #region Public Functions /// - /// Singleton class for sending and receiving events. + /// Register an event receiver with this EventManager. /// - public class EventManager + /// The name of the event. + /// The event receiver function. + public void RegisterEventReceiver(string eventName, OnReceiveEvent callback) { - #region Public Properties - /// - /// Returns the singleton event manager instance. - /// - public static EventManager Instance { get { return Singleton.Instance; } } - #endregion - - #region Public Types - /// - /// The delegate for an event receiver. - /// - /// The arguments passed into SendEvent(). - public delegate void OnReceiveEvent(object[] args); - #endregion - - #region Public Functions - /// - /// Register an event receiver with this EventManager. - /// - /// The name of the event. - /// The event receiver function. - public void RegisterEventReceiver(string eventName, OnReceiveEvent callback) - { - if (!m_EventMap.ContainsKey(eventName)) - m_EventMap.Add(eventName, new List() { callback }); - else - m_EventMap[eventName].Add(callback); - } + if (!m_EventMap.ContainsKey(eventName)) + m_EventMap.Add(eventName, new List() { callback }); + else + m_EventMap[eventName].Add(callback); + } - /// - /// Unregisters all event receivers. - /// - public void UnregisterAllEventReceivers() - { - m_EventMap.Clear(); - } + /// + /// Unregisters all event receivers. + /// + public void UnregisterAllEventReceivers() + { + m_EventMap.Clear(); + } - /// - /// Unregister all event receivers for a given event. - /// - /// Name of the event to unregister. - public void UnregisterEventReceivers(string eventName) - { - m_EventMap.Remove(eventName); - } + /// + /// Unregister all event receivers for a given event. + /// + /// Name of the event to unregister. + public void UnregisterEventReceivers(string eventName) + { + m_EventMap.Remove(eventName); + } - /// - /// Unregister a specific receiver. - /// - /// Name of the event. - /// The event handler. - public void UnregisterEventReceiver(string eventName, OnReceiveEvent callback) - { - if (m_EventMap.ContainsKey(eventName)) - m_EventMap[eventName].Remove(callback); - } + /// + /// Unregister a specific receiver. + /// + /// Name of the event. + /// The event handler. + public void UnregisterEventReceiver(string eventName, OnReceiveEvent callback) + { + if (m_EventMap.ContainsKey(eventName)) + m_EventMap[eventName].Remove(callback); + } - /// - /// Send an event to all registered receivers. - /// - /// The name of the event to send. - /// Arguments to send to the event receiver. - /// Returns true if a event receiver was found for the event. - public bool SendEvent(string eventName, params object[] args) - { - if (string.IsNullOrEmpty(eventName)) - throw new ArgumentNullException(eventName); - - List receivers = null; - if (m_EventMap.TryGetValue(eventName, out receivers)) - { - for (int i = 0; i < receivers.Count; ++i) - { - if (receivers[i] == null) - { - Log.Warning("EventManager", "Removing invalid event receiver."); - receivers.RemoveAt(i--); - continue; - } - try - { - receivers[i](args); - } - catch (Exception ex) - { - Log.Error("EventManager", "Event Receiver Exception: {0}", ex.ToString()); - } - } - return true; - } - return false; - } + /// + /// Send an event to all registered receivers. + /// + /// The name of the event to send. + /// Arguments to send to the event receiver. + /// Returns true if a event receiver was found for the event. + public bool SendEvent(string eventName, params object[] args) + { + if (string.IsNullOrEmpty(eventName)) + throw new ArgumentNullException(eventName); - /// - /// Queues an event to be sent, returns immediately. - /// - /// The name of the event to send. - /// Arguments to send to the event receiver. - public void SendEventAsync(string eventName, params object[] args) + List receivers = null; + if (m_EventMap.TryGetValue(eventName, out receivers)) + { + for (int i = 0; i < receivers.Count; ++i) { - m_AsyncEvents.Enqueue(new AsyncEvent() { m_EventName = eventName, m_Args = args }); - if (m_ProcesserCount == 0) - Runnable.Run(ProcessAsyncEvents()); + if (receivers[i] == null) + { + Log.Warning("EventManager", "Removing invalid event receiver."); + receivers.RemoveAt(i--); + continue; + } + try + { + receivers[i](args); + } + catch (Exception ex) + { + Log.Error("EventManager", "Event Receiver Exception: {0}", ex.ToString()); + } } - #endregion + return true; + } + return false; + } - #region Private Data - private Dictionary> m_EventTypeName = new Dictionary>(); - private Dictionary> m_EventMap = new Dictionary>(); + /// + /// Queues an event to be sent, returns immediately. + /// + /// The name of the event to send. + /// Arguments to send to the event receiver. + public void SendEventAsync(string eventName, params object[] args) + { + m_AsyncEvents.Enqueue(new AsyncEvent() { m_EventName = eventName, m_Args = args }); + if (m_ProcesserCount == 0) + Runnable.Run(ProcessAsyncEvents()); + } + #endregion - private class AsyncEvent - { - public string m_EventName; - public object[] m_Args; - } - private Queue m_AsyncEvents = new Queue(); - private int m_ProcesserCount = 0; + #region Private Data + private Dictionary> m_EventTypeName = new Dictionary>(); + private Dictionary> m_EventMap = new Dictionary>(); - private IEnumerator ProcessAsyncEvents() - { - m_ProcesserCount += 1; - yield return null; + private class AsyncEvent + { + public string m_EventName; + public object[] m_Args; + } + private Queue m_AsyncEvents = new Queue(); + private int m_ProcesserCount = 0; + + private IEnumerator ProcessAsyncEvents() + { + m_ProcesserCount += 1; + yield return null; - while (m_AsyncEvents.Count > 0) - { - AsyncEvent send = m_AsyncEvents.Dequeue(); - SendEvent(send.m_EventName, send.m_Args); - } + while (m_AsyncEvents.Count > 0) + { + AsyncEvent send = m_AsyncEvents.Dequeue(); + SendEvent(send.m_EventName, send.m_Args); + } - m_ProcesserCount -= 1; - } - #endregion + m_ProcesserCount -= 1; + } + #endregion - private void InitializeEventTypeNames(Type enumType) - { - m_EventTypeName[enumType] = new Dictionary(); - foreach (var en in Enum.GetNames(enumType)) - m_EventTypeName[enumType][Enum.Parse(enumType, en)] = en; - } + private void InitializeEventTypeNames(Type enumType) + { + m_EventTypeName[enumType] = new Dictionary(); + foreach (var en in Enum.GetNames(enumType)) + m_EventTypeName[enumType][Enum.Parse(enumType, en)] = en; } + } } diff --git a/Scripts/Utilities/FrameRateCounter.cs b/Scripts/Utilities/FrameRateCounter.cs old mode 100644 new mode 100755 index 1d93839da..9e9680e00 --- a/Scripts/Utilities/FrameRateCounter.cs +++ b/Scripts/Utilities/FrameRateCounter.cs @@ -20,37 +20,37 @@ namespace IBM.Watson.DeveloperCloud.Utilities { - /// - /// Displays the frame rate of the application. - /// - public class FrameRateCounter : MonoBehaviour - { - const float FPS_INTERVAL = 0.5f; - const string DISPLAY = "{0} FPS"; + /// + /// Displays the frame rate of the application. + /// + public class FrameRateCounter : MonoBehaviour + { + const float FPS_INTERVAL = 0.5f; + const string DISPLAY = "{0} FPS"; - private int m_FpsAccumulator = 0; - private float m_FpsNextPeriod = 0; - private int m_CurrentFps; + private int m_FpsAccumulator = 0; + private float m_FpsNextPeriod = 0; + private int m_CurrentFps; - [SerializeField] - private Text m_Text; + [SerializeField] + private Text m_Text; - private void Start() - { - m_FpsNextPeriod = Time.realtimeSinceStartup + FPS_INTERVAL; - } + private void Start() + { + m_FpsNextPeriod = Time.realtimeSinceStartup + FPS_INTERVAL; + } - private void Update() - { - // measure average frames per second - m_FpsAccumulator++; - if (Time.realtimeSinceStartup > m_FpsNextPeriod) - { - m_CurrentFps = (int)(m_FpsAccumulator / FPS_INTERVAL); - m_FpsAccumulator = 0; - m_FpsNextPeriod += FPS_INTERVAL; - m_Text.text = string.Format(DISPLAY, m_CurrentFps); - } - } + private void Update() + { + // measure average frames per second + m_FpsAccumulator++; + if (Time.realtimeSinceStartup > m_FpsNextPeriod) + { + m_CurrentFps = (int)(m_FpsAccumulator / FPS_INTERVAL); + m_FpsAccumulator = 0; + m_FpsNextPeriod += FPS_INTERVAL; + m_Text.text = string.Format(DISPLAY, m_CurrentFps); + } } + } } diff --git a/Scripts/Utilities/KeyEventManager.cs b/Scripts/Utilities/KeyEventManager.cs old mode 100644 new mode 100755 index 32c718853..419b42b37 --- a/Scripts/Utilities/KeyEventManager.cs +++ b/Scripts/Utilities/KeyEventManager.cs @@ -21,163 +21,163 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Key press modifiers + /// + [Flags] + public enum KeyModifiers + { /// - /// Key press modifiers + /// No key modifier down. /// - [Flags] - public enum KeyModifiers + NONE = 0x0, + /// + /// Shift key down. + /// + SHIFT = 0x1, + /// + /// Control key down. + /// + CONTROL = 0x2, + /// + /// Alt key down. + /// + ALT = 0x4 + }; + + /// + /// This class handles key presses and will sent events and/or invoke a delegate when a key is pressed. + /// + public class KeyEventManager : MonoBehaviour + { + /// How many bits to shift modifier up/down when mapped into the dictionary. + private int MODIFIER_SHIFT_BITS = 10; + private int KEYCODE_MASK = (1 << 10) - 1; + + #region Private Data + private bool m_Active = true; + private bool m_UpdateActivate = true; + private Dictionary m_KeyEvents = new Dictionary(); + #endregion + + #region Public Properties + /// + /// Set/Get the active state of this manager. + /// + public bool Active { get { return m_Active; } set { m_UpdateActivate = value; } } + /// + /// The current instance of the DebugConsole. + /// + public static KeyEventManager Instance { get { return Singleton.Instance; } } + #endregion + + #region OnEnable / OnDisable - Initial keys to capture + private void OnEnable() { - /// - /// No key modifier down. - /// - NONE = 0x0, - /// - /// Shift key down. - /// - SHIFT = 0x1, - /// - /// Control key down. - /// - CONTROL = 0x2, - /// - /// Alt key down. - /// - ALT = 0x4 - }; + KeyEventManager.Instance.RegisterKeyEvent(KeyCode.Tab, KeyModifiers.NONE, "OnKeyboardTab"); + KeyEventManager.Instance.RegisterKeyEvent(KeyCode.Return, KeyModifiers.NONE, "OnKeyboardReturn"); + KeyEventManager.Instance.RegisterKeyEvent(KeyCode.Escape, KeyModifiers.NONE, "OnKeyboardEscape"); + KeyEventManager.Instance.RegisterKeyEvent(KeyCode.BackQuote, KeyModifiers.NONE, "OnKeyboardBackquote"); + } + + private void OnDisable() + { + KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.Tab, KeyModifiers.NONE, "OnKeyboardTab"); + KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.Return, KeyModifiers.NONE, "OnKeyboardReturn"); + KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.Escape, KeyModifiers.NONE, "OnKeyboardEscape"); + KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.BackQuote, KeyModifiers.NONE, "OnKeyboardBackquote"); + } + #endregion + #region Public Functions /// - /// This class handles key presses and will sent events and/or invoke a delegate when a key is pressed. + /// Register a key event. /// - public class KeyEventManager : MonoBehaviour + /// The KeyCode of the key. + /// KeyCode modifiers + /// The event to send. + /// True is returned on success. + public bool RegisterKeyEvent(KeyCode key, KeyModifiers modifiers, string eventType) { - /// How many bits to shift modifier up/down when mapped into the dictionary. - private int MODIFIER_SHIFT_BITS = 10; - private int KEYCODE_MASK = (1 << 10) - 1; - - #region Private Data - private bool m_Active = true; - private bool m_UpdateActivate = true; - private Dictionary m_KeyEvents = new Dictionary(); - #endregion - - #region Public Properties - /// - /// Set/Get the active state of this manager. - /// - public bool Active { get { return m_Active; } set { m_UpdateActivate = value; } } - /// - /// The current instance of the DebugConsole. - /// - public static KeyEventManager Instance { get { return Singleton.Instance; } } - #endregion - - #region OnEnable / OnDisable - Initial keys to capture - private void OnEnable() - { - KeyEventManager.Instance.RegisterKeyEvent(KeyCode.Tab, KeyModifiers.NONE, "OnKeyboardTab" ); - KeyEventManager.Instance.RegisterKeyEvent(KeyCode.Return, KeyModifiers.NONE, "OnKeyboardReturn"); - KeyEventManager.Instance.RegisterKeyEvent(KeyCode.Escape, KeyModifiers.NONE, "OnKeyboardEscape"); - KeyEventManager.Instance.RegisterKeyEvent(KeyCode.BackQuote, KeyModifiers.NONE, "OnKeyboardBackquote"); - } - - private void OnDisable() - { - KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.Tab, KeyModifiers.NONE, "OnKeyboardTab" ); - KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.Return, KeyModifiers.NONE, "OnKeyboardReturn"); - KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.Escape, KeyModifiers.NONE, "OnKeyboardEscape"); - KeyEventManager.Instance.UnregisterKeyEvent(KeyCode.BackQuote, KeyModifiers.NONE, "OnKeyboardBackquote"); - } - #endregion - - #region Public Functions - /// - /// Register a key event. - /// - /// The KeyCode of the key. - /// KeyCode modifiers - /// The event to send. - /// True is returned on success. - public bool RegisterKeyEvent(KeyCode key, KeyModifiers modifiers, string eventType) - { - int code = ((int)key) | (((int)modifiers) << MODIFIER_SHIFT_BITS); - m_KeyEvents[code] = eventType; - return true; - } - /// - /// Unregister a key event. - /// - /// The KeyCode to unregister. - /// Additional keys that must be down as well to fire the event. - /// If provided, then the key will be unregistered only the event matches the existing registration. - /// True is returned on success. - public bool UnregisterKeyEvent(KeyCode key, KeyModifiers modifiers = KeyModifiers.NONE, string eventType = "" ) - { - int code = ((int)key) | (((int)modifiers) << MODIFIER_SHIFT_BITS); - if ( eventType != "" && m_KeyEvents.ContainsKey(code) && m_KeyEvents[code] == eventType ) - return m_KeyEvents.Remove( code ); + int code = ((int)key) | (((int)modifiers) << MODIFIER_SHIFT_BITS); + m_KeyEvents[code] = eventType; + return true; + } + /// + /// Unregister a key event. + /// + /// The KeyCode to unregister. + /// Additional keys that must be down as well to fire the event. + /// If provided, then the key will be unregistered only the event matches the existing registration. + /// True is returned on success. + public bool UnregisterKeyEvent(KeyCode key, KeyModifiers modifiers = KeyModifiers.NONE, string eventType = "") + { + int code = ((int)key) | (((int)modifiers) << MODIFIER_SHIFT_BITS); + if (eventType != "" && m_KeyEvents.ContainsKey(code) && m_KeyEvents[code] == eventType) + return m_KeyEvents.Remove(code); - return m_KeyEvents.Remove(code); - } + return m_KeyEvents.Remove(code); + } - #endregion + #endregion - private void Update() + private void Update() + { + if (m_Active) + { + List fire = new List(); + foreach (var kp in m_KeyEvents) { - if (m_Active) + KeyCode key = (KeyCode)(kp.Key & KEYCODE_MASK); + + if (Input.GetKeyDown(key)) + { + bool bFireEvent = true; + + int modifiers = kp.Key >> MODIFIER_SHIFT_BITS; + if (modifiers != 0) { - List fire = new List(); - foreach (var kp in m_KeyEvents) - { - KeyCode key = (KeyCode)(kp.Key & KEYCODE_MASK); - - if (Input.GetKeyDown(key)) - { - bool bFireEvent = true; - - int modifiers = kp.Key >> MODIFIER_SHIFT_BITS; - if (modifiers != 0) - { - if ((modifiers & (int)KeyModifiers.SHIFT) != 0 - && !Input.GetKey(KeyCode.RightShift) && !Input.GetKey(KeyCode.LeftShift)) - { - bFireEvent = false; - } - if ((modifiers & (int)KeyModifiers.CONTROL) != 0 - && !Input.GetKey(KeyCode.RightControl) && !Input.GetKey(KeyCode.LeftControl)) - { - bFireEvent = false; - } - if ((modifiers & (int)KeyModifiers.ALT) != 0 - && !Input.GetKey(KeyCode.RightAlt) && !Input.GetKey(KeyCode.LeftAlt)) - { - bFireEvent = false; - } - } - - if (bFireEvent) - fire.Add(kp.Value); - } - - if(Input.anyKeyDown && !string.IsNullOrEmpty(Input.inputString)) - { - EventManager.Instance.SendEvent("OnKeyboardAnyKeyDown", Input.inputString); - } - } - - // now fire the events outside of the dictionary loop so we don't throw an exception.. - foreach (var ev in fire) - EventManager.Instance.SendEvent( ev ); + if ((modifiers & (int)KeyModifiers.SHIFT) != 0 + && !Input.GetKey(KeyCode.RightShift) && !Input.GetKey(KeyCode.LeftShift)) + { + bFireEvent = false; + } + if ((modifiers & (int)KeyModifiers.CONTROL) != 0 + && !Input.GetKey(KeyCode.RightControl) && !Input.GetKey(KeyCode.LeftControl)) + { + bFireEvent = false; + } + if ((modifiers & (int)KeyModifiers.ALT) != 0 + && !Input.GetKey(KeyCode.RightAlt) && !Input.GetKey(KeyCode.LeftAlt)) + { + bFireEvent = false; + } } - // update our active flag AFTER we check the active flag, this prevents - // us from responding the key events during the same frame as we activate - // this manager. - m_Active = m_UpdateActivate; - } + if (bFireEvent) + fire.Add(kp.Value); + } - private void OnApplicationQuit() - { - Destroy(gameObject); + if (Input.anyKeyDown && !string.IsNullOrEmpty(Input.inputString)) + { + EventManager.Instance.SendEvent("OnKeyboardAnyKeyDown", Input.inputString); + } } + + // now fire the events outside of the dictionary loop so we don't throw an exception.. + foreach (var ev in fire) + EventManager.Instance.SendEvent(ev); + } + + // update our active flag AFTER we check the active flag, this prevents + // us from responding the key events during the same frame as we activate + // this manager. + m_Active = m_UpdateActivate; + } + + private void OnApplicationQuit() + { + Destroy(gameObject); } + } } diff --git a/Scripts/Utilities/NestedPrefabs.cs b/Scripts/Utilities/NestedPrefabs.cs old mode 100644 new mode 100755 index 01801e9b4..b46b747f6 --- a/Scripts/Utilities/NestedPrefabs.cs +++ b/Scripts/Utilities/NestedPrefabs.cs @@ -20,47 +20,47 @@ namespace IBM.Watson.DeveloperCloud.Utilities { - class NestedPrefabs : MonoBehaviour - { - [SerializeField] - private List m_Prefabs = new List(); - private List m_GameObjectCreated = new List(); - [SerializeField] - private bool m_SetParent = true; + class NestedPrefabs : MonoBehaviour + { + [SerializeField] + private List m_Prefabs = new List(); + private List m_GameObjectCreated = new List(); + [SerializeField] + private bool m_SetParent = true; - private void Awake() - { - foreach (GameObject prefab in m_Prefabs) - { - if (prefab == null) - continue; + private void Awake() + { + foreach (GameObject prefab in m_Prefabs) + { + if (prefab == null) + continue; - GameObject instance = Instantiate(prefab); - if (m_SetParent) - instance.transform.SetParent(transform, false); + GameObject instance = Instantiate(prefab); + if (m_SetParent) + instance.transform.SetParent(transform, false); - m_GameObjectCreated.Add(instance); - } - } + m_GameObjectCreated.Add(instance); + } + } - #region Destroy objects + #region Destroy objects - /// - /// It destroys the created object to set the initial state - /// - public void DestroyCreatedObject() - { - foreach (GameObject gameObject in m_GameObjectCreated) - { - if (gameObject == null) - continue; + /// + /// It destroys the created object to set the initial state + /// + public void DestroyCreatedObject() + { + foreach (GameObject gameObject in m_GameObjectCreated) + { + if (gameObject == null) + continue; - gameObject.SendMessage("DestroyCreatedObject", SendMessageOptions.DontRequireReceiver); - Destroy(gameObject); - } - m_GameObjectCreated.Clear(); - Destroy(this.gameObject); - } - #endregion + gameObject.SendMessage("DestroyCreatedObject", SendMessageOptions.DontRequireReceiver); + Destroy(gameObject); + } + m_GameObjectCreated.Clear(); + Destroy(this.gameObject); } + #endregion + } } diff --git a/Scripts/Utilities/Runnable.cs b/Scripts/Utilities/Runnable.cs old mode 100644 new mode 100755 index c9d544097..c8a9ca349 --- a/Scripts/Utilities/Runnable.cs +++ b/Scripts/Utilities/Runnable.cs @@ -24,147 +24,147 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Helper class for running co-routines without having to inherit from MonoBehavior. + /// + public class Runnable : MonoBehaviour + { + #region Public Properties /// - /// Helper class for running co-routines without having to inherit from MonoBehavior. + /// Returns the Runnable instance. /// - public class Runnable : MonoBehaviour + public static Runnable Instance { get { return Singleton.Instance; } } + #endregion + + #region Public Interface + /// + /// Start a co-routine function. + /// + /// The IEnumerator returns by the co-routine function the user is invoking. + /// Returns a ID that can be passed into Stop() to halt the co-routine. + public static int Run(IEnumerator routine) { - #region Public Properties - /// - /// Returns the Runnable instance. - /// - public static Runnable Instance { get { return Singleton.Instance; } } - #endregion - - #region Public Interface - /// - /// Start a co-routine function. - /// - /// The IEnumerator returns by the co-routine function the user is invoking. - /// Returns a ID that can be passed into Stop() to halt the co-routine. - public static int Run(IEnumerator routine) - { - Routine r = new Routine(routine); - return r.ID; - } + Routine r = new Routine(routine); + return r.ID; + } - /// - /// Stops a active co-routine. - /// - /// THe ID of the co-routine to stop. - public static void Stop(int ID) - { - Routine r = null; - if (Instance.m_Routines.TryGetValue(ID, out r)) - r.Stop = true; - } + /// + /// Stops a active co-routine. + /// + /// THe ID of the co-routine to stop. + public static void Stop(int ID) + { + Routine r = null; + if (Instance.m_Routines.TryGetValue(ID, out r)) + r.Stop = true; + } - /// - /// Check if a routine is still running. - /// - /// The ID returned by Run(). - /// Returns true if the routine is still active. - static public bool IsRunning(int id) - { - return Instance.m_Routines.ContainsKey(id); - } + /// + /// Check if a routine is still running. + /// + /// The ID returned by Run(). + /// Returns true if the routine is still active. + static public bool IsRunning(int id) + { + return Instance.m_Routines.ContainsKey(id); + } #if UNITY_EDITOR - private static bool sm_EditorRunnable = false; + private static bool sm_EditorRunnable = false; - /// - /// This function enables the Runnable in edit mode. - /// - public static void EnableRunnableInEditor() - { - if (!sm_EditorRunnable) - { - sm_EditorRunnable = true; - UnityEditor.EditorApplication.update += UpdateRunnable; - } - } - static void UpdateRunnable() - { - if (!Application.isPlaying) - Instance.UpdateRoutines(); - } + /// + /// This function enables the Runnable in edit mode. + /// + public static void EnableRunnableInEditor() + { + if (!sm_EditorRunnable) + { + sm_EditorRunnable = true; + UnityEditor.EditorApplication.update += UpdateRunnable; + } + } + static void UpdateRunnable() + { + if (!Application.isPlaying) + Instance.UpdateRoutines(); + } #endif - #endregion + #endregion - #region Private Types - /// - /// This class handles a running co-routine. - /// - private class Routine : IEnumerator - { - #region Public Properties - public int ID { get; private set; } - public bool Stop { get; set; } - #endregion - - #region Private Data - private bool m_bMoveNext = false; - private IEnumerator m_Enumerator = null; - #endregion - - public Routine(IEnumerator a_enumerator) - { - m_Enumerator = a_enumerator; - Runnable.Instance.StartCoroutine(this); - Stop = false; - ID = Runnable.Instance.m_NextRoutineId++; - - Runnable.Instance.m_Routines[ID] = this; + #region Private Types + /// + /// This class handles a running co-routine. + /// + private class Routine : IEnumerator + { + #region Public Properties + public int ID { get; private set; } + public bool Stop { get; set; } + #endregion + + #region Private Data + private bool m_bMoveNext = false; + private IEnumerator m_Enumerator = null; + #endregion + + public Routine(IEnumerator a_enumerator) + { + m_Enumerator = a_enumerator; + Runnable.Instance.StartCoroutine(this); + Stop = false; + ID = Runnable.Instance.m_NextRoutineId++; + + Runnable.Instance.m_Routines[ID] = this; #if ENABLE_RUNNABLE_DEBUGGING Debug.Log( string.Format("Coroutine {0} started.", ID ) ); #endif - } - - #region IEnumerator Interface - public object Current { get { return m_Enumerator.Current; } } - public bool MoveNext() - { - m_bMoveNext = m_Enumerator.MoveNext(); - if (m_bMoveNext && Stop) - m_bMoveNext = false; - - if (!m_bMoveNext) - { - Runnable.Instance.m_Routines.Remove(ID); // remove from the mapping + } + + #region IEnumerator Interface + public object Current { get { return m_Enumerator.Current; } } + public bool MoveNext() + { + m_bMoveNext = m_Enumerator.MoveNext(); + if (m_bMoveNext && Stop) + m_bMoveNext = false; + + if (!m_bMoveNext) + { + Runnable.Instance.m_Routines.Remove(ID); // remove from the mapping #if ENABLE_RUNNABLE_DEBUGGING Debug.Log( string.Format("Coroutine {0} stopped.", ID ) ); #endif - } - - return m_bMoveNext; - } - public void Reset() { m_Enumerator.Reset(); } - #endregion - } - #endregion - - #region Private Data - private Dictionary m_Routines = new Dictionary(); - private int m_NextRoutineId = 1; - #endregion - - /// - /// THis can be called by the user to force all co-routines to get a time slice, this is usually - /// invoked from an EditorApplication.Update callback so we can use runnable in Editor mode. - /// - public void UpdateRoutines() - { - if (m_Routines.Count > 0) - { - // we are not in play mode, so we must manually update our co-routines ourselves - List routines = new List(); - foreach (var kp in m_Routines) - routines.Add(kp.Value); - - foreach (var r in routines) - r.MoveNext(); - } } + + return m_bMoveNext; + } + public void Reset() { m_Enumerator.Reset(); } + #endregion + } + #endregion + + #region Private Data + private Dictionary m_Routines = new Dictionary(); + private int m_NextRoutineId = 1; + #endregion + + /// + /// THis can be called by the user to force all co-routines to get a time slice, this is usually + /// invoked from an EditorApplication.Update callback so we can use runnable in Editor mode. + /// + public void UpdateRoutines() + { + if (m_Routines.Count > 0) + { + // we are not in play mode, so we must manually update our co-routines ourselves + List routines = new List(); + foreach (var kp in m_Routines) + routines.Add(kp.Value); + + foreach (var r in routines) + r.MoveNext(); + } } + } } diff --git a/Scripts/Utilities/SerializedDelegate.cs b/Scripts/Utilities/SerializedDelegate.cs old mode 100644 new mode 100755 index a0c409d5e..c0d12203f --- a/Scripts/Utilities/SerializedDelegate.cs +++ b/Scripts/Utilities/SerializedDelegate.cs @@ -22,55 +22,55 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// This class allows for a delegate to be serialized for a component and method + /// on a given GameObject. + /// + [Serializable] + public class SerializedDelegate + { /// - /// This class allows for a delegate to be serialized for a component and method - /// on a given GameObject. + /// Default constructor. /// - [Serializable] - public class SerializedDelegate + /// The delegate type. + public SerializedDelegate(Type delegateType) { - /// - /// Default constructor. - /// - /// The delegate type. - public SerializedDelegate(Type delegateType) - { - DelegateType = delegateType; - } + DelegateType = delegateType; + } - /// - /// The delegate type of the method. - /// - public Type DelegateType { get; private set; } + /// + /// The delegate type of the method. + /// + public Type DelegateType { get; private set; } - [SerializeField] - GameObject m_Target = null; - [SerializeField] - string m_Component = null; - [SerializeField] - string m_Method = null; + [SerializeField] + GameObject m_Target = null; + [SerializeField] + string m_Component = null; + [SerializeField] + string m_Method = null; - /// - /// Target Game Object to invoke the callback under selected component - /// - public GameObject TargetGameObject { get { return m_Target; } } + /// + /// Target Game Object to invoke the callback under selected component + /// + public GameObject TargetGameObject { get { return m_Target; } } - /// - /// This resolves the actual delegate for invoke. - /// - /// Returns a delegate or null if the delegate can't be resolved. - public Delegate ResolveDelegate() - { - if (m_Target == null) - return null; - Component component = m_Target.GetComponent(m_Component); - if (component == null) - return null; - MethodInfo info = component.GetType().GetMethod(m_Method, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod); - if (info == null) - return null; + /// + /// This resolves the actual delegate for invoke. + /// + /// Returns a delegate or null if the delegate can't be resolved. + public Delegate ResolveDelegate() + { + if (m_Target == null) + return null; + Component component = m_Target.GetComponent(m_Component); + if (component == null) + return null; + MethodInfo info = component.GetType().GetMethod(m_Method, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod); + if (info == null) + return null; - return Delegate.CreateDelegate(DelegateType, component, info); - } + return Delegate.CreateDelegate(DelegateType, component, info); } + } } diff --git a/Scripts/Utilities/Singleton.cs b/Scripts/Utilities/Singleton.cs old mode 100644 new mode 100755 index 92dd95c53..41cc0554a --- a/Scripts/Utilities/Singleton.cs +++ b/Scripts/Utilities/Singleton.cs @@ -22,62 +22,62 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Singleton pattern class. This class detects if T is a MonoBehavior and will + /// make a containing GameObject. + /// + /// The typename of the class to create as a singleton object. + public class Singleton where T : class + { + #region Private Data + static private T sm_Instance = null; + #endregion + + #region Public Properties /// - /// Singleton pattern class. This class detects if T is a MonoBehavior and will - /// make a containing GameObject. + /// Returns the Singleton instance of T. /// - /// The typename of the class to create as a singleton object. - public class Singleton where T : class + public static T Instance { - #region Private Data - static private T sm_Instance = null; - #endregion - - #region Public Properties - /// - /// Returns the Singleton instance of T. - /// - public static T Instance - { - get - { - if (sm_Instance == null) - CreateInstance(); - return sm_Instance; - } - } - #endregion + get + { + if (sm_Instance == null) + CreateInstance(); + return sm_Instance; + } + } + #endregion - #region Singleton Creation - /// - /// Create the singleton instance. - /// - private static void CreateInstance() - { - if (typeof(MonoBehaviour).IsAssignableFrom(typeof(T))) - { - string singletonName = "_" + typeof(T).Name; + #region Singleton Creation + /// + /// Create the singleton instance. + /// + private static void CreateInstance() + { + if (typeof(MonoBehaviour).IsAssignableFrom(typeof(T))) + { + string singletonName = "_" + typeof(T).Name; - GameObject singletonObject = GameObject.Find(singletonName); - if (singletonObject == null) - singletonObject = new GameObject(singletonName); + GameObject singletonObject = GameObject.Find(singletonName); + if (singletonObject == null) + singletonObject = new GameObject(singletonName); #if SINGLETONS_VISIBLE - singletonObject.hideFlags = HideFlags.DontSave; + singletonObject.hideFlags = HideFlags.DontSave; #else singletonObject.hideFlags = HideFlags.HideAndDontSave; #endif - sm_Instance = singletonObject.GetComponent(); - if (sm_Instance == null) - sm_Instance = singletonObject.AddComponent(typeof(T)) as T; - } - else - { - sm_Instance = Activator.CreateInstance(typeof(T)) as T; - } + sm_Instance = singletonObject.GetComponent(); + if (sm_Instance == null) + sm_Instance = singletonObject.AddComponent(typeof(T)) as T; + } + else + { + sm_Instance = Activator.CreateInstance(typeof(T)) as T; + } - if (sm_Instance == null) - throw new WatsonException("Failed to create instance " + typeof(T).Name); - } - #endregion + if (sm_Instance == null) + throw new WatsonException("Failed to create instance " + typeof(T).Name); } + #endregion + } } diff --git a/Scripts/Utilities/TimedDestroy.cs b/Scripts/Utilities/TimedDestroy.cs old mode 100644 new mode 100755 index f9cda6136..7bb5cef91 --- a/Scripts/Utilities/TimedDestroy.cs +++ b/Scripts/Utilities/TimedDestroy.cs @@ -20,105 +20,105 @@ namespace IBM.Watson.DeveloperCloud.Utilities { - /// - /// Helper class for automatically destroying objects after a static amount of time has elapsed. - /// - public class TimedDestroy : MonoBehaviour - { - [SerializeField, Tooltip("How many seconds until this component destroy's it's parent object.")] - private float m_DestroyTime = 5.0f; - private float m_ElapsedTime = 0.0f; - private bool m_TimeReachedToDestroy = false; - [SerializeField] - private bool m_AlphaFade = true; - [SerializeField] - private bool m_AlphaFadeOnAwake = false; - [SerializeField] - private float m_FadeTime = 1.0f; - [SerializeField] - private float m_FadeTimeOnAwake = 1.0f; - [SerializeField] - private Graphic m_AlphaTarget = null; - private bool m_Fading = false; - private float m_FadeStart = 0.0f; - private Color m_InitialColor = Color.white; - private float m_FadeAwakeRatio = 0.0f; + /// + /// Helper class for automatically destroying objects after a static amount of time has elapsed. + /// + public class TimedDestroy : MonoBehaviour + { + [SerializeField, Tooltip("How many seconds until this component destroy's it's parent object.")] + private float m_DestroyTime = 5.0f; + private float m_ElapsedTime = 0.0f; + private bool m_TimeReachedToDestroy = false; + [SerializeField] + private bool m_AlphaFade = true; + [SerializeField] + private bool m_AlphaFadeOnAwake = false; + [SerializeField] + private float m_FadeTime = 1.0f; + [SerializeField] + private float m_FadeTimeOnAwake = 1.0f; + [SerializeField] + private Graphic m_AlphaTarget = null; + private bool m_Fading = false; + private float m_FadeStart = 0.0f; + private Color m_InitialColor = Color.white; + private float m_FadeAwakeRatio = 0.0f; - private void Start() - { - m_ElapsedTime = 0.0f; + private void Start() + { + m_ElapsedTime = 0.0f; - if (m_AlphaFade && m_AlphaTarget != null) - { - m_InitialColor = m_AlphaTarget.color; + if (m_AlphaFade && m_AlphaTarget != null) + { + m_InitialColor = m_AlphaTarget.color; - if (m_AlphaFadeOnAwake) - { - m_AlphaTarget.color = new Color(m_InitialColor.r, m_InitialColor.g, m_InitialColor.b, 0.0f); - } - } - } - - private void Update() + if (m_AlphaFadeOnAwake) { + m_AlphaTarget.color = new Color(m_InitialColor.r, m_InitialColor.g, m_InitialColor.b, 0.0f); + } + } + } - if (m_AlphaFadeOnAwake) - { - m_FadeAwakeRatio += (Time.deltaTime / m_FadeTimeOnAwake); - m_AlphaTarget.color = new Color(m_InitialColor.r, m_InitialColor.g, m_InitialColor.b, Mathf.Clamp01(m_FadeAwakeRatio)); - if (m_FadeAwakeRatio > 1.0f) - m_AlphaFadeOnAwake = false; - } + private void Update() + { - if (!m_TimeReachedToDestroy) - { - m_ElapsedTime += Time.deltaTime; - if (m_ElapsedTime > m_DestroyTime) - { - m_TimeReachedToDestroy = true; - OnTimeExpired(); - } - } + if (m_AlphaFadeOnAwake) + { + m_FadeAwakeRatio += (Time.deltaTime / m_FadeTimeOnAwake); + m_AlphaTarget.color = new Color(m_InitialColor.r, m_InitialColor.g, m_InitialColor.b, Mathf.Clamp01(m_FadeAwakeRatio)); + if (m_FadeAwakeRatio > 1.0f) + m_AlphaFadeOnAwake = false; + } - if (m_Fading) - { - float fElapsed = Time.time - m_FadeStart; - if (fElapsed < m_FadeTime && m_AlphaTarget != null) - { - Color c = m_AlphaTarget.color; - c.a = 1.0f - fElapsed / m_FadeTime; - m_AlphaTarget.color = c; - } - else - Destroy(gameObject); - } + if (!m_TimeReachedToDestroy) + { + m_ElapsedTime += Time.deltaTime; + if (m_ElapsedTime > m_DestroyTime) + { + m_TimeReachedToDestroy = true; + OnTimeExpired(); } + } - /// - /// Resets the timer. - /// - public void ResetTimer() + if (m_Fading) + { + float fElapsed = Time.time - m_FadeStart; + if (fElapsed < m_FadeTime && m_AlphaTarget != null) { - m_ElapsedTime = 0.0f; - m_Fading = false; - m_TimeReachedToDestroy = false; + Color c = m_AlphaTarget.color; + c.a = 1.0f - fElapsed / m_FadeTime; + m_AlphaTarget.color = c; + } + else + Destroy(gameObject); + } + } - if (m_AlphaFade && m_AlphaTarget != null) - { - m_AlphaTarget.color = m_InitialColor; + /// + /// Resets the timer. + /// + public void ResetTimer() + { + m_ElapsedTime = 0.0f; + m_Fading = false; + m_TimeReachedToDestroy = false; - } - } + if (m_AlphaFade && m_AlphaTarget != null) + { + m_AlphaTarget.color = m_InitialColor; - private void OnTimeExpired() - { - if (m_AlphaFade && m_AlphaTarget != null) - { - m_Fading = true; - m_FadeStart = Time.time; - } - else - Destroy(gameObject); - } + } + } + + private void OnTimeExpired() + { + if (m_AlphaFade && m_AlphaTarget != null) + { + m_Fading = true; + m_FadeStart = Time.time; + } + else + Destroy(gameObject); } + } } diff --git a/Scripts/Utilities/TouchEventManager.cs b/Scripts/Utilities/TouchEventManager.cs old mode 100644 new mode 100755 index c9d89958c..b4480be58 --- a/Scripts/Utilities/TouchEventManager.cs +++ b/Scripts/Utilities/TouchEventManager.cs @@ -19,7 +19,6 @@ //#define ENABLE_DEBUGGING using UnityEngine; -using UnityEngine.UI; using UnityEngine.EventSystems; using System; using System.Collections.Generic; @@ -28,2254 +27,2284 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Touch Event Manager for all touch events. + /// Each element can register their touch related functions using this manager. + /// + [RequireComponent(typeof(TapGesture))] + public class TouchEventManager : MonoBehaviour + { + /// - /// Touch Event Manager for all touch events. - /// Each element can register their touch related functions using this manager. + /// Touch Event Data holds all touch related event data for registering and unregistering events via Touch Event Manager. /// - [RequireComponent(typeof(TapGesture))] - public class TouchEventManager : MonoBehaviour + public class TouchEventData { - - /// - /// Touch Event Data holds all touch related event data for registering and unregistering events via Touch Event Manager. - /// - public class TouchEventData + private Collider m_Collider; + private Collider2D m_Collider2D; + private RectTransform m_RectTransform; + private Collider[] m_ColliderList; + private Collider2D[] m_Collider2DList; + private RectTransform[] m_RectTransformList; + private GameObject m_GameObject; + private string m_tapEventCallback; + private string m_dragEventCallback; + private bool m_isInside; + private int m_SortingLayer; + + /// + /// Game Object related with touch event + /// + public GameObject GameObjectAttached { get { return m_GameObject; } } + /// + /// If it is tap event (or one time action event) we are returning the collider of the event. + /// + public Collider Collider { get { return m_Collider; } } + /// + /// Gets the collider2 d. + /// + /// The collider2 d. + public Collider2D Collider2D { get { return m_Collider2D; } } + /// + /// Gets the rect transform. + /// + /// The rect transform. + public RectTransform RectTransform { get { return m_RectTransform; } } + /// + /// If there is a drag event (or continues action) we are holding game object and all colliders inside that object + /// + public Collider[] ColliderList { get { if (m_ColliderList == null && m_Collider != null) m_ColliderList = new Collider[] { m_Collider }; return m_ColliderList; } } + /// + /// If there is a drag event (or continues action) we are holding game object and all colliders inside that object + /// + public Collider2D[] ColliderList2D { get { if (m_Collider2DList == null && m_Collider2D != null) m_Collider2DList = new Collider2D[] { m_Collider2D }; return m_Collider2DList; } } + /// + /// Gets the rect transform list. + /// + /// The rect transform list. + public RectTransform[] RectTransformList { get { if (m_RectTransformList == null && m_RectTransform != null) m_RectTransformList = new RectTransform[] { m_RectTransform }; return m_RectTransformList; } } + + /// + /// If the touch event has happened inside of that object (collider) we will fire that event. Otherwise, it is considered as outside + /// + public bool IsInside { get { return m_isInside; } } + /// + /// Tap Delegate to call + /// + public string TapCallback { get { return m_tapEventCallback; } } + /// + /// Drag Delegate to call + /// + public string DragCallback { get { return m_dragEventCallback; } } + /// + /// Greater sorting layer is higher importance level. + /// + public int SortingLayer { get { return m_SortingLayer; } } + /// + /// Gets a value indicating whether this instance can drag object. + /// + /// true if this instance can drag object; otherwise, false. + public bool CanDragObject { get { return GameObjectAttached != null && ((ColliderList != null && ColliderList.Length > 0) || (ColliderList2D != null && ColliderList2D.Length > 0) || (RectTransformList != null && RectTransformList.Length > 0)); } } + + /// + /// Touch event constructor for Tap Event registration. + /// + /// Collider of the object to tap + /// Callback for Tap Event. After tapped, callback will be invoked + /// Sorting level in order to sort the event listeners + /// Whether the tap is inside the object or not + public TouchEventData(Collider collider, string callback, int sortingLayer, bool isInside) + { + m_Collider = collider; + m_Collider2D = null; + m_RectTransform = null; + m_ColliderList = null; + m_Collider2DList = null; + m_RectTransformList = null; + m_tapEventCallback = callback; + m_SortingLayer = sortingLayer; + m_isInside = isInside; + } + + /// + /// Touch event constructor for 2D Tap Event registration. + /// + /// Collider of the object to tap + /// Callback for Tap Event. After tapped, callback will be invoked + /// Sorting level in order to sort the event listeners + /// Whether the tap is inside the object or not + public TouchEventData(Collider2D collider, string callback, int sortingLayer, bool isInside) + { + m_Collider = null; + m_Collider2D = collider; + m_RectTransform = null; + m_ColliderList = null; + m_Collider2DList = null; + m_RectTransformList = null; + m_tapEventCallback = callback; + m_SortingLayer = sortingLayer; + m_isInside = isInside; + } + + /// + /// Initializes a new instance of the + /// class. + /// + /// Rect transform. + /// Callback. + /// Sorting layer. + /// If set to true is inside. + public TouchEventData(RectTransform rectTransform, string callback, int sortingLayer, bool isInside) + { + m_Collider = null; + m_Collider2D = null; + m_RectTransform = rectTransform; + m_ColliderList = null; + m_Collider2DList = null; + m_RectTransformList = null; + m_tapEventCallback = callback; + m_SortingLayer = sortingLayer; + m_isInside = isInside; + } + + /// + /// Touch event constructor for Drag Event registration. + /// + /// Gameobject to drag + /// Callback for Drag event. After dragging started, callback will be invoked until drag will be finished + /// Sorting level in order to sort the event listeners + /// + public TouchEventData(GameObject gameObject, string callback, int sortingLayer, bool isInside) + { + m_GameObject = gameObject; + m_ColliderList = null; + if (gameObject != null) { - private Collider m_Collider; - private Collider2D m_Collider2D; - private RectTransform m_RectTransform; - private Collider[] m_ColliderList; - private Collider2D[] m_Collider2DList; - private RectTransform[] m_RectTransformList; - private GameObject m_GameObject; - private string m_tapEventCallback; - private string m_dragEventCallback; - private bool m_isInside; - private int m_SortingLayer; - - /// - /// Game Object related with touch event - /// - public GameObject GameObjectAttached { get { return m_GameObject; } } - /// - /// If it is tap event (or one time action event) we are returning the collider of the event. - /// - public Collider Collider { get { return m_Collider; } } - /// - /// Gets the collider2 d. - /// - /// The collider2 d. - public Collider2D Collider2D { get { return m_Collider2D; } } - /// - /// Gets the rect transform. - /// - /// The rect transform. - public RectTransform RectTransform { get { return m_RectTransform; } } - /// - /// If there is a drag event (or continues action) we are holding game object and all colliders inside that object - /// - public Collider[] ColliderList { get { if (m_ColliderList == null && m_Collider != null) m_ColliderList = new Collider[] { m_Collider }; return m_ColliderList; } } - /// - /// If there is a drag event (or continues action) we are holding game object and all colliders inside that object - /// - public Collider2D[] ColliderList2D { get { if (m_Collider2DList == null && m_Collider2D != null) m_Collider2DList = new Collider2D[] { m_Collider2D }; return m_Collider2DList; } } - /// - /// Gets the rect transform list. - /// - /// The rect transform list. - public RectTransform[] RectTransformList { get { if (m_RectTransformList == null && m_RectTransform != null) m_RectTransformList = new RectTransform[] { m_RectTransform }; return m_RectTransformList; } } - - /// - /// If the touch event has happened inside of that object (collider) we will fire that event. Otherwise, it is considered as outside - /// - public bool IsInside { get { return m_isInside; } } - /// - /// Tap Delegate to call - /// - public string TapCallback { get { return m_tapEventCallback; } } - /// - /// Drag Delegate to call - /// - public string DragCallback { get { return m_dragEventCallback; } } - /// - /// Greater sorting layer is higher importance level. - /// - public int SortingLayer { get { return m_SortingLayer; } } - /// - /// Gets a value indicating whether this instance can drag object. - /// - /// true if this instance can drag object; otherwise, false. - public bool CanDragObject { get { return GameObjectAttached != null && ((ColliderList != null && ColliderList.Length > 0) || (ColliderList2D != null && ColliderList2D.Length > 0) || (RectTransformList != null && RectTransformList.Length > 0)); } } - - /// - /// Touch event constructor for Tap Event registration. - /// - /// Collider of the object to tap - /// Callback for Tap Event. After tapped, callback will be invoked - /// Sorting level in order to sort the event listeners - /// Whether the tap is inside the object or not - public TouchEventData(Collider collider, string callback, int sortingLayer, bool isInside) + m_ColliderList = gameObject.GetComponentsInChildren(includeInactive: true); + m_Collider2DList = gameObject.GetComponentsInChildren(includeInactive: true); + m_RectTransformList = gameObject.GetComponentsInChildren(includeInactive: true); + } + m_dragEventCallback = callback; + m_SortingLayer = sortingLayer; + m_isInside = isInside; + } + + /// + /// Determines whether this instance has touched on the specified hitTransform. + /// + /// true if this instance has touched on the specified hitTransform; otherwise, false. + /// Hit transform. + public bool HasTouchedOn(Transform hitTransform) + { + bool hasTouchedOn = false; + if (ColliderList != null) + { + foreach (Collider itemCollider in ColliderList) + { + if (itemCollider.transform == hitTransform && itemCollider.gameObject.activeSelf) { - m_Collider = collider; - m_Collider2D = null; - m_RectTransform = null; - m_ColliderList = null; - m_Collider2DList = null; - m_RectTransformList = null; - m_tapEventCallback = callback; - m_SortingLayer = sortingLayer; - m_isInside = isInside; + hasTouchedOn = true; + break; } + } + } - /// - /// Touch event constructor for 2D Tap Event registration. - /// - /// Collider of the object to tap - /// Callback for Tap Event. After tapped, callback will be invoked - /// Sorting level in order to sort the event listeners - /// Whether the tap is inside the object or not - public TouchEventData(Collider2D collider, string callback, int sortingLayer, bool isInside) + if (!hasTouchedOn && ColliderList2D != null) + { + foreach (Collider2D itemCollider in ColliderList2D) + { + if (itemCollider.transform == hitTransform && itemCollider.gameObject.activeSelf) { - m_Collider = null; - m_Collider2D = collider; - m_RectTransform = null; - m_ColliderList = null; - m_Collider2DList = null; - m_RectTransformList = null; - m_tapEventCallback = callback; - m_SortingLayer = sortingLayer; - m_isInside = isInside; + hasTouchedOn = true; + break; } + } + } - /// - /// Initializes a new instance of the - /// class. - /// - /// Rect transform. - /// Callback. - /// Sorting layer. - /// If set to true is inside. - public TouchEventData(RectTransform rectTransform, string callback, int sortingLayer, bool isInside) + if (!hasTouchedOn && RectTransformList != null) + { + foreach (RectTransform itemRectTransform in RectTransformList) + { + if (itemRectTransform.transform == hitTransform && itemRectTransform.gameObject.activeSelf) { - m_Collider = null; - m_Collider2D = null; - m_RectTransform = rectTransform; - m_ColliderList = null; - m_Collider2DList = null; - m_RectTransformList = null; - m_tapEventCallback = callback; - m_SortingLayer = sortingLayer; - m_isInside = isInside; + hasTouchedOn = true; + break; } + } + } - /// - /// Touch event constructor for Drag Event registration. - /// - /// Gameobject to drag - /// Callback for Drag event. After dragging started, callback will be invoked until drag will be finished - /// Sorting level in order to sort the event listeners - /// - public TouchEventData(GameObject gameObject, string callback, int sortingLayer, bool isInside) - { - m_GameObject = gameObject; - m_ColliderList = null; - if (gameObject != null) - { - m_ColliderList = gameObject.GetComponentsInChildren(includeInactive: true); - m_Collider2DList = gameObject.GetComponentsInChildren(includeInactive: true); - m_RectTransformList = gameObject.GetComponentsInChildren(includeInactive: true); - } - m_dragEventCallback = callback; - m_SortingLayer = sortingLayer; - m_isInside = isInside; - } + return hasTouchedOn; + } + + /// + /// To check equality of the same Touch Event Data + /// + /// Object to check equality + /// True if objects are equal + public override bool Equals(object obj) + { + bool isEqual = false; + TouchEventData touchEventData = obj as TouchEventData; + if (touchEventData != null) + { + isEqual = + (touchEventData.Collider == this.Collider && + touchEventData.Collider2D == this.Collider2D && + touchEventData.RectTransform == this.RectTransform && + touchEventData.GameObjectAttached == this.GameObjectAttached && + touchEventData.IsInside == this.IsInside && + touchEventData.SortingLayer == this.SortingLayer && + touchEventData.DragCallback == this.DragCallback && + touchEventData.TapCallback == this.TapCallback); + } + else + { + isEqual = base.Equals(obj); + } - /// - /// Determines whether this instance has touched on the specified hitTransform. - /// - /// true if this instance has touched on the specified hitTransform; otherwise, false. - /// Hit transform. - public bool HasTouchedOn(Transform hitTransform) - { - bool hasTouchedOn = false; - if (ColliderList != null) - { - foreach (Collider itemCollider in ColliderList) - { - if (itemCollider.transform == hitTransform && itemCollider.gameObject.activeSelf) - { - hasTouchedOn = true; - break; - } - } - } + return isEqual; + } + + /// + /// Returns the hash code + /// + /// Default hash code coming from base class + public override int GetHashCode() + { + return base.GetHashCode(); + } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[TouchEventData: GameObjectAttached={0}, Collider={1}, Collider2D={2}, RectTransform={3}, ColliderList={4}, ColliderList2D={5}, RectTransformList={6}, IsInside={7}, TapCallback={8}, DragCallback={9}, SortingLayer={10}, CanDragObject={11}]", GameObjectAttached, Collider, Collider2D, RectTransform, ColliderList, ColliderList2D, RectTransformList, IsInside, TapCallback, DragCallback, SortingLayer, CanDragObject); + } - if (!hasTouchedOn && ColliderList2D != null) - { - foreach (Collider2D itemCollider in ColliderList2D) - { - if (itemCollider.transform == hitTransform && itemCollider.gameObject.activeSelf) - { - hasTouchedOn = true; - break; - } - } - } + } - if (!hasTouchedOn && RectTransformList != null) - { - foreach (RectTransform itemRectTransform in RectTransformList) - { - if (itemRectTransform.transform == hitTransform && itemRectTransform.gameObject.activeSelf) - { - hasTouchedOn = true; - break; - } - } - } + #region Private Data + private UnityEngine.Camera m_mainCamera; + + private bool m_Active = true; + private Dictionary> m_TapEvents = new Dictionary>(); + private Dictionary> m_DoubleTapEvents = new Dictionary>(); + private Dictionary> m_DragEvents = new Dictionary>(); + #endregion + + #region Serialized Private + [SerializeField] + private TapGesture m_TapGesture; + [SerializeField] + private TapGesture m_DoubleTapGesture; + [SerializeField] + private TapGesture m_ThreeTapGesture; + [SerializeField] + private ScreenTransformGesture m_OneFingerMoveGesture; + [SerializeField] + private ScreenTransformGesture m_TwoFingerMoveGesture; + [SerializeField] + private PressGesture m_PressGesture; + [SerializeField] + private ReleaseGesture m_ReleaseGesture; + [SerializeField] + private LongPressGesture m_LongPressGesture; + + #endregion + + #region Public Properties + /// + /// Set/Get the active state of this manager. + /// + public bool Active { get { return m_Active; } set { m_Active = value; } } - return hasTouchedOn; - } + private static TouchEventManager sm_Instance = null; + /// + /// The current instance of the TouchEventManager. + /// + public static TouchEventManager Instance { get { return sm_Instance; } } + #endregion - /// - /// To check equality of the same Touch Event Data - /// - /// Object to check equality - /// True if objects are equal - public override bool Equals(object obj) - { - bool isEqual = false; - TouchEventData touchEventData = obj as TouchEventData; - if (touchEventData != null) - { - isEqual = - (touchEventData.Collider == this.Collider && - touchEventData.Collider2D == this.Collider2D && - touchEventData.RectTransform == this.RectTransform && - touchEventData.GameObjectAttached == this.GameObjectAttached && - touchEventData.IsInside == this.IsInside && - touchEventData.SortingLayer == this.SortingLayer && - touchEventData.DragCallback == this.DragCallback && - touchEventData.TapCallback == this.TapCallback); - } - else - { - isEqual = base.Equals(obj); - } + #region Awake / OnEnable / OnDisable - return isEqual; - } + void Awake() + { + sm_Instance = this; + } - /// - /// Returns the hash code - /// - /// Default hash code coming from base class - public override int GetHashCode() - { - return base.GetHashCode(); - } + private void OnEnable() + { + m_mainCamera = UnityEngine.Camera.main; + if (m_TapGesture != null) + m_TapGesture.Tapped += TapGesture_Tapped; + if (m_DoubleTapGesture != null) + m_DoubleTapGesture.Tapped += DoubleTapGesture_Tapped; + if (m_ThreeTapGesture != null) + m_ThreeTapGesture.Tapped += ThreeTapGesture_Tapped; + if (m_OneFingerMoveGesture != null) + m_OneFingerMoveGesture.Transformed += OneFingerTransformedHandler; + if (m_TwoFingerMoveGesture != null) + m_TwoFingerMoveGesture.Transformed += TwoFingerTransformedHandler; + if (m_PressGesture != null) + m_PressGesture.Pressed += PressGesturePressed; + if (m_ReleaseGesture != null) + m_ReleaseGesture.Released += ReleaseGestureReleased; + if (m_LongPressGesture != null) + m_LongPressGesture.LongPressed += LongPressGesturePressed; - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - return string.Format("[TouchEventData: GameObjectAttached={0}, Collider={1}, Collider2D={2}, RectTransform={3}, ColliderList={4}, ColliderList2D={5}, RectTransformList={6}, IsInside={7}, TapCallback={8}, DragCallback={9}, SortingLayer={10}, CanDragObject={11}]", GameObjectAttached, Collider, Collider2D, RectTransform, ColliderList, ColliderList2D, RectTransformList, IsInside, TapCallback, DragCallback, SortingLayer, CanDragObject); - } + } - } + private void OnDisable() + { + if (m_TapGesture != null) + m_TapGesture.Tapped -= TapGesture_Tapped; + if (m_DoubleTapGesture != null) + m_DoubleTapGesture.Tapped -= DoubleTapGesture_Tapped; + if (m_ThreeTapGesture != null) + m_ThreeTapGesture.Tapped -= ThreeTapGesture_Tapped; + if (m_OneFingerMoveGesture != null) + m_OneFingerMoveGesture.Transformed -= OneFingerTransformedHandler; + if (m_TwoFingerMoveGesture != null) + m_TwoFingerMoveGesture.Transformed -= TwoFingerTransformedHandler; + if (m_PressGesture != null) + m_PressGesture.Pressed -= PressGesturePressed; + if (m_ReleaseGesture != null) + m_ReleaseGesture.Released -= ReleaseGestureReleased; + if (m_LongPressGesture != null) + m_LongPressGesture.LongPressed -= LongPressGesturePressed; + + if (m_DragEvents != null) + m_DragEvents.Clear(); + if (m_TapEvents != null) + m_TapEvents.Clear(); + if (m_DoubleTapEvents != null) + m_DoubleTapEvents.Clear(); + } - #region Private Data - private UnityEngine.Camera m_mainCamera; - - private bool m_Active = true; - private Dictionary> m_TapEvents = new Dictionary>(); - private Dictionary> m_DoubleTapEvents = new Dictionary>(); - private Dictionary> m_DragEvents = new Dictionary>(); - #endregion - - #region Serialized Private - [SerializeField] - private TapGesture m_TapGesture; - [SerializeField] - private TapGesture m_DoubleTapGesture; - [SerializeField] - private TapGesture m_ThreeTapGesture; - [SerializeField] - private ScreenTransformGesture m_OneFingerMoveGesture; - [SerializeField] - private ScreenTransformGesture m_TwoFingerMoveGesture; - [SerializeField] - private PressGesture m_PressGesture; - [SerializeField] - private ReleaseGesture m_ReleaseGesture; - [SerializeField] - private LongPressGesture m_LongPressGesture; - - #endregion - - #region Public Properties - /// - /// Set/Get the active state of this manager. - /// - public bool Active { get { return m_Active; } set { m_Active = value; } } - - private static TouchEventManager sm_Instance = null; - /// - /// The current instance of the TouchEventManager. - /// - public static TouchEventManager Instance { get { return sm_Instance; } } - #endregion - - #region Awake / OnEnable / OnDisable - - void Awake() - { - sm_Instance = this; - } + /// + /// Gets the main camera. + /// + /// The main camera. + public UnityEngine.Camera MainCamera + { + get + { + if (m_mainCamera == null || !m_mainCamera.transform.CompareTag("MainCamera")) + m_mainCamera = UnityEngine.Camera.main; - private void OnEnable() - { - m_mainCamera = UnityEngine.Camera.main; - if (m_TapGesture != null) - m_TapGesture.Tapped += TapGesture_Tapped; - if (m_DoubleTapGesture != null) - m_DoubleTapGesture.Tapped += DoubleTapGesture_Tapped; - if (m_ThreeTapGesture != null) - m_ThreeTapGesture.Tapped += ThreeTapGesture_Tapped; - if (m_OneFingerMoveGesture != null) - m_OneFingerMoveGesture.Transformed += OneFingerTransformedHandler; - if (m_TwoFingerMoveGesture != null) - m_TwoFingerMoveGesture.Transformed += TwoFingerTransformedHandler; - if (m_PressGesture != null) - m_PressGesture.Pressed += PressGesturePressed; - if (m_ReleaseGesture != null) - m_ReleaseGesture.Released += ReleaseGestureReleased; - if (m_LongPressGesture != null) - m_LongPressGesture.LongPressed += LongPressGesturePressed; + return m_mainCamera; + } + } - } - private void OnDisable() + #endregion + + #region OneFinger Events - Register / UnRegister / Call + /// + /// Registers the drag event. + /// + /// true, if drag event was registered, false otherwise. + /// Game object to drag. If it is null then fullscreen drag is registered. + /// Callback. + /// Number of finger. + /// Sorting layer. + /// If set to true is drag inside. + public bool RegisterDragEvent(GameObject gameObjectToDrag, string callback, int numberOfFinger = 1, int SortingLayer = 0, bool isDragInside = true) + { + bool success = false; + + if (!string.IsNullOrEmpty(callback)) + { + if (m_DragEvents.ContainsKey(numberOfFinger)) { - if (m_TapGesture != null) - m_TapGesture.Tapped -= TapGesture_Tapped; - if (m_DoubleTapGesture != null) - m_DoubleTapGesture.Tapped -= DoubleTapGesture_Tapped; - if (m_ThreeTapGesture != null) - m_ThreeTapGesture.Tapped -= ThreeTapGesture_Tapped; - if (m_OneFingerMoveGesture != null) - m_OneFingerMoveGesture.Transformed -= OneFingerTransformedHandler; - if (m_TwoFingerMoveGesture != null) - m_TwoFingerMoveGesture.Transformed -= TwoFingerTransformedHandler; - if (m_PressGesture != null) - m_PressGesture.Pressed -= PressGesturePressed; - if (m_ReleaseGesture != null) - m_ReleaseGesture.Released -= ReleaseGestureReleased; - if (m_LongPressGesture != null) - m_LongPressGesture.LongPressed -= LongPressGesturePressed; - - if (m_DragEvents != null) - m_DragEvents.Clear(); - if (m_TapEvents != null) - m_TapEvents.Clear(); - if (m_DoubleTapEvents != null) - m_DoubleTapEvents.Clear(); + m_DragEvents[numberOfFinger].Add(new TouchEventData(gameObjectToDrag, callback, SortingLayer, isDragInside)); } - - /// - /// Gets the main camera. - /// - /// The main camera. - public UnityEngine.Camera MainCamera + else { - get - { - if (m_mainCamera == null || !m_mainCamera.transform.CompareTag("MainCamera")) - m_mainCamera = UnityEngine.Camera.main; - - return m_mainCamera; - } + m_DragEvents[numberOfFinger] = new List() { new TouchEventData(gameObjectToDrag, callback, SortingLayer, isDragInside) }; } + success = true; + } + else + { + Log.Warning("TouchEventManager", "There is no callback for drag event registration"); + } - #endregion + return success; + } - #region OneFinger Events - Register / UnRegister / Call - /// - /// Registers the drag event. - /// - /// true, if drag event was registered, false otherwise. - /// Game object to drag. If it is null then fullscreen drag is registered. - /// Callback. - /// Number of finger. - /// Sorting layer. - /// If set to true is drag inside. - public bool RegisterDragEvent(GameObject gameObjectToDrag, string callback, int numberOfFinger = 1, int SortingLayer = 0, bool isDragInside = true) + /// + /// Unregisters the drag event. + /// + /// true, if drag event was unregistered, false otherwise. + /// Game object to drag. + /// Callback. + /// Number of finger. + /// Sorting layer. + /// If set to true is drag inside. + public bool UnregisterDragEvent(GameObject gameObjectToDrag, string callback, int numberOfFinger = 1, int SortingLayer = 0, bool isDragInside = true) + { + bool success = false; + + if (!string.IsNullOrEmpty(callback)) + { + if (m_DragEvents.ContainsKey(numberOfFinger)) { - bool success = false; + int numberOfRemovedCallbacks = m_DragEvents[numberOfFinger].RemoveAll( + e => + e.GameObjectAttached == gameObjectToDrag && + e.DragCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isDragInside); + + success &= (numberOfRemovedCallbacks > 0); + } + } + else + { + Log.Warning("TouchEventManager", "There is no callback for drag event unregistration"); + } + return success; + } - if (!string.IsNullOrEmpty(callback)) - { - if (m_DragEvents.ContainsKey(numberOfFinger)) - { - m_DragEvents[numberOfFinger].Add(new TouchEventData(gameObjectToDrag, callback, SortingLayer, isDragInside)); - } - else - { - m_DragEvents[numberOfFinger] = new List() { new TouchEventData(gameObjectToDrag, callback, SortingLayer, isDragInside) }; - } - success = true; - } - else + private void OneFingerTransformedHandler(object sender, System.EventArgs e) + { + RaycastHit hitToFire3D = default(RaycastHit); + RaycastHit2D hitToFire2D = default(RaycastHit2D); +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + RaycastResult hitToFire2DEventSystem = default(RaycastResult); +#endif + + //Log.Status ("TouchEventManager", "oneFingerManipulationTransformedHandler: {0}", m_OneFingerMoveGesture.DeltaPosition); + if (m_Active) + { + TouchEventData dragEventToFire = null; + Vector3 oneFingerScreenPosition = m_OneFingerMoveGesture.ScreenPosition; + Ray rayForDrag = MainCamera.ScreenPointToRay(oneFingerScreenPosition); + + foreach (var kp in m_DragEvents) + { + if (kp.Key == 1) + { + //Adding Variables for 3D Touch Check + Transform hitTransform3D = null; + RaycastHit hit3D = default(RaycastHit); + bool isHitOnLayer3D = Physics.Raycast(rayForDrag, out hit3D, Mathf.Infinity, kp.Key); + if (isHitOnLayer3D) { - Log.Warning("TouchEventManager", "There is no callback for drag event registration"); + hitTransform3D = hit3D.collider.transform; } - return success; - } - - /// - /// Unregisters the drag event. - /// - /// true, if drag event was unregistered, false otherwise. - /// Game object to drag. - /// Callback. - /// Number of finger. - /// Sorting layer. - /// If set to true is drag inside. - public bool UnregisterDragEvent(GameObject gameObjectToDrag, string callback, int numberOfFinger = 1, int SortingLayer = 0, bool isDragInside = true) - { - bool success = false; + //Adding Variables for 2D Touch Check for 2d Colliders + Transform hitTransform2D = null; + RaycastHit2D hit2D = Physics2D.Raycast(rayForDrag.origin, rayForDrag.direction, Mathf.Infinity, kp.Key); + bool isHitOnLayer2D = false; + if (hit2D.collider != null) + { + isHitOnLayer2D = true; + hitTransform2D = hit2D.collider.transform; + } - if (!string.IsNullOrEmpty(callback)) +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //Adding Variables for Event.System Touch for UI Elements + Transform hitTransform2DEventSystem = null; + bool isHitOnLayer2DEventSystem = false; + RaycastResult hit2DEventSystem = default(RaycastResult); + if (EventSystem.current != null) { - if (m_DragEvents.ContainsKey(numberOfFinger)) + PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); + pointerEventForTap.position = oneFingerScreenPosition; + List raycastResultListFor2DEventSystem = new List(); + EventSystem.current.RaycastAll(pointerEventForTap, raycastResultListFor2DEventSystem); + foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) + { + + isHitOnLayer2DEventSystem = kp.Value.Exists(element => (element.GameObjectAttached != null && element.GameObjectAttached.activeSelf && element.GameObjectAttached.layer == itemRaycastResult.gameObject.layer)); + if (isHitOnLayer2DEventSystem) { - int numberOfRemovedCallbacks = m_DragEvents[numberOfFinger].RemoveAll( - e => - e.GameObjectAttached == gameObjectToDrag && - e.DragCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isDragInside); - - success &= (numberOfRemovedCallbacks > 0); + hit2DEventSystem = itemRaycastResult; + hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; + break; } + } } - else - { - Log.Warning("TouchEventManager", "There is no callback for drag event unregistration"); - } - return success; - } +#endif - - private void OneFingerTransformedHandler(object sender, System.EventArgs e) - { - RaycastHit hitToFire3D = default(RaycastHit); - RaycastHit2D hitToFire2D = default(RaycastHit2D); - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - RaycastResult hitToFire2DEventSystem = default(RaycastResult); - #endif - - //Log.Status ("TouchEventManager", "oneFingerManipulationTransformedHandler: {0}", m_OneFingerMoveGesture.DeltaPosition); - if (m_Active) + for (int i = 0; i < kp.Value.Count; ++i) { - TouchEventData dragEventToFire = null; - Vector3 oneFingerScreenPosition = m_OneFingerMoveGesture.ScreenPosition; - Ray rayForDrag = MainCamera.ScreenPointToRay(oneFingerScreenPosition); - - foreach (var kp in m_DragEvents) + TouchEventData dragEventData = kp.Value[i]; + + if (kp.Value[i].ColliderList == null && kp.Value[i].ColliderList2D == null && kp.Value[i].RectTransformList == null) + { + Log.Warning("TouchEventManager", "Removing invalid collider event receiver from OneFingerDrag"); + kp.Value.RemoveAt(i--); + continue; + } + + if (string.IsNullOrEmpty(dragEventData.DragCallback)) + { + Log.Warning("TouchEventManager", "Removing invalid event receiver from OneFingerDrag"); + kp.Value.RemoveAt(i--); + continue; + } + + //If we can drag the object, we should check that whether there is a raycast or not! + + //3d Hit Check + if (dragEventData.ColliderList != null && dragEventData.ColliderList.Length > 0) + { + if (dragEventData.IsInside && isHitOnLayer3D && Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf)) { - if (kp.Key == 1) - { - //Adding Variables for 3D Touch Check - Transform hitTransform3D = null; - RaycastHit hit3D = default(RaycastHit); - bool isHitOnLayer3D = Physics.Raycast(rayForDrag, out hit3D, Mathf.Infinity, kp.Key); - if (isHitOnLayer3D) - { - hitTransform3D = hit3D.collider.transform; - } - - //Adding Variables for 2D Touch Check for 2d Colliders - Transform hitTransform2D = null; - RaycastHit2D hit2D = Physics2D.Raycast(rayForDrag.origin, rayForDrag.direction, Mathf.Infinity, kp.Key); - bool isHitOnLayer2D = false; - if (hit2D.collider != null) - { - isHitOnLayer2D = true; - hitTransform2D = hit2D.collider.transform; - } - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //Adding Variables for Event.System Touch for UI Elements - Transform hitTransform2DEventSystem = null; - bool isHitOnLayer2DEventSystem = false; - RaycastResult hit2DEventSystem = default(RaycastResult); - if (EventSystem.current != null) - { - PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); - pointerEventForTap.position = oneFingerScreenPosition; - List raycastResultListFor2DEventSystem = new List(); - EventSystem.current.RaycastAll (pointerEventForTap, raycastResultListFor2DEventSystem); - foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) - { - - isHitOnLayer2DEventSystem = kp.Value.Exists(element => (element.GameObjectAttached != null && element.GameObjectAttached.activeSelf && element.GameObjectAttached.layer == itemRaycastResult.gameObject.layer)); - if (isHitOnLayer2DEventSystem) - { - hit2DEventSystem = itemRaycastResult; - hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; - break; - } - } - } - #endif - - for (int i = 0; i < kp.Value.Count; ++i) - { - TouchEventData dragEventData = kp.Value[i]; - - if (kp.Value[i].ColliderList == null && kp.Value[i].ColliderList2D == null && kp.Value[i].RectTransformList == null ) - { - Log.Warning("TouchEventManager", "Removing invalid collider event receiver from OneFingerDrag"); - kp.Value.RemoveAt(i--); - continue; - } - - if (string.IsNullOrEmpty(dragEventData.DragCallback)) - { - Log.Warning("TouchEventManager", "Removing invalid event receiver from OneFingerDrag"); - kp.Value.RemoveAt(i--); - continue; - } - - //If we can drag the object, we should check that whether there is a raycast or not! - - //3d Hit Check - if (dragEventData.ColliderList != null && dragEventData.ColliderList.Length > 0) - { - if (dragEventData.IsInside && isHitOnLayer3D && Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf)) - { - //Tapped inside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - #if ENABLE_DEBUGGING + //Tapped inside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - OneFingerDrag Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - OneFingerDrag Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if ( !dragEventData.IsInside && (!isHitOnLayer3D || !Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf))) - { - //Tapped outside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if (!dragEventData.IsInside && (!isHitOnLayer3D || !Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf))) + { + //Tapped outside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - OneFingerDrag Event Found 3D - outside. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - OneFingerDrag Event Found 3D - outside. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - //2d Hit Check - if (dragEventData.ColliderList2D != null && dragEventData.ColliderList2D.Length > 0) - { - if (dragEventData.IsInside && isHitOnLayer2D && Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf)) - { - //Tapped inside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + + //2d Hit Check + if (dragEventData.ColliderList2D != null && dragEventData.ColliderList2D.Length > 0) + { + if (dragEventData.IsInside && isHitOnLayer2D && Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf)) + { + //Tapped inside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - OneFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - OneFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if (!dragEventData.IsInside && (!isHitOnLayer2D || !Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf))) - { - //Tapped outside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if (!dragEventData.IsInside && (!isHitOnLayer2D || !Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf))) + { + //Tapped outside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - OneFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - OneFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //2D UI Hit Check using EventSystem - if (dragEventData.RectTransformList != null && dragEventData.RectTransformList.Length > 0) - { - if (dragEventData.IsInside && isHitOnLayer2DEventSystem && Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf)) - { - //Tapped inside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //2D UI Hit Check using EventSystem + if (dragEventData.RectTransformList != null && dragEventData.RectTransformList.Length > 0) + { + if (dragEventData.IsInside && isHitOnLayer2DEventSystem && Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf)) + { + //Tapped inside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - OneFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - OneFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - //do nothing - } - } - - } else if ( !dragEventData.IsInside && (!isHitOnLayer2DEventSystem || !Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf) )) - { - //Tapped outside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if (!dragEventData.IsInside && (!isHitOnLayer2DEventSystem || !Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf))) + { + //Tapped outside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - OneFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - OneFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - //do nothing - } - } - } else - { - //do nothing - } - } - #endif - } +#endif } + else + { + //do nothing + } + } } - - if (dragEventToFire != null) - EventManager.Instance.SendEvent(dragEventToFire.DragCallback, m_OneFingerMoveGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); - - EventManager.Instance.SendEvent("OnDragOneFingerFullscreen", m_OneFingerMoveGesture); + else + { + //do nothing + } + } +#endif } + } } - private void TwoFingerTransformedHandler(object sender, System.EventArgs e) + if (dragEventToFire != null) + EventManager.Instance.SendEvent(dragEventToFire.DragCallback, m_OneFingerMoveGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); + + EventManager.Instance.SendEvent("OnDragOneFingerFullscreen", m_OneFingerMoveGesture); + } + } + + private void TwoFingerTransformedHandler(object sender, System.EventArgs e) + { + RaycastHit hitToFire3D = default(RaycastHit); + RaycastHit2D hitToFire2D = default(RaycastHit2D); +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + RaycastResult hitToFire2DEventSystem = default(RaycastResult); +#endif + + //Log.Status ("TouchEventManager", "TwoFingerTransformedHandler: {0}", m_TwoFingerMoveGesture.DeltaPosition); + if (m_Active) + { + TouchEventData dragEventToFire = null; + Vector3 twoFingerScreenPosition = m_TwoFingerMoveGesture.ScreenPosition; + Ray rayForDrag = MainCamera.ScreenPointToRay(twoFingerScreenPosition); + + + foreach (var kp in m_DragEvents) { - RaycastHit hitToFire3D = default(RaycastHit); - RaycastHit2D hitToFire2D = default(RaycastHit2D); - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - RaycastResult hitToFire2DEventSystem = default(RaycastResult); - #endif - - //Log.Status ("TouchEventManager", "TwoFingerTransformedHandler: {0}", m_TwoFingerMoveGesture.DeltaPosition); - if (m_Active) + if (kp.Key == 2) + { + //Adding Variables for 3D Touch Check + Transform hitTransform3D = null; + RaycastHit hit3D = default(RaycastHit); + bool isHitOnLayer3D = Physics.Raycast(rayForDrag, out hit3D, Mathf.Infinity, kp.Key); + if (isHitOnLayer3D) + { + hitTransform3D = hit3D.collider.transform; + } + + //Adding Variables for 2D Touch Check for 2d Colliders + Transform hitTransform2D = null; + RaycastHit2D hit2D = Physics2D.Raycast(rayForDrag.origin, rayForDrag.direction, Mathf.Infinity, kp.Key); + bool isHitOnLayer2D = false; + if (hit2D.collider != null) { - TouchEventData dragEventToFire = null; - Vector3 twoFingerScreenPosition = m_TwoFingerMoveGesture.ScreenPosition; - Ray rayForDrag = MainCamera.ScreenPointToRay(twoFingerScreenPosition); + isHitOnLayer2D = true; + hitTransform2D = hit2D.collider.transform; + } +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //Adding Variables for Event.System Touch for UI Elements + Transform hitTransform2DEventSystem = null; + bool isHitOnLayer2DEventSystem = false; + RaycastResult hit2DEventSystem = default(RaycastResult); + if (EventSystem.current != null) + { + PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); + pointerEventForTap.position = twoFingerScreenPosition; + List raycastResultListFor2DEventSystem = new List(); + EventSystem.current.RaycastAll(pointerEventForTap, raycastResultListFor2DEventSystem); + foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) + { + + isHitOnLayer2DEventSystem = kp.Value.Exists(element => (element.GameObjectAttached != null && element.GameObjectAttached.layer == itemRaycastResult.gameObject.layer)); + if (isHitOnLayer2DEventSystem) + { + hit2DEventSystem = itemRaycastResult; + hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; + break; + } + } + } +#endif - foreach (var kp in m_DragEvents) + for (int i = 0; i < kp.Value.Count; ++i) + { + TouchEventData dragEventData = kp.Value[i]; + + if (kp.Value[i].ColliderList == null && kp.Value[i].ColliderList2D == null && kp.Value[i].RectTransformList == null) + { + Log.Warning("TouchEventManager", "Removing invalid collider event receiver from TwoFingerDrag"); + kp.Value.RemoveAt(i--); + continue; + } + + if (string.IsNullOrEmpty(dragEventData.DragCallback)) + { + Log.Warning("TouchEventManager", "Removing invalid event receiver from TwoFingerDrag"); + kp.Value.RemoveAt(i--); + continue; + } + + //If we can drag the object, we should check that whether there is a raycast or not! + + //3d Hit Check + if (dragEventData.ColliderList != null && dragEventData.ColliderList.Length > 0) + { + if (dragEventData.IsInside && isHitOnLayer3D && Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf)) { - if (kp.Key == 2) - { - //Adding Variables for 3D Touch Check - Transform hitTransform3D = null; - RaycastHit hit3D = default(RaycastHit); - bool isHitOnLayer3D = Physics.Raycast(rayForDrag, out hit3D, Mathf.Infinity, kp.Key); - if (isHitOnLayer3D) - { - hitTransform3D = hit3D.collider.transform; - } - - //Adding Variables for 2D Touch Check for 2d Colliders - Transform hitTransform2D = null; - RaycastHit2D hit2D = Physics2D.Raycast(rayForDrag.origin, rayForDrag.direction, Mathf.Infinity, kp.Key); - bool isHitOnLayer2D = false; - if (hit2D.collider != null) - { - isHitOnLayer2D = true; - hitTransform2D = hit2D.collider.transform; - } - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //Adding Variables for Event.System Touch for UI Elements - Transform hitTransform2DEventSystem = null; - bool isHitOnLayer2DEventSystem = false; - RaycastResult hit2DEventSystem = default(RaycastResult); - if (EventSystem.current != null) - { - PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); - pointerEventForTap.position = twoFingerScreenPosition; - List raycastResultListFor2DEventSystem = new List(); - EventSystem.current.RaycastAll (pointerEventForTap, raycastResultListFor2DEventSystem); - foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) - { - - isHitOnLayer2DEventSystem = kp.Value.Exists(element => (element.GameObjectAttached != null && element.GameObjectAttached.layer == itemRaycastResult.gameObject.layer)); - if (isHitOnLayer2DEventSystem) - { - hit2DEventSystem = itemRaycastResult; - hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; - break; - } - } - } - #endif - - for (int i = 0; i < kp.Value.Count; ++i) - { - TouchEventData dragEventData = kp.Value[i]; - - if (kp.Value[i].ColliderList == null && kp.Value[i].ColliderList2D == null && kp.Value[i].RectTransformList == null ) - { - Log.Warning("TouchEventManager", "Removing invalid collider event receiver from TwoFingerDrag"); - kp.Value.RemoveAt(i--); - continue; - } - - if (string.IsNullOrEmpty(dragEventData.DragCallback)) - { - Log.Warning("TouchEventManager", "Removing invalid event receiver from TwoFingerDrag"); - kp.Value.RemoveAt(i--); - continue; - } - - //If we can drag the object, we should check that whether there is a raycast or not! - - //3d Hit Check - if (dragEventData.ColliderList != null && dragEventData.ColliderList.Length > 0) - { - if (dragEventData.IsInside && isHitOnLayer3D && Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf)) - { - //Tapped inside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - #if ENABLE_DEBUGGING + //Tapped inside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - TwoFingerDrag Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - TwoFingerDrag Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if ( !dragEventData.IsInside && (!isHitOnLayer3D || !Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf))) - { - //Tapped outside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if (!dragEventData.IsInside && (!isHitOnLayer3D || !Array.Exists(dragEventData.ColliderList, element => element.transform == hitTransform3D && element.gameObject.activeSelf))) + { + //Tapped outside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - TwoFingerDrag Event Found 3D - outside. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - TwoFingerDrag Event Found 3D - outside. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - //2d Hit Check - if (dragEventData.ColliderList2D != null && dragEventData.ColliderList2D.Length > 0) - { - if (dragEventData.IsInside && isHitOnLayer2D && Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf)) - { - //Tapped inside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + + //2d Hit Check + if (dragEventData.ColliderList2D != null && dragEventData.ColliderList2D.Length > 0) + { + if (dragEventData.IsInside && isHitOnLayer2D && Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf)) + { + //Tapped inside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - TwoFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - TwoFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if (!dragEventData.IsInside && (!isHitOnLayer2D || !Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf))) - { - //Tapped outside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if (!dragEventData.IsInside && (!isHitOnLayer2D || !Array.Exists(dragEventData.ColliderList2D, element => element.transform == hitTransform2D && element.gameObject.activeSelf))) + { + //Tapped outside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - TwoFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - TwoFingerDrag Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //2D UI Hit Check using EventSystem - if (dragEventData.RectTransformList != null && dragEventData.RectTransformList.Length > 0) - { - if (dragEventData.IsInside && isHitOnLayer2DEventSystem && Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf)) - { - //Tapped inside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //2D UI Hit Check using EventSystem + if (dragEventData.RectTransformList != null && dragEventData.RectTransformList.Length > 0) + { + if (dragEventData.IsInside && isHitOnLayer2DEventSystem && Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf)) + { + //Tapped inside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - TwoFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || - (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer || + (dragEventToFire.SortingLayer == dragEventData.SortingLayer && !dragEventToFire.IsInside)) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Inside - TwoFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - //do nothing - } - } - - } else if ( !dragEventData.IsInside && (!isHitOnLayer2DEventSystem || !Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf) )) - { - //Tapped outside the object - if (dragEventToFire == null) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if (!dragEventData.IsInside && (!isHitOnLayer2DEventSystem || !Array.Exists(dragEventData.RectTransformList, element => element.transform == hitTransform2DEventSystem && element.gameObject.activeSelf))) + { + //Tapped outside the object + if (dragEventToFire == null) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - TwoFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) - { - dragEventToFire = dragEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (dragEventData.SortingLayer > dragEventToFire.SortingLayer) + { + dragEventToFire = dragEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Outside - TwoFingerDrag Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, dragEventData.DragCallback, dragEventData.SortingLayer, dragEventData.IsInside); - #endif - } else - { - //do nothing - } - } - } else - { - //do nothing - } - } - #endif - } +#endif + } + else + { + //do nothing } + } } - - if (dragEventToFire != null) - EventManager.Instance.SendEvent(dragEventToFire.DragCallback, m_TwoFingerMoveGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); - - EventManager.Instance.SendEvent("OnDragTwoFingerFullscreen", m_TwoFingerMoveGesture); + else + { + //do nothing + } + } +#endif } + } } - #endregion - - #region TapEvents - Register / UnRegister / Call - /// - /// Registers the tap event. - /// 3d Colliders is the first priority - /// 2d Collider is the second priority - /// 2d UI Event System is the third priority - /// If object has 3d collider, and 2d collider and an UI element. - /// Touch is checking by priority order. - /// - /// true, if tap event was registered, false otherwise. - /// Game object to touch. - /// Callback. - /// Sorting layer. - /// If set to true is tap inside. - /// Layer mask. - public bool RegisterTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isTapInside = true, LayerMask layerMask = default(LayerMask)) + + if (dragEventToFire != null) + EventManager.Instance.SendEvent(dragEventToFire.DragCallback, m_TwoFingerMoveGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); + + EventManager.Instance.SendEvent("OnDragTwoFingerFullscreen", m_TwoFingerMoveGesture); + } + } + #endregion + + #region TapEvents - Register / UnRegister / Call + /// + /// Registers the tap event. + /// 3d Colliders is the first priority + /// 2d Collider is the second priority + /// 2d UI Event System is the third priority + /// If object has 3d collider, and 2d collider and an UI element. + /// Touch is checking by priority order. + /// + /// true, if tap event was registered, false otherwise. + /// Game object to touch. + /// Callback. + /// Sorting layer. + /// If set to true is tap inside. + /// Layer mask. + public bool RegisterTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isTapInside = true, LayerMask layerMask = default(LayerMask)) + { + bool success = false; + + if (gameObjectToTouch != null) + { + if (!string.IsNullOrEmpty(callback)) { - bool success = false; + Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(); - if (gameObjectToTouch != null) + if (colliderList != null && colliderList.Length > 0) + { + foreach (Collider itemCollider in colliderList) { - if (!string.IsNullOrEmpty(callback)) - { - Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(); - - if (colliderList != null && colliderList.Length > 0) - { - foreach (Collider itemCollider in colliderList) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - #if ENABLE_DEBUGGING +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "RegisterTapEvent for 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemCollider, callback, SortingLayer, isTapInside); - #endif - - if (m_TapEvents.ContainsKey(layerMaskAsKey)) - { - m_TapEvents[layerMaskAsKey].Add(new TouchEventData(itemCollider, callback, SortingLayer, isTapInside)); - } - else - { - m_TapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemCollider, callback, SortingLayer, isTapInside) }; - } - } - - success = true; - } - else - { - #if ENABLE_DEBUGGING +#endif + + if (m_TapEvents.ContainsKey(layerMaskAsKey)) + { + m_TapEvents[layerMaskAsKey].Add(new TouchEventData(itemCollider, callback, SortingLayer, isTapInside)); + } + else + { + m_TapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemCollider, callback, SortingLayer, isTapInside) }; + } + } + + success = true; + } + else + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "There is no 3D collider of given gameobjectToTouch"); - #endif - } +#endif + } - if (!success) - { - Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren (); - if (colliderList2D != null && colliderList2D.Length > 0) - { - foreach (Collider2D itemCollider in colliderList2D) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - - #if ENABLE_DEBUGGING + if (!success) + { + Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren(); + if (colliderList2D != null && colliderList2D.Length > 0) + { + foreach (Collider2D itemCollider in colliderList2D) + { + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "RegisterTapEvent For 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemCollider, callback, SortingLayer, isTapInside); - #endif - - if (m_TapEvents.ContainsKey (layerMaskAsKey)) - { - m_TapEvents [layerMaskAsKey].Add (new TouchEventData (itemCollider, callback, SortingLayer, isTapInside)); - } else - { - m_TapEvents [layerMaskAsKey] = new List () { new TouchEventData (itemCollider, callback, SortingLayer, isTapInside) }; - } - } - - success = true; - } else - { - #if ENABLE_DEBUGGING - Log.Debug ("TouchEventManager", "There is no 2D collider of given gameobjectToTouch"); - #endif - } - } - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - if (!success) - { - RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren (includeInactive: true); - if (rectTransformList != null && rectTransformList.Length > 0) - { - foreach (RectTransform itemRectTransform in rectTransformList) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << itemRectTransform.gameObject.layer); - - #if ENABLE_DEBUGGING +#endif + + if (m_TapEvents.ContainsKey(layerMaskAsKey)) + { + m_TapEvents[layerMaskAsKey].Add(new TouchEventData(itemCollider, callback, SortingLayer, isTapInside)); + } + else + { + m_TapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemCollider, callback, SortingLayer, isTapInside) }; + } + } + + success = true; + } + else + { +#if ENABLE_DEBUGGING + Log.Debug ("TouchEventManager", "There is no 2D collider of given gameobjectToTouch"); +#endif + } + } +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + if (!success) + { + RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (rectTransformList != null && rectTransformList.Length > 0) + { + foreach (RectTransform itemRectTransform in rectTransformList) + { + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << itemRectTransform.gameObject.layer); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "RegisterTapEvent For 2D Event System. itemRectTransform: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemRectTransform, callback, SortingLayer, isTapInside); - #endif - - if (m_TapEvents.ContainsKey (layerMaskAsKey)) - { - m_TapEvents [layerMaskAsKey].Add (new TouchEventData (itemRectTransform, callback, SortingLayer, isTapInside)); - } else - { - m_TapEvents [layerMaskAsKey] = new List () { new TouchEventData (itemRectTransform, callback, SortingLayer, isTapInside) }; - } - } - - success = true; - } else - { - #if ENABLE_DEBUGGING - Log.Debug ("TouchEventManager", "There is no Rect Transform of given gameobjectToTouch"); - #endif - } - } - #endif +#endif + if (m_TapEvents.ContainsKey(layerMaskAsKey)) + { + m_TapEvents[layerMaskAsKey].Add(new TouchEventData(itemRectTransform, callback, SortingLayer, isTapInside)); } else { - Log.Warning("TouchEventManager", "There is no callback for tap event registration"); + m_TapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemRectTransform, callback, SortingLayer, isTapInside) }; } + } + + success = true; } else { - Log.Warning("TouchEventManager", "There is no gameobject for tap event registration"); +#if ENABLE_DEBUGGING + Log.Debug ("TouchEventManager", "There is no Rect Transform of given gameobjectToTouch"); +#endif } + } +#endif - return success; } + else + { + Log.Warning("TouchEventManager", "There is no callback for tap event registration"); + } + } + else + { + Log.Warning("TouchEventManager", "There is no gameobject for tap event registration"); + } + + return success; + } + + /// + /// Unregisters the tap event. + /// + /// true, if tap event was unregistered, false otherwise. + /// Game object to touch. + /// Callback. + /// Sorting layer. + /// If set to true is tap inside. + /// Layer mask. + public bool UnregisterTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isTapInside = true, LayerMask layerMask = default(LayerMask)) + { + bool success = false; - /// - /// Unregisters the tap event. - /// - /// true, if tap event was unregistered, false otherwise. - /// Game object to touch. - /// Callback. - /// Sorting layer. - /// If set to true is tap inside. - /// Layer mask. - public bool UnregisterTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isTapInside = true, LayerMask layerMask = default(LayerMask)) + if (gameObjectToTouch != null) + { + if (!string.IsNullOrEmpty(callback)) { - bool success = false; + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - if (gameObjectToTouch != null) + if (m_TapEvents.ContainsKey(layerMaskAsKey)) + { + success = true; + Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (colliderList != null && colliderList.Length > 0) { - if (!string.IsNullOrEmpty(callback)) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); + foreach (Collider itemCollider in colliderList) + { + int numberOfRemovedCallbacks = m_TapEvents[layerMaskAsKey].RemoveAll( + e => + e.Collider == itemCollider && + e.TapCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isTapInside); + + success &= (numberOfRemovedCallbacks > 0); + } + } + else + { + success = false; + } - if (m_TapEvents.ContainsKey(layerMaskAsKey)) - { - success = true; - Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); - if (colliderList != null && colliderList.Length > 0) - { - foreach (Collider itemCollider in colliderList) - { - int numberOfRemovedCallbacks = m_TapEvents[layerMaskAsKey].RemoveAll( - e => - e.Collider == itemCollider && - e.TapCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isTapInside); - - success &= (numberOfRemovedCallbacks > 0); - } - } - else - { - success = false; - } - - if (!success) - { - success = true; - Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); - if (colliderList2D != null && colliderList2D.Length > 0) - { - foreach (Collider2D itemCollider2D in colliderList2D) - { - int numberOfRemovedCallbacks = m_TapEvents[layerMaskAsKey].RemoveAll( - e => - e.Collider2D == itemCollider2D && - e.TapCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isTapInside); - - success &= (numberOfRemovedCallbacks > 0); - } - } - else - { - success = false; - } - } - - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - if (!success) - { - success = true; - RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren (includeInactive: true); - if (rectTransformList != null && rectTransformList.Length > 0) - { - foreach (RectTransform itemRectTransform in rectTransformList) - { - int numberOfRemovedCallbacks = m_TapEvents[layerMaskAsKey].RemoveAll( - e => - e.RectTransform == itemRectTransform && - e.TapCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isTapInside); - - success &= (numberOfRemovedCallbacks > 0); - } - } - else - { - success = false; - } - } - #endif - } - } - else + if (!success) + { + success = true; + Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (colliderList2D != null && colliderList2D.Length > 0) + { + foreach (Collider2D itemCollider2D in colliderList2D) { - Log.Warning("TouchEventManager", "There is no callback for tap event unregistration"); + int numberOfRemovedCallbacks = m_TapEvents[layerMaskAsKey].RemoveAll( + e => + e.Collider2D == itemCollider2D && + e.TapCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isTapInside); + + success &= (numberOfRemovedCallbacks > 0); } + } + else + { + success = false; + } } - else + + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + if (!success) { - Log.Warning("TouchEventManager", "There is no gameobject for tap event unregistration"); + success = true; + RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (rectTransformList != null && rectTransformList.Length > 0) + { + foreach (RectTransform itemRectTransform in rectTransformList) + { + int numberOfRemovedCallbacks = m_TapEvents[layerMaskAsKey].RemoveAll( + e => + e.RectTransform == itemRectTransform && + e.TapCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isTapInside); + + success &= (numberOfRemovedCallbacks > 0); + } + } + else + { + success = false; + } } - - return success; +#endif + } } - - private void TapGesture_Tapped(object sender, System.EventArgs e) + else { - if (m_Active) - { - #if ENABLE_DEBUGGING + Log.Warning("TouchEventManager", "There is no callback for tap event unregistration"); + } + } + else + { + Log.Warning("TouchEventManager", "There is no gameobject for tap event unregistration"); + } + + return success; + } + + private void TapGesture_Tapped(object sender, System.EventArgs e) + { + if (m_Active) + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "TapGesture_Tapped: {0} - {1}", m_TapGesture.ScreenPosition, m_TapGesture.NumTouches); - #endif +#endif - TouchEventData tapEventToFire = null; + TouchEventData tapEventToFire = null; - RaycastHit hitToFire3D = default(RaycastHit); - RaycastHit2D hitToFire2D = default(RaycastHit2D); - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - RaycastResult hitToFire2DEventSystem = default(RaycastResult); - #endif + RaycastHit hitToFire3D = default(RaycastHit); + RaycastHit2D hitToFire2D = default(RaycastHit2D); +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + RaycastResult hitToFire2DEventSystem = default(RaycastResult); +#endif - foreach (var kp in m_TapEvents) - { - //Adding Variables for 3D Tap Check - Ray rayForTab = MainCamera.ScreenPointToRay(m_TapGesture.ScreenPosition); - Transform hitTransform3D = null; - RaycastHit hit3D = default(RaycastHit); - bool isHitOnLayer3D = Physics.Raycast(rayForTab, out hit3D, Mathf.Infinity, kp.Key); - if (isHitOnLayer3D) - { - hitTransform3D = hit3D.collider.transform; - } + foreach (var kp in m_TapEvents) + { + //Adding Variables for 3D Tap Check + Ray rayForTab = MainCamera.ScreenPointToRay(m_TapGesture.ScreenPosition); + Transform hitTransform3D = null; + RaycastHit hit3D = default(RaycastHit); + bool isHitOnLayer3D = Physics.Raycast(rayForTab, out hit3D, Mathf.Infinity, kp.Key); + if (isHitOnLayer3D) + { + hitTransform3D = hit3D.collider.transform; + } + + //Adding Variables for 2D Tap Check for 2d Colliders + Transform hitTransform2D = null; + RaycastHit2D hit2D = Physics2D.Raycast(rayForTab.origin, rayForTab.direction, Mathf.Infinity, kp.Key); + bool isHitOnLayer2D = false; + if (hit2D.collider != null) + { + isHitOnLayer2D = true; + hitTransform2D = hit2D.collider.transform; + } + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //Adding Variables for Event.System Tap for UI Elements + Transform hitTransform2DEventSystem = null; + bool isHitOnLayer2DEventSystem = false; + RaycastResult hit2DEventSystem = default(RaycastResult); + if (EventSystem.current != null) + { + PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); + pointerEventForTap.position = m_TapGesture.ScreenPosition; + List raycastResultListFor2DEventSystem = new List(); + EventSystem.current.RaycastAll(pointerEventForTap, raycastResultListFor2DEventSystem); + foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) + { + LayerMask layerMaskOfItem = 1 << itemRaycastResult.gameObject.layer; + isHitOnLayer2DEventSystem = ((layerMaskOfItem.value & kp.Key) == layerMaskOfItem.value); + + if (isHitOnLayer2DEventSystem) + { + hit2DEventSystem = itemRaycastResult; + hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; + break; + } + } + } +#endif - //Adding Variables for 2D Tap Check for 2d Colliders - Transform hitTransform2D = null; - RaycastHit2D hit2D = Physics2D.Raycast(rayForTab.origin, rayForTab.direction, Mathf.Infinity, kp.Key); - bool isHitOnLayer2D = false; - if (hit2D.collider != null) - { - isHitOnLayer2D = true; - hitTransform2D = hit2D.collider.transform; - } - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //Adding Variables for Event.System Tap for UI Elements - Transform hitTransform2DEventSystem = null; - bool isHitOnLayer2DEventSystem = false; - RaycastResult hit2DEventSystem = default(RaycastResult); - if (EventSystem.current != null) - { - PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); - pointerEventForTap.position = m_TapGesture.ScreenPosition; - List raycastResultListFor2DEventSystem = new List(); - EventSystem.current.RaycastAll (pointerEventForTap, raycastResultListFor2DEventSystem); - foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) - { - LayerMask layerMaskOfItem = 1 << itemRaycastResult.gameObject.layer; - isHitOnLayer2DEventSystem = ((layerMaskOfItem.value & kp.Key) == layerMaskOfItem.value); - - if (isHitOnLayer2DEventSystem) - { - hit2DEventSystem = itemRaycastResult; - hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; - break; - } - } - } - #endif + for (int i = 0; i < kp.Value.Count; ++i) + { + TouchEventData tapEventData = kp.Value[i]; + + if (kp.Value[i].Collider == null && kp.Value[i].Collider2D == null && kp.Value[i].RectTransform == null && kp.Value[i].RectTransformList == null) + { + Log.Warning("TouchEventManager", "Removing invalid collider event receiver from TapEventList from {0}", kp.Value[i].ToString()); + kp.Value.RemoveAt(i--); + continue; + } + if (string.IsNullOrEmpty(tapEventData.TapCallback)) + { + Log.Warning("TouchEventManager", "Removing invalid event receiver from TapEventList {0}", kp.Value[i]); + kp.Value.RemoveAt(i--); + continue; + } - for (int i = 0; i < kp.Value.Count; ++i) - { - TouchEventData tapEventData = kp.Value[i]; - - if (kp.Value[i].Collider == null && kp.Value[i].Collider2D == null && kp.Value[i].RectTransform == null && kp.Value[i].RectTransformList == null ) - { - Log.Warning("TouchEventManager", "Removing invalid collider event receiver from TapEventList from {0}", kp.Value[i].ToString()); - kp.Value.RemoveAt(i--); - continue; - } - - if (string.IsNullOrEmpty(tapEventData.TapCallback)) - { - Log.Warning("TouchEventManager", "Removing invalid event receiver from TapEventList {0}", kp.Value[i]); - kp.Value.RemoveAt(i--); - continue; - } - - //3d Hit Check - if (tapEventData.Collider != null) - { - if (isHitOnLayer3D && hitTransform3D == tapEventData.Collider.transform && tapEventData.IsInside) - { - //Tapped inside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - #if ENABLE_DEBUGGING + //3d Hit Check + if (tapEventData.Collider != null) + { + if (isHitOnLayer3D && hitTransform3D == tapEventData.Collider.transform && tapEventData.IsInside) + { + //Tapped inside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || - (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || + (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if ((!isHitOnLayer3D || hitTransform3D != tapEventData.Collider.transform) && !tapEventData.IsInside) - { - //Tapped outside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if ((!isHitOnLayer3D || hitTransform3D != tapEventData.Collider.transform) && !tapEventData.IsInside) + { + //Tapped outside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - //2d Hit Check - if (tapEventData.Collider2D != null) - { - if (isHitOnLayer2D && hitTransform2D == tapEventData.Collider2D.transform && tapEventData.IsInside) - { - //Tapped inside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + + //2d Hit Check + if (tapEventData.Collider2D != null) + { + if (isHitOnLayer2D && hitTransform2D == tapEventData.Collider2D.transform && tapEventData.IsInside) + { + //Tapped inside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || - (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || + (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if ((!isHitOnLayer2D || hitTransform2D != tapEventData.Collider2D.transform) && !tapEventData.IsInside) - { - //Tapped outside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if ((!isHitOnLayer2D || hitTransform2D != tapEventData.Collider2D.transform) && !tapEventData.IsInside) + { + //Tapped outside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //2D UI Hit Check using EventSystem - if (tapEventData.RectTransform != null) - { - if (isHitOnLayer2DEventSystem && hitTransform2DEventSystem == tapEventData.RectTransform.transform && tapEventData.IsInside) - { - //Tapped inside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING - Log.Debug("TouchEventManager", "Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || - (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING - Log.Debug("TouchEventManager", "Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - //do nothing - } - } - - } else if ((!isHitOnLayer2DEventSystem || hitTransform2DEventSystem != tapEventData.RectTransform.transform) && !tapEventData.IsInside) - { - //Tapped outside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //2D UI Hit Check using EventSystem + if (tapEventData.RectTransform != null) + { + if (isHitOnLayer2DEventSystem && hitTransform2DEventSystem == tapEventData.RectTransform.transform && tapEventData.IsInside) + { + //Tapped inside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || + (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - //do nothing - } - } - } else - { - //do nothing - } - } - #endif - - } +#endif + } + else + { + //do nothing + } } - if (tapEventToFire != null) - EventManager.Instance.SendEvent(tapEventToFire.TapCallback, m_TapGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); + } + else if ((!isHitOnLayer2DEventSystem || hitTransform2DEventSystem != tapEventData.RectTransform.transform) && !tapEventData.IsInside) + { + //Tapped outside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; - EventManager.Instance.SendEvent("OnSingleTap", m_TapGesture); +#if ENABLE_DEBUGGING + Log.Debug("TouchEventManager", "Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING + Log.Debug("TouchEventManager", "Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } } +#endif + + } } - #endregion - - #region Double TapEvents - Register / UnRegister / Call - /// - /// Registers the double tap event. - /// - /// true, if double tap event was registered, false otherwise. - /// Game object to touch. - /// Callback. - /// Sorting layer. - /// If set to true is double tap inside. - /// Layer mask. - public bool RegisterDoubleTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isDoubleTapInside = true, LayerMask layerMask = default(LayerMask)) + + if (tapEventToFire != null) + EventManager.Instance.SendEvent(tapEventToFire.TapCallback, m_TapGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); + + EventManager.Instance.SendEvent("OnSingleTap", m_TapGesture); + } + } + #endregion + + #region Double TapEvents - Register / UnRegister / Call + /// + /// Registers the double tap event. + /// + /// true, if double tap event was registered, false otherwise. + /// Game object to touch. + /// Callback. + /// Sorting layer. + /// If set to true is double tap inside. + /// Layer mask. + public bool RegisterDoubleTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isDoubleTapInside = true, LayerMask layerMask = default(LayerMask)) + { + bool success = false; + + if (gameObjectToTouch != null) + { + if (!string.IsNullOrEmpty(callback)) { - bool success = false; + Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(); - if (gameObjectToTouch != null) + if (colliderList != null && colliderList.Length > 0) + { + foreach (Collider itemCollider in colliderList) { - if (!string.IsNullOrEmpty(callback)) - { - Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(); - - if (colliderList != null && colliderList.Length > 0) - { - foreach (Collider itemCollider in colliderList) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - #if ENABLE_DEBUGGING +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "RegisterDoubleTapEvent for 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemCollider, callback, SortingLayer, isDoubleTapInside); - #endif - - if (m_DoubleTapEvents.ContainsKey(layerMaskAsKey)) - { - m_DoubleTapEvents[layerMaskAsKey].Add(new TouchEventData(itemCollider, callback, SortingLayer, isDoubleTapInside)); - } - else - { - m_DoubleTapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemCollider, callback, SortingLayer, isDoubleTapInside) }; - } - } - - success = true; - } - else - { - Log.Warning("TouchEventManager", "There is no 3D collider of given gameobjectToTouch (double-tap)"); - } +#endif + + if (m_DoubleTapEvents.ContainsKey(layerMaskAsKey)) + { + m_DoubleTapEvents[layerMaskAsKey].Add(new TouchEventData(itemCollider, callback, SortingLayer, isDoubleTapInside)); + } + else + { + m_DoubleTapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemCollider, callback, SortingLayer, isDoubleTapInside) }; + } + } - if (!success) - { - Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren (); - if (colliderList2D != null && colliderList2D.Length > 0) - { - foreach (Collider2D itemCollider in colliderList2D) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - - #if ENABLE_DEBUGGING - Log.Debug("TouchEventManager", "RegisterDoubleTapEvent For 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemCollider, callback, SortingLayer, isDoubleTapInside); - #endif - - if (m_DoubleTapEvents.ContainsKey (layerMaskAsKey)) - { - m_DoubleTapEvents [layerMaskAsKey].Add (new TouchEventData (itemCollider, callback, SortingLayer, isDoubleTapInside)); - } else - { - m_DoubleTapEvents [layerMaskAsKey] = new List () { new TouchEventData (itemCollider, callback, SortingLayer, isDoubleTapInside) }; - } - } - - success = true; - } else - { - Log.Warning ("TouchEventManager", "There is no 2D collider of given gameobjectToTouch (double-tap)"); - } - } + success = true; + } + else + { + Log.Warning("TouchEventManager", "There is no 3D collider of given gameobjectToTouch (double-tap)"); + } + + if (!success) + { + Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren(); + if (colliderList2D != null && colliderList2D.Length > 0) + { + foreach (Collider2D itemCollider in colliderList2D) + { + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - if (!success) - { - RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren (includeInactive: true); - if (rectTransformList != null && rectTransformList.Length > 0) - { - foreach (RectTransform itemRectTransform in rectTransformList) - { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << itemRectTransform.gameObject.layer); - - #if ENABLE_DEBUGGING - Log.Debug("TouchEventManager", "RegisterDoubleTapEvent For 2D Event System. itemRectTransform: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemRectTransform, callback, SortingLayer, isDoubleTapInside); - #endif - - if (m_DoubleTapEvents.ContainsKey (layerMaskAsKey)) - { - m_DoubleTapEvents [layerMaskAsKey].Add (new TouchEventData (itemRectTransform, callback, SortingLayer, isDoubleTapInside)); - } else - { - m_DoubleTapEvents [layerMaskAsKey] = new List () { new TouchEventData (itemRectTransform, callback, SortingLayer, isDoubleTapInside) }; - } - } - - success = true; - } else - { - Log.Warning ("TouchEventManager", "There is no Rect Transform of given gameobjectToTouch (double-tap)"); - } - } - #endif +#if ENABLE_DEBUGGING + Log.Debug("TouchEventManager", "RegisterDoubleTapEvent For 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemCollider, callback, SortingLayer, isDoubleTapInside); +#endif + if (m_DoubleTapEvents.ContainsKey(layerMaskAsKey)) + { + m_DoubleTapEvents[layerMaskAsKey].Add(new TouchEventData(itemCollider, callback, SortingLayer, isDoubleTapInside)); } else { - Log.Warning("TouchEventManager", "There is no callback for double-tap event registration"); + m_DoubleTapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemCollider, callback, SortingLayer, isDoubleTapInside) }; } + } + + success = true; } else { - Log.Warning("TouchEventManager", "There is no gameobject for double-tap event registration"); + Log.Warning("TouchEventManager", "There is no 2D collider of given gameobjectToTouch (double-tap)"); } + } - return success; - } +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + if (!success) + { + RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (rectTransformList != null && rectTransformList.Length > 0) + { + foreach (RectTransform itemRectTransform in rectTransformList) + { + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << itemRectTransform.gameObject.layer); - /// - /// Unregisters the double tap event. - /// - /// true, if double tap event was unregistered, false otherwise. - /// Game object to touch. - /// Callback. - /// Sorting layer. - /// If set to true is double tap inside. - /// Layer mask. - public bool UnregisterDoubleTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isDoubleTapInside = true, LayerMask layerMask = default(LayerMask)) - { - bool success = false; +#if ENABLE_DEBUGGING + Log.Debug("TouchEventManager", "RegisterDoubleTapEvent For 2D Event System. itemRectTransform: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3}",itemRectTransform, callback, SortingLayer, isDoubleTapInside); +#endif - if (gameObjectToTouch != null) - { - if (!string.IsNullOrEmpty(callback)) + if (m_DoubleTapEvents.ContainsKey(layerMaskAsKey)) { - int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); - - if (m_DoubleTapEvents.ContainsKey(layerMaskAsKey)) - { - success = true; - Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); - if (colliderList != null && colliderList.Length > 0) - { - foreach (Collider itemCollider in colliderList) - { - int numberOfRemovedCallbacks = m_DoubleTapEvents[layerMaskAsKey].RemoveAll( - e => - e.Collider == itemCollider && - e.TapCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isDoubleTapInside); - - success &= (numberOfRemovedCallbacks > 0); - } - } - else - { - success = false; - } - - if (!success) - { - success = true; - Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); - if (colliderList2D != null && colliderList2D.Length > 0) - { - foreach (Collider2D itemCollider2D in colliderList2D) - { - int numberOfRemovedCallbacks = m_DoubleTapEvents[layerMaskAsKey].RemoveAll( - e => - e.Collider2D == itemCollider2D && - e.TapCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isDoubleTapInside); - - success &= (numberOfRemovedCallbacks > 0); - } - } - else - { - success = false; - } - - } - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - if (!success) - { - success = true; - RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren (includeInactive: true); - if (rectTransformList != null && rectTransformList.Length > 0) - { - foreach (RectTransform itemRectTransform in rectTransformList) - { - int numberOfRemovedCallbacks = m_DoubleTapEvents[layerMaskAsKey].RemoveAll( - e => - e.RectTransform == itemRectTransform && - e.TapCallback == callback && - e.SortingLayer == SortingLayer && - e.IsInside == isDoubleTapInside); - - success &= (numberOfRemovedCallbacks > 0); - } - } - else - { - success = false; - } - } - #endif - } + m_DoubleTapEvents[layerMaskAsKey].Add(new TouchEventData(itemRectTransform, callback, SortingLayer, isDoubleTapInside)); } else { - Log.Warning("TouchEventManager", "There is no callback for double-tap event unregistration"); + m_DoubleTapEvents[layerMaskAsKey] = new List() { new TouchEventData(itemRectTransform, callback, SortingLayer, isDoubleTapInside) }; } + } + + success = true; } else { - Log.Warning("TouchEventManager", "There is no gameobject for double-tap event unregistration"); + Log.Warning("TouchEventManager", "There is no Rect Transform of given gameobjectToTouch (double-tap)"); } + } +#endif - return success; } + else + { + Log.Warning("TouchEventManager", "There is no callback for double-tap event registration"); + } + } + else + { + Log.Warning("TouchEventManager", "There is no gameobject for double-tap event registration"); + } + + return success; + } + /// + /// Unregisters the double tap event. + /// + /// true, if double tap event was unregistered, false otherwise. + /// Game object to touch. + /// Callback. + /// Sorting layer. + /// If set to true is double tap inside. + /// Layer mask. + public bool UnregisterDoubleTapEvent(GameObject gameObjectToTouch, string callback, int SortingLayer = 0, bool isDoubleTapInside = true, LayerMask layerMask = default(LayerMask)) + { + bool success = false; - private void DoubleTapGesture_Tapped(object sender, System.EventArgs e) + if (gameObjectToTouch != null) + { + if (!string.IsNullOrEmpty(callback)) { - if (m_Active) + int layerMaskAsKey = (layerMask != default(LayerMask)) ? layerMask.value : (1 << gameObjectToTouch.layer); + + if (m_DoubleTapEvents.ContainsKey(layerMaskAsKey)) + { + success = true; + Collider[] colliderList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (colliderList != null && colliderList.Length > 0) + { + foreach (Collider itemCollider in colliderList) + { + int numberOfRemovedCallbacks = m_DoubleTapEvents[layerMaskAsKey].RemoveAll( + e => + e.Collider == itemCollider && + e.TapCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isDoubleTapInside); + + success &= (numberOfRemovedCallbacks > 0); + } + } + else + { + success = false; + } + + if (!success) + { + success = true; + Collider2D[] colliderList2D = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (colliderList2D != null && colliderList2D.Length > 0) + { + foreach (Collider2D itemCollider2D in colliderList2D) + { + int numberOfRemovedCallbacks = m_DoubleTapEvents[layerMaskAsKey].RemoveAll( + e => + e.Collider2D == itemCollider2D && + e.TapCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isDoubleTapInside); + + success &= (numberOfRemovedCallbacks > 0); + } + } + else + { + success = false; + } + + } +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + if (!success) { - #if ENABLE_DEBUGGING + success = true; + RectTransform[] rectTransformList = gameObjectToTouch.GetComponentsInChildren(includeInactive: true); + if (rectTransformList != null && rectTransformList.Length > 0) + { + foreach (RectTransform itemRectTransform in rectTransformList) + { + int numberOfRemovedCallbacks = m_DoubleTapEvents[layerMaskAsKey].RemoveAll( + e => + e.RectTransform == itemRectTransform && + e.TapCallback == callback && + e.SortingLayer == SortingLayer && + e.IsInside == isDoubleTapInside); + + success &= (numberOfRemovedCallbacks > 0); + } + } + else + { + success = false; + } + } +#endif + } + } + else + { + Log.Warning("TouchEventManager", "There is no callback for double-tap event unregistration"); + } + } + else + { + Log.Warning("TouchEventManager", "There is no gameobject for double-tap event unregistration"); + } + + return success; + } + + + private void DoubleTapGesture_Tapped(object sender, System.EventArgs e) + { + if (m_Active) + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "DoubleTapGesture_Tapped: {0} - {1}", m_DoubleTapGesture.ScreenPosition, m_DoubleTapGesture.NumTouches); - #endif +#endif - TouchEventData tapEventToFire = null; + TouchEventData tapEventToFire = null; - RaycastHit hitToFire3D = default(RaycastHit); - RaycastHit2D hitToFire2D = default(RaycastHit2D); - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - RaycastResult hitToFire2DEventSystem = default(RaycastResult); - #endif + RaycastHit hitToFire3D = default(RaycastHit); + RaycastHit2D hitToFire2D = default(RaycastHit2D); +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + RaycastResult hitToFire2DEventSystem = default(RaycastResult); +#endif - foreach (var kp in m_DoubleTapEvents) - { - //Adding Variables for 3D Tap Check - Ray rayForTab = MainCamera.ScreenPointToRay(m_DoubleTapGesture.ScreenPosition); - Transform hitTransform3D = null; - RaycastHit hit3D = default(RaycastHit); - bool isHitOnLayer3D = Physics.Raycast(rayForTab, out hit3D, Mathf.Infinity, kp.Key); - if (isHitOnLayer3D) - { - hitTransform3D = hit3D.collider.transform; - } + foreach (var kp in m_DoubleTapEvents) + { + //Adding Variables for 3D Tap Check + Ray rayForTab = MainCamera.ScreenPointToRay(m_DoubleTapGesture.ScreenPosition); + Transform hitTransform3D = null; + RaycastHit hit3D = default(RaycastHit); + bool isHitOnLayer3D = Physics.Raycast(rayForTab, out hit3D, Mathf.Infinity, kp.Key); + if (isHitOnLayer3D) + { + hitTransform3D = hit3D.collider.transform; + } + + //Adding Variables for 2D Tap Check for 2d Colliders + Transform hitTransform2D = null; + RaycastHit2D hit2D = Physics2D.Raycast(rayForTab.origin, rayForTab.direction, Mathf.Infinity, kp.Key); + bool isHitOnLayer2D = false; + if (hit2D.collider != null) + { + isHitOnLayer2D = true; + hitTransform2D = hit2D.collider.transform; + } + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //Adding Variables for Event.System Tap for UI Elements + Transform hitTransform2DEventSystem = null; + bool isHitOnLayer2DEventSystem = false; + RaycastResult hit2DEventSystem = default(RaycastResult); + if (EventSystem.current != null) + { + PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); + pointerEventForTap.position = m_DoubleTapGesture.ScreenPosition; + List raycastResultListFor2DEventSystem = new List(); + EventSystem.current.RaycastAll(pointerEventForTap, raycastResultListFor2DEventSystem); + foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) + { - //Adding Variables for 2D Tap Check for 2d Colliders - Transform hitTransform2D = null; - RaycastHit2D hit2D = Physics2D.Raycast(rayForTab.origin, rayForTab.direction, Mathf.Infinity, kp.Key); - bool isHitOnLayer2D = false; - if (hit2D.collider != null) - { - isHitOnLayer2D = true; - hitTransform2D = hit2D.collider.transform; - } + LayerMask layerMaskOfItem = 1 << itemRaycastResult.gameObject.layer; + isHitOnLayer2DEventSystem = ((layerMaskOfItem.value & kp.Key) == layerMaskOfItem.value); + if (isHitOnLayer2DEventSystem) + { + hit2DEventSystem = itemRaycastResult; + hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; + break; + } + } + } +#endif - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //Adding Variables for Event.System Tap for UI Elements - Transform hitTransform2DEventSystem = null; - bool isHitOnLayer2DEventSystem = false; - RaycastResult hit2DEventSystem = default(RaycastResult); - if (EventSystem.current != null) - { - PointerEventData pointerEventForTap = new PointerEventData(EventSystem.current); - pointerEventForTap.position = m_DoubleTapGesture.ScreenPosition; - List raycastResultListFor2DEventSystem = new List(); - EventSystem.current.RaycastAll (pointerEventForTap, raycastResultListFor2DEventSystem); - foreach (RaycastResult itemRaycastResult in raycastResultListFor2DEventSystem) - { - - LayerMask layerMaskOfItem = 1 << itemRaycastResult.gameObject.layer; - isHitOnLayer2DEventSystem = ((layerMaskOfItem.value & kp.Key) == layerMaskOfItem.value); - if (isHitOnLayer2DEventSystem) - { - hit2DEventSystem = itemRaycastResult; - hitTransform2DEventSystem = itemRaycastResult.gameObject.transform; - break; - } - } - } - #endif + for (int i = 0; i < kp.Value.Count; ++i) + { + TouchEventData tapEventData = kp.Value[i]; - for (int i = 0; i < kp.Value.Count; ++i) - { - TouchEventData tapEventData = kp.Value[i]; - - if (kp.Value[i].Collider == null && kp.Value[i].Collider2D == null && kp.Value[i].RectTransform == null && kp.Value[i].RectTransformList == null) - { - Log.Warning("TouchEventManager", "Removing invalid collider event receiver from DoubleTapEventList"); - kp.Value.RemoveAt(i--); - continue; - } - - if (string.IsNullOrEmpty(tapEventData.TapCallback)) - { - Log.Warning("TouchEventManager", "Removing invalid event receiver from DoubleTapEventList"); - kp.Value.RemoveAt(i--); - continue; - } - - //3d Hit Check - if (tapEventData.Collider != null) - { - if (isHitOnLayer3D && hitTransform3D == tapEventData.Collider.transform && tapEventData.IsInside) - { - //Tapped inside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - #if ENABLE_DEBUGGING + if (kp.Value[i].Collider == null && kp.Value[i].Collider2D == null && kp.Value[i].RectTransform == null && kp.Value[i].RectTransformList == null) + { + Log.Warning("TouchEventManager", "Removing invalid collider event receiver from DoubleTapEventList"); + kp.Value.RemoveAt(i--); + continue; + } + + if (string.IsNullOrEmpty(tapEventData.TapCallback)) + { + Log.Warning("TouchEventManager", "Removing invalid event receiver from DoubleTapEventList"); + kp.Value.RemoveAt(i--); + continue; + } + + //3d Hit Check + if (tapEventData.Collider != null) + { + if (isHitOnLayer3D && hitTransform3D == tapEventData.Collider.transform && tapEventData.IsInside) + { + //Tapped inside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || - (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || + (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if ((!isHitOnLayer3D || hitTransform3D != tapEventData.Collider.transform) && !tapEventData.IsInside) - { - //Tapped outside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if ((!isHitOnLayer3D || hitTransform3D != tapEventData.Collider.transform) && !tapEventData.IsInside) + { + //Tapped outside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) - { - tapEventToFire = tapEventData; - hitToFire3D = hit3D; - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) + { + tapEventToFire = tapEventData; + hitToFire3D = hit3D; + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 3D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform3D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - //2d Hit Check - if (tapEventData.Collider2D != null) - { - if (isHitOnLayer2D && hitTransform2D == tapEventData.Collider2D.transform && tapEventData.IsInside) - { - //Tapped inside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + + //2d Hit Check + if (tapEventData.Collider2D != null) + { + if (isHitOnLayer2D && hitTransform2D == tapEventData.Collider2D.transform && tapEventData.IsInside) + { + //Tapped inside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || - (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || + (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - - } - else if ((!isHitOnLayer2D || hitTransform2D != tapEventData.Collider2D.transform) && !tapEventData.IsInside) - { - //Tapped outside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + + } + else if ((!isHitOnLayer2D || hitTransform2D != tapEventData.Collider2D.transform) && !tapEventData.IsInside) + { + //Tapped outside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = hit2D; - hitToFire2DEventSystem = default(RaycastResult); - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = hit2D; + hitToFire2DEventSystem = default(RaycastResult); + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 2D. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2D, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - //do nothing - } - } - } - else - { - //do nothing - } - } - - #if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER - //2D UI Hit Check using EventSystem - if (tapEventData.RectTransform != null) - { - if (isHitOnLayer2DEventSystem && hitTransform2DEventSystem == tapEventData.RectTransform.transform && tapEventData.IsInside) - { - //Tapped inside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING - Log.Debug("TouchEventManager", "Double-Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } - else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || - (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING - Log.Debug("TouchEventManager", "Double-Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - //do nothing - } - } - - } - else if ((!isHitOnLayer2DEventSystem || hitTransform2DEventSystem != tapEventData.RectTransform.transform) && !tapEventData.IsInside) - { - //Tapped outside the object - if (tapEventToFire == null) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } + } + +#if UNITY_4_6 || UNITY_5 || UNITY_5_3_OR_NEWER + //2D UI Hit Check using EventSystem + if (tapEventData.RectTransform != null) + { + if (isHitOnLayer2DEventSystem && hitTransform2DEventSystem == tapEventData.RectTransform.transform && tapEventData.IsInside) + { + //Tapped inside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) - { - tapEventToFire = tapEventData; - hitToFire3D = default(RaycastHit); - hitToFire2D = default(RaycastHit2D); - hitToFire2DEventSystem = hit2DEventSystem; - - #if ENABLE_DEBUGGING +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer || + (tapEventToFire.SortingLayer == tapEventData.SortingLayer && !tapEventToFire.IsInside)) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "Double-Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); - #endif - } else - { - //do nothing - } - } - } else - { - //do nothing - } - } - #endif - - } +#endif + } + else + { + //do nothing + } } - if (tapEventToFire != null) - EventManager.Instance.SendEvent(tapEventToFire.TapCallback, m_DoubleTapGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); + } + else if ((!isHitOnLayer2DEventSystem || hitTransform2DEventSystem != tapEventData.RectTransform.transform) && !tapEventData.IsInside) + { + //Tapped outside the object + if (tapEventToFire == null) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; - EventManager.Instance.SendEvent("OnDoubleTap", m_DoubleTapGesture); +#if ENABLE_DEBUGGING + Log.Debug("TouchEventManager", "Double-Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); +#endif + } + else + { + if (tapEventData.SortingLayer > tapEventToFire.SortingLayer) + { + tapEventToFire = tapEventData; + hitToFire3D = default(RaycastHit); + hitToFire2D = default(RaycastHit2D); + hitToFire2DEventSystem = hit2DEventSystem; + +#if ENABLE_DEBUGGING + Log.Debug("TouchEventManager", "Double-Tap Event Found 2D Event System. itemCollider: {0}, callback: {1}, SortingLayer: {2}, isTapInside: {3} ",hitTransform2DEventSystem, tapEventData.TapCallback, tapEventData.SortingLayer, tapEventData.IsInside); +#endif + } + else + { + //do nothing + } + } + } + else + { + //do nothing + } } +#endif + + } } - #endregion + if (tapEventToFire != null) + EventManager.Instance.SendEvent(tapEventToFire.TapCallback, m_DoubleTapGesture, hitToFire3D, hitToFire2D, hitToFire2DEventSystem); + EventManager.Instance.SendEvent("OnDoubleTap", m_DoubleTapGesture); + } + } - #region Three Tap Gesture Call + #endregion - private void ThreeTapGesture_Tapped(object sender, System.EventArgs e) - { - if (m_Active) - { - #if ENABLE_DEBUGGING + + #region Three Tap Gesture Call + + private void ThreeTapGesture_Tapped(object sender, System.EventArgs e) + { + if (m_Active) + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "ThreeTapGesture_Tapped: {0} - {1}", m_ThreeTapGesture.ScreenPosition, m_ThreeTapGesture.NumTouches); - #endif - EventManager.Instance.SendEvent("OnTripleTap", m_ThreeTapGesture); - } - } +#endif + EventManager.Instance.SendEvent("OnTripleTap", m_ThreeTapGesture); + } + } - #endregion + #endregion - #region PressGesture Events - Call - There is no registration is sends automatically the press event + #region PressGesture Events - Call - There is no registration is sends automatically the press event - private void PressGesturePressed(object sender, System.EventArgs e) - { - #if ENABLE_DEBUGGING + private void PressGesturePressed(object sender, System.EventArgs e) + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "PressGesturePressed: {0} - {1}", m_PressGesture.ScreenPosition, m_PressGesture.NumTouches); - #endif +#endif - EventManager.Instance.SendEvent("OnTouchPressedFullscreen", m_PressGesture); - } + EventManager.Instance.SendEvent("OnTouchPressedFullscreen", m_PressGesture); + } - #endregion + #endregion - #region Long Press Gesture Events + #region Long Press Gesture Events - private void LongPressGesturePressed(object sender, System.EventArgs e) - { - #if ENABLE_DEBUGGING + private void LongPressGesturePressed(object sender, System.EventArgs e) + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "LongPressGesturePressed: {0} - {1}", m_LongPressGesture.ScreenPosition, m_LongPressGesture.NumTouches); - #endif +#endif - EventManager.Instance.SendEvent("OnLongPressOneFinger", m_LongPressGesture); - } + EventManager.Instance.SendEvent("OnLongPressOneFinger", m_LongPressGesture); + } - #endregion + #endregion - #region ReleaseGesture Events - Call - There is no registration is sends automatically the release event + #region ReleaseGesture Events - Call - There is no registration is sends automatically the release event - private void ReleaseGestureReleased(object sender, System.EventArgs e) - { - #if ENABLE_DEBUGGING + private void ReleaseGestureReleased(object sender, System.EventArgs e) + { +#if ENABLE_DEBUGGING Log.Debug("TouchEventManager", "ReleaseGestureReleased: {0} - {1}", m_ReleaseGesture.ScreenPosition, m_ReleaseGesture.NumTouches); - #endif +#endif - EventManager.Instance.SendEvent("OnTouchReleasedFullscreen", m_ReleaseGesture); - } - #endregion + EventManager.Instance.SendEvent("OnTouchReleasedFullscreen", m_ReleaseGesture); } + #endregion + } } diff --git a/Scripts/Utilities/UnityObjectUtil.cs b/Scripts/Utilities/UnityObjectUtil.cs old mode 100644 new mode 100755 index 1443d551b..bc0328c78 --- a/Scripts/Utilities/UnityObjectUtil.cs +++ b/Scripts/Utilities/UnityObjectUtil.cs @@ -15,83 +15,80 @@ * */ -using IBM.Watson.DeveloperCloud.Logging; -using System; using System.Collections; using System.Collections.Generic; -using System.IO; using UnityEngine; namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// AudioClip helper functions. + /// + public static class UnityObjectUtil + { + private static Queue sm_DestroyQueue = new Queue(); + private static int sm_DestroyQueueID = 0; + /// - /// AudioClip helper functions. + /// Returns the state of the AudioClip destroy queue. /// - public static class UnityObjectUtil + /// Returns true if the destoy queue processor is active. + public static bool IsDestroyQueueActive() { - private static Queue sm_DestroyQueue = new Queue(); - private static int sm_DestroyQueueID = 0; - - /// - /// Returns the state of the AudioClip destroy queue. - /// - /// Returns true if the destoy queue processor is active. - public static bool IsDestroyQueueActive() - { - return sm_DestroyQueueID != 0; - } + return sm_DestroyQueueID != 0; + } - /// - /// Start up the AudioClip destroy queue processor. - /// - public static void StartDestroyQueue() - { - if (sm_DestroyQueueID == 0) - sm_DestroyQueueID = Runnable.Run(ProcessDestroyQueue()); - } + /// + /// Start up the AudioClip destroy queue processor. + /// + public static void StartDestroyQueue() + { + if (sm_DestroyQueueID == 0) + sm_DestroyQueueID = Runnable.Run(ProcessDestroyQueue()); + } - /// - /// Stop the AudioClip destroy processor. - /// - public static void StopDestroyQueue() - { - if (sm_DestroyQueueID != 0) - { - Runnable.Stop(sm_DestroyQueueID); - sm_DestroyQueueID = 0; - } - } + /// + /// Stop the AudioClip destroy processor. + /// + public static void StopDestroyQueue() + { + if (sm_DestroyQueueID != 0) + { + Runnable.Stop(sm_DestroyQueueID); + sm_DestroyQueueID = 0; + } + } - /// - /// Queue an AudioClip for destruction on the main thread. This function is thread-safe. - /// - /// The AudioClip to destroy. - public static void DestroyUnityObject(UnityEngine.Object obj) - { - if (sm_DestroyQueueID == 0) - throw new WatsonException("Destroy queue not started."); + /// + /// Queue an AudioClip for destruction on the main thread. This function is thread-safe. + /// + /// The AudioClip to destroy. + public static void DestroyUnityObject(UnityEngine.Object obj) + { + if (sm_DestroyQueueID == 0) + throw new WatsonException("Destroy queue not started."); - lock (sm_DestroyQueue) - sm_DestroyQueue.Enqueue(obj); - } + lock (sm_DestroyQueue) + sm_DestroyQueue.Enqueue(obj); + } - private static IEnumerator ProcessDestroyQueue() - { - yield return null; + private static IEnumerator ProcessDestroyQueue() + { + yield return null; - while (sm_DestroyQueueID != 0) - { - yield return new WaitForSeconds(1.0f); + while (sm_DestroyQueueID != 0) + { + yield return new WaitForSeconds(1.0f); - lock (sm_DestroyQueue) - { - while (sm_DestroyQueue.Count > 0) - { - UnityEngine.Object obj = sm_DestroyQueue.Dequeue(); - UnityEngine.Object.DestroyImmediate(obj, true); - } - } - } + lock (sm_DestroyQueue) + { + while (sm_DestroyQueue.Count > 0) + { + UnityEngine.Object obj = sm_DestroyQueue.Dequeue(); + UnityEngine.Object.DestroyImmediate(obj, true); + } } + } } + } } diff --git a/Scripts/Utilities/Utility.cs b/Scripts/Utilities/Utility.cs index b44f96f32..cfec0bb91 100755 --- a/Scripts/Utilities/Utility.cs +++ b/Scripts/Utilities/Utility.cs @@ -29,465 +29,465 @@ namespace IBM.Watson.DeveloperCloud.Utilities { + /// + /// Utility functions. + /// + static public class Utility + { + private static fsSerializer sm_Serializer = new fsSerializer(); + private static string sm_MacAddress = null; + /// - /// Utility functions. + /// This helper functions returns all Type's that inherit from the given type. /// - static public class Utility + /// The Type to find all types that inherit from the given type. + /// A array of all Types that inherit from type. + public static Type[] FindAllDerivedTypes(Type type) { - private static fsSerializer sm_Serializer = new fsSerializer(); - private static string sm_MacAddress = null; - - /// - /// This helper functions returns all Type's that inherit from the given type. - /// - /// The Type to find all types that inherit from the given type. - /// A array of all Types that inherit from type. - public static Type[] FindAllDerivedTypes(Type type) - { - List types = new List(); - foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) - { - foreach (var t in assembly.GetTypes()) - { - if (t == type || t.IsAbstract) - continue; - if (type.IsAssignableFrom(t)) - types.Add(t); - } - } - - return types.ToArray(); - } - - /// - /// Approximately the specified a, b and tolerance. - /// - /// The first component. - /// The second component. - /// Tolerance. - public static bool Approximately(double a, double b, double tolerance = 0.0001) - { - return (System.Math.Abs(a - b) < tolerance); - } - - /// - /// Approximately the specified a, b and tolerance. - /// - /// The first component. - /// The second component. - /// Tolerance. - public static bool Approximately(float a, float b, float tolerance = 0.0001f) + List types = new List(); + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + { + foreach (var t in assembly.GetTypes()) { - return (Mathf.Abs(a - b) < tolerance); + if (t == type || t.IsAbstract) + continue; + if (type.IsAssignableFrom(t)) + types.Add(t); } + } - /// - /// Approximately the specified a, b and tolerance. - /// - /// The first component. - /// The second component. - /// Tolerance. - public static bool Approximately(Vector3 a, Vector3 b, float tolerance = 0.0001f) - { - return Approximately(a.x, b.x, tolerance) && Approximately(a.y, b.y, tolerance) && Approximately(a.z, b.z, tolerance); - } + return types.ToArray(); + } - /// - /// Approximately Quaternion with the specified a, b and tolerance. - /// - /// The first component. - /// The second component. - /// Tolerance. - public static bool Approximately(Quaternion a, Quaternion b, float tolerance = 0.0001f) - { - return - (Approximately(a.eulerAngles.x, b.eulerAngles.x, tolerance) || Approximately((a.eulerAngles.x < 0 ? a.eulerAngles.x + 360.0f : a.eulerAngles.x), (b.eulerAngles.x < 0 ? b.eulerAngles.x + 360.0f : b.eulerAngles.x), tolerance)) && - (Approximately(a.eulerAngles.y, b.eulerAngles.y, tolerance) || Approximately((a.eulerAngles.y < 0 ? a.eulerAngles.y + 360.0f : a.eulerAngles.y), (b.eulerAngles.y < 0 ? b.eulerAngles.y + 360.0f : b.eulerAngles.y), tolerance)) && - (Approximately(a.eulerAngles.z, b.eulerAngles.z, tolerance) || Approximately((a.eulerAngles.z < 0 ? a.eulerAngles.z + 360.0f : a.eulerAngles.z), (b.eulerAngles.z < 0 ? b.eulerAngles.z + 360.0f : b.eulerAngles.z), tolerance)); - } + /// + /// Approximately the specified a, b and tolerance. + /// + /// The first component. + /// The second component. + /// Tolerance. + public static bool Approximately(double a, double b, double tolerance = 0.0001) + { + return (System.Math.Abs(a - b) < tolerance); + } - /// - /// Finds the object in child of parent object by name of child - /// - /// The object. - /// Parent Object. - /// Name child. - public static GameObject FindObject(GameObject parent, string nameChild) - { - GameObject childObject = null; + /// + /// Approximately the specified a, b and tolerance. + /// + /// The first component. + /// The second component. + /// Tolerance. + public static bool Approximately(float a, float b, float tolerance = 0.0001f) + { + return (Mathf.Abs(a - b) < tolerance); + } - string[] childPath = nameChild.Split('/'); + /// + /// Approximately the specified a, b and tolerance. + /// + /// The first component. + /// The second component. + /// Tolerance. + public static bool Approximately(Vector3 a, Vector3 b, float tolerance = 0.0001f) + { + return Approximately(a.x, b.x, tolerance) && Approximately(a.y, b.y, tolerance) && Approximately(a.z, b.z, tolerance); + } - for (int i = 0; i < childPath.Length; i++) - { - string childTransformName = childPath[i]; - - Transform[] childerenTransform = parent.GetComponentsInChildren(includeInactive: true); - if (childerenTransform != null) - { - foreach (Transform item in childerenTransform) - { - if (string.Equals(item.name, childTransformName)) - { - if (i == childPath.Length - 1) - { - childObject = item.gameObject; - } - else - { - parent = item.gameObject; - } - break; - } - } - } - } - return childObject; - } + /// + /// Approximately Quaternion with the specified a, b and tolerance. + /// + /// The first component. + /// The second component. + /// Tolerance. + public static bool Approximately(Quaternion a, Quaternion b, float tolerance = 0.0001f) + { + return + (Approximately(a.eulerAngles.x, b.eulerAngles.x, tolerance) || Approximately((a.eulerAngles.x < 0 ? a.eulerAngles.x + 360.0f : a.eulerAngles.x), (b.eulerAngles.x < 0 ? b.eulerAngles.x + 360.0f : b.eulerAngles.x), tolerance)) && + (Approximately(a.eulerAngles.y, b.eulerAngles.y, tolerance) || Approximately((a.eulerAngles.y < 0 ? a.eulerAngles.y + 360.0f : a.eulerAngles.y), (b.eulerAngles.y < 0 ? b.eulerAngles.y + 360.0f : b.eulerAngles.y), tolerance)) && + (Approximately(a.eulerAngles.z, b.eulerAngles.z, tolerance) || Approximately((a.eulerAngles.z < 0 ? a.eulerAngles.z + 360.0f : a.eulerAngles.z), (b.eulerAngles.z < 0 ? b.eulerAngles.z + 360.0f : b.eulerAngles.z), tolerance)); + } - /// - /// Finds the objects in children of parent object by name of child - /// - /// The objects. - /// Parent. - /// Name child. - /// Check string contains the name instead of equality. - /// If true, children will be returned sorted by their name. - public static T[] FindObjects(GameObject parent, string nameChild, bool isContains = false, bool sortByName = false, bool includeInactive = true) where T : Component - { - T[] childObjects = null; - List listGameObject = new List(); + /// + /// Finds the object in child of parent object by name of child + /// + /// The object. + /// Parent Object. + /// Name child. + public static GameObject FindObject(GameObject parent, string nameChild) + { + GameObject childObject = null; - string[] childPath = nameChild.Split('/'); + string[] childPath = nameChild.Split('/'); - for (int i = 0; i < childPath.Length; i++) - { - string childTransformName = childPath[i]; - T[] childerenTransform = parent.GetComponentsInChildren(includeInactive: includeInactive); - if (childerenTransform != null) - { - foreach (T item in childerenTransform) - { - if ((isContains && item.name.Contains(childTransformName)) || string.Equals(item.name, childTransformName)) - { - if (i == childPath.Length - 1) - { - listGameObject.Add(item); - } - else - { - parent = item.gameObject; - } - } - } - } - } + for (int i = 0; i < childPath.Length; i++) + { + string childTransformName = childPath[i]; - if (listGameObject.Count > 0) + Transform[] childerenTransform = parent.GetComponentsInChildren(includeInactive: true); + if (childerenTransform != null) + { + foreach (Transform item in childerenTransform) + { + if (string.Equals(item.name, childTransformName)) { - if (sortByName) - { - listGameObject.Sort((x, y) => x.name.CompareTo(y.name)); - } - childObjects = listGameObject.ToArray(); + if (i == childPath.Length - 1) + { + childObject = item.gameObject; + } + else + { + parent = item.gameObject; + } + break; } - - return childObjects; + } } + } + return childObject; + } - /// - /// Get the MD5 hash of a string. - /// - /// - /// - public static string GetMD5(string s) - { - if (string.IsNullOrEmpty(s)) - return string.Empty; - - MD5 md5 = new MD5CryptoServiceProvider(); - byte[] data = Encoding.Default.GetBytes(s); - byte[] result = md5.ComputeHash(data); - - StringBuilder output = new StringBuilder(); - foreach (var b in result) - output.Append(b.ToString("x2")); + /// + /// Finds the objects in children of parent object by name of child + /// + /// The objects. + /// Parent. + /// Name child. + /// Check string contains the name instead of equality. + /// If true, children will be returned sorted by their name. + public static T[] FindObjects(GameObject parent, string nameChild, bool isContains = false, bool sortByName = false, bool includeInactive = true) where T : Component + { + T[] childObjects = null; + List listGameObject = new List(); - return output.ToString(); - } + string[] childPath = nameChild.Split('/'); - /// - /// Removes any tags from a string. (e.g. ) - /// - /// - /// - public static string RemoveTags(string s, char tagStartChar = '<', char tagEndChar = '>' ) + for (int i = 0; i < childPath.Length; i++) + { + string childTransformName = childPath[i]; + T[] childerenTransform = parent.GetComponentsInChildren(includeInactive: includeInactive); + if (childerenTransform != null) { - if (!string.IsNullOrEmpty(s)) + foreach (T item in childerenTransform) + { + if ((isContains && item.name.Contains(childTransformName)) || string.Equals(item.name, childTransformName)) { - int tagStart = s.IndexOf(tagStartChar); - while (tagStart >= 0) - { - int tagEnd = s.IndexOf(tagEndChar, tagStart); - if (tagEnd < 0) - break; - - string pre = tagStart > 0 ? s.Substring(0, tagStart) : string.Empty; - string post = tagEnd < s.Length ? s.Substring(tagEnd + 1) : string.Empty; - s = pre + post; - - tagStart = s.IndexOf(tagStartChar); - } + if (i == childPath.Length - 1) + { + listGameObject.Add(item); + } + else + { + parent = item.gameObject; + } } - - return s; + } } + } - /// - /// Gets the on off string. - /// - /// The on off string. - /// If set to true b. - public static string GetOnOffString(bool b) + if (listGameObject.Count > 0) + { + if (sortByName) { - return b?"ON": "OFF"; + listGameObject.Sort((x, y) => x.name.CompareTo(y.name)); } + childObjects = listGameObject.ToArray(); + } + return childObjects; + } - /// - /// Strips the prepending ! statment from string. - /// - /// The string. - /// S. - public static string StripString(string s) - { - string[] delimiter = new string[] {"!", "! "}; - string[] newString = s.Split(delimiter, System.StringSplitOptions.None); - if(newString.Length > 1) - { - return newString[1]; - } - else - { - return s; - } + /// + /// Get the MD5 hash of a string. + /// + /// + /// + public static string GetMD5(string s) + { + if (string.IsNullOrEmpty(s)) + return string.Empty; - } + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] data = Encoding.Default.GetBytes(s); + byte[] result = md5.ComputeHash(data); - /// - /// Gets the EPOCH time in UTC time zome - /// - /// Double EPOCH in UTC - public static double GetEpochUTCMilliseconds() - { - DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return (DateTime.UtcNow - epoch).TotalMilliseconds; - } + StringBuilder output = new StringBuilder(); + foreach (var b in result) + output.Append(b.ToString("x2")); - /// - /// Gets the epoch UTC seconds. - /// - /// The epoch UTC seconds. - public static double GetEpochUTCSeconds() - { - DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return (DateTime.UtcNow - epoch).TotalSeconds; - } + return output.ToString(); + } - /// - /// Gets the date time from epoch. - /// - /// The date time from epoch. - /// Epoch time. - /// Kind. - public static DateTime GetLocalDateTimeFromEpoch(double epochTime) + /// + /// Removes any tags from a string. (e.g. ) + /// + /// + /// + public static string RemoveTags(string s, char tagStartChar = '<', char tagEndChar = '>') + { + if (!string.IsNullOrEmpty(s)) + { + int tagStart = s.IndexOf(tagStartChar); + while (tagStart >= 0) { - DateTime dateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc); - try - { - dateTime = dateTime.AddSeconds(epochTime).ToLocalTime(); - } - catch (ArgumentOutOfRangeException ex) - { - Log.Debug("Utility", "Time conversion assuming time is in Milliseconds: {0}, {1}", epochTime, ex.Message); - dateTime = dateTime.AddMilliseconds(epochTime).ToLocalTime(); - } - - return dateTime; - } + int tagEnd = s.IndexOf(tagEndChar, tagStart); + if (tagEnd < 0) + break; + string pre = tagStart > 0 ? s.Substring(0, tagStart) : string.Empty; + string post = tagEnd < s.Length ? s.Substring(tagEnd + 1) : string.Empty; + s = pre + post; - /// - /// Returns First valid Mac address of the local machine - /// - public static string MacAddress - { - get - { - if (string.IsNullOrEmpty(sm_MacAddress)) - { - foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces()) - { - string macAddress = adapter.GetPhysicalAddress().ToString(); - if (!string.IsNullOrEmpty(macAddress)) - { - string regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})"; - string replace = "$1:$2:$3:$4:$5:$6"; - sm_MacAddress = Regex.Replace(macAddress, regex, replace); - - break; - } - } - } - - return sm_MacAddress; - } + tagStart = s.IndexOf(tagStartChar); } + } - /// - /// Converts Color32 array to Byte array. - /// - /// Color32 array of the image. - /// - public static byte[] Color32ArrayToByteArray(Color32[] colors) - { - if (colors == null || colors.Length == 0) - return null; + return s; + } - int lengthOfColor32 = Marshal.SizeOf(typeof(Color32)); - int length = lengthOfColor32 * colors.Length; - byte[] bytes = new byte[length]; + /// + /// Gets the on off string. + /// + /// The on off string. + /// If set to true b. + public static string GetOnOffString(bool b) + { + return b ? "ON" : "OFF"; + } - GCHandle handle = default(GCHandle); - try - { - handle = GCHandle.Alloc(colors, GCHandleType.Pinned); - IntPtr ptr = handle.AddrOfPinnedObject(); - Marshal.Copy(ptr, bytes, 0, length); - } - finally - { - if (handle != default(GCHandle)) - handle.Free(); - } - return bytes; - } + /// + /// Strips the prepending ! statment from string. + /// + /// The string. + /// S. + public static string StripString(string s) + { + string[] delimiter = new string[] { "!", "! " }; + string[] newString = s.Split(delimiter, System.StringSplitOptions.None); + if (newString.Length > 1) + { + return newString[1]; + } + else + { + return s; + } + + } - #region Cache Generic Deserialization - /// - /// Save value to data cache. - /// - /// - /// - /// - /// - /// - /// - /// - /// - public static void SaveToCache(Dictionary dictionaryCache, string cacheDirectoryId, string cacheId, T objectToCache, string prefix="", long maxCacheSize = 1024 * 1024 * 50, double maxCacheAge = 24 * 7) where T : class, new() - { - if (objectToCache != null) - { - DataCache cache = null; + /// + /// Gets the EPOCH time in UTC time zome + /// + /// Double EPOCH in UTC + public static double GetEpochUTCMilliseconds() + { + DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return (DateTime.UtcNow - epoch).TotalMilliseconds; + } - if (!dictionaryCache.TryGetValue(cacheDirectoryId, out cache)) - { - cache = new DataCache( prefix + cacheDirectoryId, maxCacheSize: maxCacheSize, maxCacheAge: double.MaxValue); //We will store the values as max time - dictionaryCache[ cacheDirectoryId ] = cache; - } + /// + /// Gets the epoch UTC seconds. + /// + /// The epoch UTC seconds. + public static double GetEpochUTCSeconds() + { + DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + return (DateTime.UtcNow - epoch).TotalSeconds; + } - fsData data = null; - fsResult r = sm_Serializer.TrySerialize(objectToCache.GetType(), objectToCache, out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); + /// + /// Gets the date time from epoch. + /// + /// The date time from epoch. + /// Epoch time. + /// Kind. + public static DateTime GetLocalDateTimeFromEpoch(double epochTime) + { + DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); + try + { + dateTime = dateTime.AddSeconds(epochTime).ToLocalTime(); + } + catch (ArgumentOutOfRangeException ex) + { + Log.Debug("Utility", "Time conversion assuming time is in Milliseconds: {0}, {1}", epochTime, ex.Message); + dateTime = dateTime.AddMilliseconds(epochTime).ToLocalTime(); + } - cache.Save(cacheId, Encoding.UTF8.GetBytes(fsJsonPrinter.PrettyJson(data))); - } - } + return dateTime; + } - /// - /// Get value from the data cache. - /// - /// - /// - /// - /// - /// - /// - public static T GetFromCache(Dictionary dictionaryCache, string cacheDirectoryId, string cacheId, string prefix="") where T : class, new() - { - T cachedObject = null; - DataCache cache = null; - if (! dictionaryCache.TryGetValue( cacheDirectoryId, out cache ) ) + /// + /// Returns First valid Mac address of the local machine + /// + public static string MacAddress + { + get + { + if (string.IsNullOrEmpty(sm_MacAddress)) + { + foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces()) + { + string macAddress = adapter.GetPhysicalAddress().ToString(); + if (!string.IsNullOrEmpty(macAddress)) { - cache = new DataCache( prefix + cacheDirectoryId ); - dictionaryCache[ cacheDirectoryId ] = cache; - } + string regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})"; + string replace = "$1:$2:$3:$4:$5:$6"; + sm_MacAddress = Regex.Replace(macAddress, regex, replace); - byte [] cached = cache.Find( cacheId ); - if ( cached != null ) - { - cachedObject = DeserializeResponse( cached ); - if ( cachedObject != null) - { - return cachedObject; - } + break; } - - return cachedObject; + } } - #endregion + return sm_MacAddress; + } + } - #region De-Serialization + /// + /// Converts Color32 array to Byte array. + /// + /// Color32 array of the image. + /// + public static byte[] Color32ArrayToByteArray(Color32[] colors) + { + if (colors == null || colors.Length == 0) + return null; + + int lengthOfColor32 = Marshal.SizeOf(typeof(Color32)); + int length = lengthOfColor32 * colors.Length; + byte[] bytes = new byte[length]; + + GCHandle handle = default(GCHandle); + try + { + handle = GCHandle.Alloc(colors, GCHandleType.Pinned); + IntPtr ptr = handle.AddrOfPinnedObject(); + Marshal.Copy(ptr, bytes, 0, length); + } + finally + { + if (handle != default(GCHandle)) + handle.Free(); + } + + return bytes; + } + + #region Cache Generic Deserialization + /// + /// Save value to data cache. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static void SaveToCache(Dictionary dictionaryCache, string cacheDirectoryId, string cacheId, T objectToCache, string prefix = "", long maxCacheSize = 1024 * 1024 * 50, double maxCacheAge = 24 * 7) where T : class, new() + { + if (objectToCache != null) + { + DataCache cache = null; - /// - /// Deserializes the response. - /// - /// The response. - /// Resp. - /// Object. - /// The 1st type parameter. - public static T DeserializeResponse( byte [] resp, object obj = null ) where T : class, new() + if (!dictionaryCache.TryGetValue(cacheDirectoryId, out cache)) { - return DeserializeResponse(Encoding.UTF8.GetString( resp ), obj); + cache = new DataCache(prefix + cacheDirectoryId, maxCacheSize: maxCacheSize, maxCacheAge: double.MaxValue); //We will store the values as max time + dictionaryCache[cacheDirectoryId] = cache; } - /// - /// Deserializes the response. - /// - /// The response. - /// Json string of object - /// Object. - /// The 1st type parameter. - public static T DeserializeResponse( string json, object obj = null ) where T : class, new() + fsData data = null; + fsResult r = sm_Serializer.TrySerialize(objectToCache.GetType(), objectToCache, out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + cache.Save(cacheId, Encoding.UTF8.GetBytes(fsJsonPrinter.PrettyJson(data))); + } + } + + /// + /// Get value from the data cache. + /// + /// + /// + /// + /// + /// + /// + public static T GetFromCache(Dictionary dictionaryCache, string cacheDirectoryId, string cacheId, string prefix = "") where T : class, new() + { + T cachedObject = null; + + DataCache cache = null; + if (!dictionaryCache.TryGetValue(cacheDirectoryId, out cache)) + { + cache = new DataCache(prefix + cacheDirectoryId); + dictionaryCache[cacheDirectoryId] = cache; + } + + byte[] cached = cache.Find(cacheId); + if (cached != null) + { + cachedObject = DeserializeResponse(cached); + if (cachedObject != null) { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(json, out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); + return cachedObject; + } + } - if ( obj == null ) - obj = new T(); + return cachedObject; + } - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); + #endregion - return (T)obj; - } - catch (Exception e) - { - Log.Error("Utility", "DeserializeResponse Exception: {0}", e.ToString()); - } + #region De-Serialization - return null; - } - #endregion - } + /// + /// Deserializes the response. + /// + /// The response. + /// Resp. + /// Object. + /// The 1st type parameter. + public static T DeserializeResponse(byte[] resp, object obj = null) where T : class, new() + { + return DeserializeResponse(Encoding.UTF8.GetString(resp), obj); + } + + /// + /// Deserializes the response. + /// + /// The response. + /// Json string of object + /// Object. + /// The 1st type parameter. + public static T DeserializeResponse(string json, object obj = null) where T : class, new() + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(json, out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + if (obj == null) + obj = new T(); + + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + return (T)obj; + } + catch (Exception e) + { + Log.Error("Utility", "DeserializeResponse Exception: {0}", e.ToString()); + } + + return null; + } + #endregion + } } diff --git a/Scripts/Utilities/WatsonException.cs b/Scripts/Utilities/WatsonException.cs old mode 100644 new mode 100755 index 3fcc81285..7c7ef6a58 --- a/Scripts/Utilities/WatsonException.cs +++ b/Scripts/Utilities/WatsonException.cs @@ -19,18 +19,18 @@ namespace IBM.Watson.DeveloperCloud.Utilities { - /// - /// Watson exception class. - /// - class WatsonException : System.Exception + /// + /// Watson exception class. + /// + class WatsonException : System.Exception + { + public WatsonException(string message) : base(message) { - public WatsonException(string message) : base(message) - { - Log.Critical("Exception", "Exception: {0}", message); - } - public WatsonException(string message, WatsonException innerException) : base(message, innerException) - { - Log.Critical("Exception", "Exception: {0}", message); - } + Log.Critical("Exception", "Exception: {0}", message); } + public WatsonException(string message, WatsonException innerException) : base(message, innerException) + { + Log.Critical("Exception", "Exception: {0}", message); + } + } } diff --git a/Scripts/Utilities/WaveFile.cs b/Scripts/Utilities/WaveFile.cs old mode 100644 new mode 100755 index acd899afd..cdfdaa4e3 --- a/Scripts/Utilities/WaveFile.cs +++ b/Scripts/Utilities/WaveFile.cs @@ -24,238 +24,238 @@ namespace IBM.Watson.DeveloperCloud.Utilities { - /// - /// WAV Utility functions. - /// - static public class WaveFile + /// + /// WAV Utility functions. + /// + static public class WaveFile + { + #region Private Types + [StructLayout(LayoutKind.Sequential, Pack = 1)] + struct IFF_FORM_CHUNK { - #region Private Types - [StructLayout(LayoutKind.Sequential, Pack = 1)] - struct IFF_FORM_CHUNK - { - public uint form_id; - public uint form_length; - public uint id; - }; + public uint form_id; + public uint form_length; + public uint id; + }; - [StructLayout(LayoutKind.Sequential, Pack = 1)] - struct IFF_CHUNK - { - public uint id; - public uint length; - }; + [StructLayout(LayoutKind.Sequential, Pack = 1)] + struct IFF_CHUNK + { + public uint id; + public uint length; + }; - [StructLayout(LayoutKind.Sequential, Pack = 1)] - struct WAV_PCM - { - public ushort format_tag; - public ushort channels; - public uint sample_rate; - public uint average_data_rate; - public ushort alignment; - public ushort bits_per_sample; - }; - #endregion - - #region Private Functions - private static T ReadType(BinaryReader reader) - { - byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T))); + [StructLayout(LayoutKind.Sequential, Pack = 1)] + struct WAV_PCM + { + public ushort format_tag; + public ushort channels; + public uint sample_rate; + public uint average_data_rate; + public ushort alignment; + public ushort bits_per_sample; + }; + #endregion + + #region Private Functions + private static T ReadType(BinaryReader reader) + { + byte[] bytes = reader.ReadBytes(Marshal.SizeOf(typeof(T))); - GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); - T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); - handle.Free(); + GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); + T theStructure = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); + handle.Free(); - return theStructure; - } + return theStructure; + } - private static void WriteType(BinaryWriter writer, T data) - { - int size = Marshal.SizeOf(data); - byte[] bytes = new byte[size]; + private static void WriteType(BinaryWriter writer, T data) + { + int size = Marshal.SizeOf(data); + byte[] bytes = new byte[size]; - IntPtr ptr = Marshal.AllocHGlobal(size); - Marshal.StructureToPtr(data, ptr, true); - Marshal.Copy(ptr, bytes, 0, size); - Marshal.FreeHGlobal(ptr); + IntPtr ptr = Marshal.AllocHGlobal(size); + Marshal.StructureToPtr(data, ptr, true); + Marshal.Copy(ptr, bytes, 0, size); + Marshal.FreeHGlobal(ptr); - writer.Write(bytes, 0, size); - } + writer.Write(bytes, 0, size); + } - private static uint MakeID(string id) - { - byte[] bytes = Encoding.ASCII.GetBytes(id); - return BitConverter.ToUInt32(bytes, 0); - } + private static uint MakeID(string id) + { + byte[] bytes = Encoding.ASCII.GetBytes(id); + return BitConverter.ToUInt32(bytes, 0); + } - private static string GetID(uint id) + private static string GetID(uint id) + { + byte[] bytes = BitConverter.GetBytes(id); + return new string(new char[] { (char)bytes[0], (char)bytes[1], (char)bytes[2], (char)bytes[3] }); + } + #endregion + + #region Public Functions + /// + /// Creates a AudioClip object from WAV file data. + /// + /// What name to give the AudioClip. + /// The raw data of the WAV file. + /// Returns an AudioClip object on success, null on failure. + public static AudioClip ParseWAV(string clipName, byte[] data) + { + MemoryStream stream = new MemoryStream(data, false); + BinaryReader reader = new BinaryReader(stream); + + IFF_FORM_CHUNK form = ReadType(reader); + if (GetID(form.form_id) != "RIFF" || GetID(form.id) != "WAVE") + { + Log.Error("TextToSpeech", "Malformed WAV header: {0} != RIFF || {1} != WAVE", GetID(form.form_id), GetID(form.id)); + return null; + } + + WAV_PCM header = new WAV_PCM(); + bool bHeaderFound = false; + + while (reader.BaseStream.Position < reader.BaseStream.Length) + { + IFF_CHUNK chunk = ReadType(reader); + + int ChunkLength = (int)chunk.length; + if (ChunkLength < 0) // HACK: Deal with TextToSpeech bug where the chunk length is not set for the data chunk.. + ChunkLength = (int)(reader.BaseStream.Length - reader.BaseStream.Position); + if ((ChunkLength & 0x1) != 0) + ChunkLength += 1; + + long ChunkEnd = reader.BaseStream.Position + ChunkLength; + if (GetID(chunk.id) == "fmt ") { - byte[] bytes = BitConverter.GetBytes(id); - return new string(new char[] { (char)bytes[0], (char)bytes[1], (char)bytes[2], (char)bytes[3] }); + bHeaderFound = true; + header = ReadType(reader); } - #endregion - - #region Public Functions - /// - /// Creates a AudioClip object from WAV file data. - /// - /// What name to give the AudioClip. - /// The raw data of the WAV file. - /// Returns an AudioClip object on success, null on failure. - public static AudioClip ParseWAV(string clipName, byte[] data) + else if (GetID(chunk.id) == "data") { - MemoryStream stream = new MemoryStream(data, false); - BinaryReader reader = new BinaryReader(stream); - - IFF_FORM_CHUNK form = ReadType(reader); - if (GetID(form.form_id) != "RIFF" || GetID(form.id) != "WAVE") - { - Log.Error("TextToSpeech", "Malformed WAV header: {0} != RIFF || {1} != WAVE", GetID(form.form_id), GetID(form.id)); - return null; - } - - WAV_PCM header = new WAV_PCM(); - bool bHeaderFound = false; - - while (reader.BaseStream.Position < reader.BaseStream.Length) - { - IFF_CHUNK chunk = ReadType(reader); - - int ChunkLength = (int)chunk.length; - if (ChunkLength < 0) // HACK: Deal with TextToSpeech bug where the chunk length is not set for the data chunk.. - ChunkLength = (int)(reader.BaseStream.Length - reader.BaseStream.Position); - if ((ChunkLength & 0x1) != 0) - ChunkLength += 1; - - long ChunkEnd = reader.BaseStream.Position + ChunkLength; - if (GetID(chunk.id) == "fmt ") - { - bHeaderFound = true; - header = ReadType(reader); - } - else if (GetID(chunk.id) == "data") - { - if (!bHeaderFound) - { - Log.Error("TextToSpeech", "Failed to find header."); - return null; - } - byte[] waveform = reader.ReadBytes(ChunkLength); - - // convert into a float based wave form.. - int channels = (int)header.channels; - int bps = (int)header.bits_per_sample; - float divisor = 1 << (bps - 1); - int bytesps = bps / 8; - int samples = waveform.Length / bytesps; - - Log.Debug("TextToSpeech", "WAV INFO, channels = {0}, bps = {1}, samples = {2}, rate = {3}", - channels, bps, samples, header.sample_rate); - - float[] wf = new float[samples]; - if (bps == 16) - { - for (int s = 0; s < samples; ++s) - wf[s] = ((float)BitConverter.ToInt16(waveform, s * bytesps)) / divisor; - } - else if (bps == 32) - { - for (int s = 0; s < samples; ++s) - wf[s] = ((float)BitConverter.ToInt32(waveform, s * bytesps)) / divisor; - } - else if (bps == 8) - { - for (int s = 0; s < samples; ++s) - wf[s] = ((float)BitConverter.ToChar(waveform, s * bytesps)) / divisor; - } - else - { - Log.Error("ParseWAV", "Unspported BPS {0} in WAV data.", bps.ToString()); - return null; - } - - AudioClip clip = AudioClip.Create(clipName, samples, channels, (int)header.sample_rate, false); - clip.SetData(wf, 0); - - return clip; - } - - reader.BaseStream.Position = ChunkEnd; - } - + if (!bHeaderFound) + { + Log.Error("TextToSpeech", "Failed to find header."); return null; - } + } + byte[] waveform = reader.ReadBytes(ChunkLength); + + // convert into a float based wave form.. + int channels = (int)header.channels; + int bps = (int)header.bits_per_sample; + float divisor = 1 << (bps - 1); + int bytesps = bps / 8; + int samples = waveform.Length / bytesps; + + Log.Debug("TextToSpeech", "WAV INFO, channels = {0}, bps = {1}, samples = {2}, rate = {3}", + channels, bps, samples, header.sample_rate); + + float[] wf = new float[samples]; + if (bps == 16) + { + for (int s = 0; s < samples; ++s) + wf[s] = ((float)BitConverter.ToInt16(waveform, s * bytesps)) / divisor; + } + else if (bps == 32) + { + for (int s = 0; s < samples; ++s) + wf[s] = ((float)BitConverter.ToInt32(waveform, s * bytesps)) / divisor; + } + else if (bps == 8) + { + for (int s = 0; s < samples; ++s) + wf[s] = ((float)BitConverter.ToChar(waveform, s * bytesps)) / divisor; + } + else + { + Log.Error("ParseWAV", "Unspported BPS {0} in WAV data.", bps.ToString()); + return null; + } - /// - /// Creates a WAV file from a AudioClip object. - /// - /// The AudioClip object to generate the WAV file from. - /// How many bits per sample we should use in the WAV file, 8, 16, or 32. - /// Returns a byte array of the raw data of the WAV file. - public static byte[] CreateWAV(AudioClip clip, int bps = 16) - { - MemoryStream stream = new MemoryStream(); - BinaryWriter writer = new BinaryWriter(stream); - - IFF_FORM_CHUNK form = new IFF_FORM_CHUNK(); - form.form_id = MakeID("RIFF"); - form.form_length = 0xffffffff; - form.id = MakeID("WAVE"); - WriteType(writer, form); - - long form_start = writer.BaseStream.Position; - float divisor = 1 << (bps - 1); - - WAV_PCM header = new WAV_PCM(); - header.format_tag = 1; - header.alignment = 2; - header.bits_per_sample = (ushort)bps; - header.sample_rate = (uint)clip.frequency; - header.channels = (ushort)clip.channels; - header.average_data_rate = (uint)((bps / 8) * clip.channels * clip.frequency); - - IFF_CHUNK fmt = new IFF_CHUNK(); - fmt.id = MakeID("fmt "); - fmt.length = (uint)Marshal.SizeOf(header); - WriteType(writer, fmt); - WriteType(writer, header); - - IFF_CHUNK data = new IFF_CHUNK(); - data.id = MakeID("data"); - data.length = (uint)((bps / 8) * clip.samples * clip.channels); - WriteType(writer, data); - - float[] samples = new float[clip.samples * clip.channels]; - clip.GetData(samples, 0); - - if (bps == 16) - { - for (int i = 0; i < samples.Length; ++i) - writer.Write((short)(samples[i] * divisor)); - } - else if (bps == 32) - { - for (int i = 0; i < samples.Length; ++i) - writer.Write((int)(samples[i] * divisor)); - } - else if (bps == 8) - { - for (int i = 0; i < samples.Length; ++i) - writer.Write((char)(samples[i] * divisor)); - } - else - { - Log.Error("CreateWAV", "Unsupported BPS {0} in WAV data.", bps.ToString()); - return null; - } - - // lastly, update the form length.. - form.form_length = (uint)(writer.BaseStream.Position - form_start); - writer.Seek(0, SeekOrigin.Begin); - WriteType(writer, form); - - return stream.GetBuffer(); + AudioClip clip = AudioClip.Create(clipName, samples, channels, (int)header.sample_rate, false); + clip.SetData(wf, 0); + + return clip; } - #endregion + + reader.BaseStream.Position = ChunkEnd; + } + + return null; + } + + /// + /// Creates a WAV file from a AudioClip object. + /// + /// The AudioClip object to generate the WAV file from. + /// How many bits per sample we should use in the WAV file, 8, 16, or 32. + /// Returns a byte array of the raw data of the WAV file. + public static byte[] CreateWAV(AudioClip clip, int bps = 16) + { + MemoryStream stream = new MemoryStream(); + BinaryWriter writer = new BinaryWriter(stream); + + IFF_FORM_CHUNK form = new IFF_FORM_CHUNK(); + form.form_id = MakeID("RIFF"); + form.form_length = 0xffffffff; + form.id = MakeID("WAVE"); + WriteType(writer, form); + + long form_start = writer.BaseStream.Position; + float divisor = 1 << (bps - 1); + + WAV_PCM header = new WAV_PCM(); + header.format_tag = 1; + header.alignment = 2; + header.bits_per_sample = (ushort)bps; + header.sample_rate = (uint)clip.frequency; + header.channels = (ushort)clip.channels; + header.average_data_rate = (uint)((bps / 8) * clip.channels * clip.frequency); + + IFF_CHUNK fmt = new IFF_CHUNK(); + fmt.id = MakeID("fmt "); + fmt.length = (uint)Marshal.SizeOf(header); + WriteType(writer, fmt); + WriteType(writer, header); + + IFF_CHUNK data = new IFF_CHUNK(); + data.id = MakeID("data"); + data.length = (uint)((bps / 8) * clip.samples * clip.channels); + WriteType(writer, data); + + float[] samples = new float[clip.samples * clip.channels]; + clip.GetData(samples, 0); + + if (bps == 16) + { + for (int i = 0; i < samples.Length; ++i) + writer.Write((short)(samples[i] * divisor)); + } + else if (bps == 32) + { + for (int i = 0; i < samples.Length; ++i) + writer.Write((int)(samples[i] * divisor)); + } + else if (bps == 8) + { + for (int i = 0; i < samples.Length; ++i) + writer.Write((char)(samples[i] * divisor)); + } + else + { + Log.Error("CreateWAV", "Unsupported BPS {0} in WAV data.", bps.ToString()); + return null; + } + + // lastly, update the form length.. + form.form_length = (uint)(writer.BaseStream.Position - form_start); + writer.Seek(0, SeekOrigin.Begin); + WriteType(writer, form); + + return stream.GetBuffer(); } + #endregion + } } From 4b9abcad277152ebc6a59c618621c5856a243bdf Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Wed, 26 Oct 2016 11:58:58 -0500 Subject: [PATCH 23/28] format widgets --- Scripts/Widgets/ActivateWidget.cs | 58 +- Scripts/Widgets/ClassDisplayWidget.cs | 63 +- Scripts/Widgets/ClassifierWidget.cs | 111 +- Scripts/Widgets/DataTypes.cs | 890 +++++++------- Scripts/Widgets/EventWidget.cs | 74 +- Scripts/Widgets/KeyboardWidget.cs | 76 +- Scripts/Widgets/LanguageTranslatorWidget.cs | 658 +++++----- Scripts/Widgets/MicrophoneWidget.cs | 598 +++++----- .../NaturalLanguageClassifierWidget.cs | 592 ++++----- Scripts/Widgets/SpeechDisplayWidget.cs | 174 +-- Scripts/Widgets/SpeechToTextWidget.cs | 333 +++--- Scripts/Widgets/TextToSpeechWidget.cs | 402 +++---- Scripts/Widgets/TouchWidget.cs | 260 ++-- Scripts/Widgets/WebCamDisplayWidget.cs | 144 +-- Scripts/Widgets/WebCamWidget.cs | 506 ++++---- Scripts/Widgets/Widget.cs | 1054 ++++++++--------- 16 files changed, 2997 insertions(+), 2996 deletions(-) mode change 100644 => 100755 Scripts/Widgets/ActivateWidget.cs mode change 100644 => 100755 Scripts/Widgets/ClassDisplayWidget.cs mode change 100644 => 100755 Scripts/Widgets/ClassifierWidget.cs mode change 100644 => 100755 Scripts/Widgets/EventWidget.cs mode change 100644 => 100755 Scripts/Widgets/KeyboardWidget.cs mode change 100644 => 100755 Scripts/Widgets/TextToSpeechWidget.cs mode change 100644 => 100755 Scripts/Widgets/TouchWidget.cs mode change 100644 => 100755 Scripts/Widgets/Widget.cs diff --git a/Scripts/Widgets/ActivateWidget.cs b/Scripts/Widgets/ActivateWidget.cs old mode 100644 new mode 100755 index 4eca6d0ef..78aeeb63a --- a/Scripts/Widgets/ActivateWidget.cs +++ b/Scripts/Widgets/ActivateWidget.cs @@ -20,37 +20,37 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// Simple widget class for connecting a UI button to an activation input on a widget. - /// - public class ActivateWidget : Widget - { - #region Outputs - [SerializeField] - private Output m_ActivateOutput = new Output(typeof(BooleanData), true); - #endregion + /// + /// Simple widget class for connecting a UI button to an activation input on a widget. + /// + public class ActivateWidget : Widget + { + #region Outputs + [SerializeField] + private Output m_ActivateOutput = new Output(typeof(BooleanData), true); + #endregion - #region Private Data - [SerializeField] - private bool m_SendValue = true; - #endregion + #region Private Data + [SerializeField] + private bool m_SendValue = true; + #endregion - #region Widget interface - /// - protected override string GetName() - { - return "Activate"; - } - #endregion + #region Widget interface + /// + protected override string GetName() + { + return "Activate"; + } + #endregion - #region Event Handlers - /// - /// Button event handler. - /// - public void OnButton() - { - m_ActivateOutput.SendData(new BooleanData(m_SendValue)); - } - #endregion + #region Event Handlers + /// + /// Button event handler. + /// + public void OnButton() + { + m_ActivateOutput.SendData(new BooleanData(m_SendValue)); } + #endregion + } } diff --git a/Scripts/Widgets/ClassDisplayWidget.cs b/Scripts/Widgets/ClassDisplayWidget.cs old mode 100644 new mode 100755 index f2b38feaf..b69b711b1 --- a/Scripts/Widgets/ClassDisplayWidget.cs +++ b/Scripts/Widgets/ClassDisplayWidget.cs @@ -15,7 +15,6 @@ * */ - using IBM.Watson.DeveloperCloud.DataTypes; using UnityEngine; using UnityEngine.UI; @@ -24,39 +23,39 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// Simple widget for displaying the Natural Language Classification in the UI. - /// - public class ClassDisplayWidget : Widget - { - #region Inputs - [SerializeField] - private Input m_ClassInput = new Input("ClassInput", typeof(ClassifyResultData), "OnClassInput"); - #endregion + /// + /// Simple widget for displaying the Natural Language Classification in the UI. + /// + public class ClassDisplayWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_ClassInput = new Input("ClassInput", typeof(ClassifyResultData), "OnClassInput"); + #endregion - #region Widget interface - /// - protected override string GetName() - { - return "ClassDisplay"; - } - #endregion + #region Widget interface + /// + protected override string GetName() + { + return "ClassDisplay"; + } + #endregion - #region Private Data - [SerializeField] - private Text m_ClassDisplay = null; - #endregion + #region Private Data + [SerializeField] + private Text m_ClassDisplay = null; + #endregion - #region Event Handlers - private void OnClassInput(Data data) - { - ClassifyResultData results = (ClassifyResultData)data; - if (m_ClassDisplay != null) - { - m_ClassDisplay.text = string.Format("Top class: {0} ({1:0.00})", - results.Result.top_class, results.Result.topConfidence); - } - } - #endregion + #region Event Handlers + private void OnClassInput(Data data) + { + ClassifyResultData results = (ClassifyResultData)data; + if (m_ClassDisplay != null) + { + m_ClassDisplay.text = string.Format("Top class: {0} ({1:0.00})", + results.Result.top_class, results.Result.topConfidence); + } } + #endregion + } } diff --git a/Scripts/Widgets/ClassifierWidget.cs b/Scripts/Widgets/ClassifierWidget.cs old mode 100644 new mode 100755 index fe70ab6a1..02e45ecfa --- a/Scripts/Widgets/ClassifierWidget.cs +++ b/Scripts/Widgets/ClassifierWidget.cs @@ -15,7 +15,6 @@ * */ - using IBM.Watson.DeveloperCloud.Services.NaturalLanguageClassifier.v1; using IBM.Watson.DeveloperCloud.DataTypes; using IBM.Watson.DeveloperCloud.Utilities; @@ -27,71 +26,71 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// This widget class maps Natural Language Classifier results to a SerializedDelegate. - /// - public class ClassifierWidget : Widget - { - #region Inputs - [SerializeField] - private Input m_ClassifyInput = new Input("Classified", typeof(ClassifyResultData), "OnClassifyInput"); - #endregion + /// + /// This widget class maps Natural Language Classifier results to a SerializedDelegate. + /// + public class ClassifierWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_ClassifyInput = new Input("Classified", typeof(ClassifyResultData), "OnClassifyInput"); + #endregion - #region Outputs - [SerializeField] - private Output m_ClassifyOutput = new Output(typeof(ClassifyResultData)); - #endregion + #region Outputs + [SerializeField] + private Output m_ClassifyOutput = new Output(typeof(ClassifyResultData)); + #endregion - #region Widget interface - /// - protected override string GetName() - { - return "Classifier"; - } - #endregion + #region Widget interface + /// + protected override string GetName() + { + return "Classifier"; + } + #endregion - #region Private Data - private delegate void OnClassifierResult(ClassifyResult result); + #region Private Data + private delegate void OnClassifierResult(ClassifyResult result); - [Serializable] - private class Mapping - { - public string m_Class = string.Empty; - public SerializedDelegate m_Callback = new SerializedDelegate(typeof(OnClassifierResult)); - public bool m_Exclusive = true; - }; + [Serializable] + private class Mapping + { + public string m_Class = string.Empty; + public SerializedDelegate m_Callback = new SerializedDelegate(typeof(OnClassifierResult)); + public bool m_Exclusive = true; + }; - [SerializeField] - private List m_Mappings = new List(); - #endregion + [SerializeField] + private List m_Mappings = new List(); + #endregion - #region Event Handlers - private void OnClassifyInput(Data data) - { - ClassifyResultData input = (ClassifyResultData)data; + #region Event Handlers + private void OnClassifyInput(Data data) + { + ClassifyResultData input = (ClassifyResultData)data; - bool bPassthrough = true; - foreach (var mapping in m_Mappings) + bool bPassthrough = true; + foreach (var mapping in m_Mappings) + { + if (mapping.m_Class == input.Result.top_class) + { + OnClassifierResult callback = mapping.m_Callback.ResolveDelegate() as OnClassifierResult; + if (callback != null) + { + callback(input.Result); + if (mapping.m_Exclusive) { - if (mapping.m_Class == input.Result.top_class) - { - OnClassifierResult callback = mapping.m_Callback.ResolveDelegate() as OnClassifierResult; - if (callback != null) - { - callback(input.Result); - if (mapping.m_Exclusive) - { - bPassthrough = false; - break; - } - } - } + bPassthrough = false; + break; } - - if (bPassthrough) - m_ClassifyOutput.SendData(data); + } } - #endregion + } + + if (bPassthrough) + m_ClassifyOutput.SendData(data); } + #endregion + } } \ No newline at end of file diff --git a/Scripts/Widgets/DataTypes.cs b/Scripts/Widgets/DataTypes.cs index 38cf5662d..96a8f1fdd 100755 --- a/Scripts/Widgets/DataTypes.cs +++ b/Scripts/Widgets/DataTypes.cs @@ -24,512 +24,514 @@ namespace IBM.Watson.DeveloperCloud.DataTypes { + /// + /// This data class is for text data to spoken by the TextToSpeech widget. + /// + public class TextToSpeechData : Widget.Data + { /// - /// This data class is for text data to spoken by the TextToSpeech widget. + /// Default constructor. /// - public class TextToSpeechData : Widget.Data + public TextToSpeechData() + { } + /// + /// String constructor. + /// + /// + public TextToSpeechData(string text) { - /// - /// Default constructor. - /// - public TextToSpeechData() - { } - /// - /// String constructor. - /// - /// - public TextToSpeechData(string text) - { - Text = text; - } - /// - /// Name of this data type. - /// - /// A human readable name for this data type. - public override string GetName() - { - return "TextToSpeech"; - } + Text = text; + } + /// + /// Name of this data type. + /// + /// A human readable name for this data type. + public override string GetName() + { + return "TextToSpeech"; + } - /// - /// The text to convert to speech. - /// - public string Text { get; set; } - }; + /// + /// The text to convert to speech. + /// + public string Text { get; set; } + }; + + /// + /// Data type for a source language change. + /// + public class LanguageData : Widget.Data + { + /// + /// Default constructor. + /// + public LanguageData() + { } /// - /// Data type for a source language change. + /// Constructor which takes the language ID as a string. /// - public class LanguageData : Widget.Data + /// The language ID. + public LanguageData(string language) { - /// - /// Default constructor. - /// - public LanguageData() - {} - - /// - /// Constructor which takes the language ID as a string. - /// - /// The language ID. - public LanguageData( string language ) - { - Language = language; - } - - /// - public override string GetName() - { - return "Language"; - } + Language = language; + } - /// - /// The language ID. - /// - public string Language { get; set; } - }; + /// + public override string GetName() + { + return "Language"; + } /// - /// Data type sent to change the voice type. + /// The language ID. + /// + public string Language { get; set; } + }; + + /// + /// Data type sent to change the voice type. + /// + public class VoiceData : Widget.Data + { + /// + /// Default constructor. /// - public class VoiceData : Widget.Data + public VoiceData() + { } + /// + /// Constructor which takes the voice type enumeration. + /// + /// The voice to select. + public VoiceData(VoiceType voice) { - /// - /// Default constructor. - /// - public VoiceData() - { } - /// - /// Constructor which takes the voice type enumeration. - /// - /// The voice to select. - public VoiceData( VoiceType voice ) - { - Voice = voice; - } + Voice = voice; + } - /// - public override string GetName() - { - return "Voice"; - } + /// + public override string GetName() + { + return "Voice"; + } + + /// + /// The enumeration of the voice to select. + /// + public VoiceType Voice { get; set; } + }; + + /// + /// This class holds a AudioClip and maximum sample level. + /// + public class AudioData : Widget.Data + { + /// + /// Default constructor. + /// + public AudioData() + { } - /// - /// The enumeration of the voice to select. - /// - public VoiceType Voice { get; set; } - }; + /// + ~AudioData() + { + UnityObjectUtil.DestroyUnityObject(Clip); + } /// - /// This class holds a AudioClip and maximum sample level. + /// Constructor. /// - public class AudioData : Widget.Data + /// The AudioClip. + /// The maximum sample level in the audio clip. + public AudioData(AudioClip clip, float maxLevel) { - /// - /// Default constructor. - /// - public AudioData() - { } - - /// - ~AudioData() - { - UnityObjectUtil.DestroyUnityObject( Clip ); - } + Clip = clip; + MaxLevel = maxLevel; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "Audio"; + } - /// - /// Constructor. - /// - /// The AudioClip. - /// The maximum sample level in the audio clip. - public AudioData(AudioClip clip, float maxLevel) - { - Clip = clip; - MaxLevel = maxLevel; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "Audio"; - } + /// + /// The AudioClip. + /// + public AudioClip Clip { get; set; } + /// + /// The maximum level in the audio clip. + /// + public float MaxLevel { get; set; } - /// - /// The AudioClip. - /// - public AudioClip Clip { get; set; } - /// - /// The maximum level in the audio clip. - /// - public float MaxLevel { get; set; } - - }; - - /// - /// This class holds a reference to WebCamTexture. - /// - public class WebCamTextureData : Widget.Data - { - /// - /// Default constructor. - /// - public WebCamTextureData() - { } - - /// - //~WebCamTextureData() - //{ - // UnityObjectUtil.DestroyUnityObject(CamTexture); - //} - - /// - /// Constructor. - /// - /// The WebCamTexture. - public WebCamTextureData(WebCamTexture camTexture, int requestedWidth = 640, int requestedHeight = 480, int requestedFPS = 60) - { - CamTexture = camTexture; - RequestedWidth = requestedWidth; - RequestedHeight = requestedHeight; - RequestedFPS = requestedFPS; - } - - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "WebCamTexture"; - } - - /// - /// The WebCamTexture. - /// - public WebCamTexture CamTexture { get; set; } - /// - /// The Requested Width of the WebCamTexture - /// - public int RequestedWidth { get; set; } - /// - /// The Requested Height of the WebCamTexture. - /// - public int RequestedHeight { get; set; } - /// - /// The Requested FPS of the WebCamTexture. - /// - public int RequestedFPS { get; set; } - - } - /// - /// This class holds a boolean value. - /// - public class BooleanData : Widget.Data - { - /// - /// Default constructor. - /// - public BooleanData() - { } - /// - /// Data constructor. - /// - /// - public BooleanData(bool b) - { - Boolean = b; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "Boolean"; - } + }; - /// - /// The bool value. - /// - public bool Boolean { get; set; } - }; + /// + /// This class holds a reference to WebCamTexture. + /// + public class WebCamTextureData : Widget.Data + { + /// + /// Default constructor. + /// + public WebCamTextureData() + { } + + /// + //~WebCamTextureData() + //{ + // UnityObjectUtil.DestroyUnityObject(CamTexture); + //} /// - /// Boolean state sent when TextToSpeech starts and ends playing audio. + /// Constructor. /// - public class SpeakingStateData : Widget.Data + /// The WebCamTexture. + public WebCamTextureData(WebCamTexture camTexture, int requestedWidth = 640, int requestedHeight = 480, int requestedFPS = 60) { - /// - /// Default constructor. - /// - public SpeakingStateData() - { } - /// - /// Data constructor. - /// - /// The speaking state, true for speaking, false for not. - public SpeakingStateData( bool b ) - { - Boolean = b; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "Speaking"; - } - - /// - /// Speaking state property. True if speaking, false if not. - /// - public bool Boolean { get; set; } + CamTexture = camTexture; + RequestedWidth = requestedWidth; + RequestedHeight = requestedHeight; + RequestedFPS = requestedFPS; } /// - /// Boolean state for disabling the microphone input. + /// Name of this data type. /// - public class DisableMicData : Widget.Data + /// The readable name. + public override string GetName() { - /// - /// Default constructor. - /// - public DisableMicData() - { } - /// - /// Data constructor. - /// - /// Disable microphone state. - public DisableMicData( bool b ) - { - Boolean = b; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "DisableMic"; - } - /// - /// Disable microphone state, true for disabled, false for not. - /// - public bool Boolean { get; set; } + return "WebCamTexture"; } /// - /// Boolean state for disabling the WebCam input. + /// The WebCamTexture. /// - public class DisableWebCamData : Widget.Data + public WebCamTexture CamTexture { get; set; } + /// + /// The Requested Width of the WebCamTexture + /// + public int RequestedWidth { get; set; } + /// + /// The Requested Height of the WebCamTexture. + /// + public int RequestedHeight { get; set; } + /// + /// The Requested FPS of the WebCamTexture. + /// + public int RequestedFPS { get; set; } + + } + /// + /// This class holds a boolean value. + /// + public class BooleanData : Widget.Data + { + /// + /// Default constructor. + /// + public BooleanData() + { } + /// + /// Data constructor. + /// + /// + public BooleanData(bool b) { - /// - /// Default constructor. - /// - public DisableWebCamData() - { } - /// - /// Data constructor. - /// - /// Disable WebCam state. - public DisableWebCamData(bool b) - { - Boolean = b; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "DisableWebCam"; - } - /// - /// Disable WebCam state, true for disabled, false for not. - /// - public bool Boolean { get; set; } + Boolean = b; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "Boolean"; } /// - /// Boolean state for disabling the CloseCaption output. + /// The bool value. + /// + public bool Boolean { get; set; } + }; + + /// + /// Boolean state sent when TextToSpeech starts and ends playing audio. + /// + public class SpeakingStateData : Widget.Data + { + /// + /// Default constructor. + /// + public SpeakingStateData() + { } + /// + /// Data constructor. /// - public class DisableCloseCaptionData : Widget.Data + /// The speaking state, true for speaking, false for not. + public SpeakingStateData(bool b) { - /// - /// Default constructor. - /// - public DisableCloseCaptionData() - { } - /// - /// Data constructor. - /// - /// Disable DisableCloseCaptionData state. - public DisableCloseCaptionData( bool b ) - { - Boolean = b; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "DisableCloseCaptionData"; - } - /// - /// Disable DisableCloseCaptionData state, true for disabled, false for not. - /// - public bool Boolean { get; set; } + Boolean = b; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "Speaking"; } /// - /// This class is for audio level data. + /// Speaking state property. True if speaking, false if not. + /// + public bool Boolean { get; set; } + } + + /// + /// Boolean state for disabling the microphone input. + /// + public class DisableMicData : Widget.Data + { + /// + /// Default constructor. /// - public class LevelData : Widget.Data + public DisableMicData() + { } + /// + /// Data constructor. + /// + /// Disable microphone state. + public DisableMicData(bool b) { - /// - /// Default constructor. - /// - public LevelData() - { } - /// - /// Data constructor. - /// - /// The level data. - public LevelData( float f , float m = 1.0f) - { - Float = f; - Modifier = m; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "Level"; - } - /// - /// The level data. - /// - public float Float { get; set; } + Boolean = b; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "DisableMic"; + } + /// + /// Disable microphone state, true for disabled, false for not. + /// + public bool Boolean { get; set; } + } + + /// + /// Boolean state for disabling the WebCam input. + /// + public class DisableWebCamData : Widget.Data + { + /// + /// Default constructor. + /// + public DisableWebCamData() + { } + /// + /// Data constructor. + /// + /// Disable WebCam state. + public DisableWebCamData(bool b) + { + Boolean = b; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "DisableWebCam"; + } + /// + /// Disable WebCam state, true for disabled, false for not. + /// + public bool Boolean { get; set; } + } + + /// + /// Boolean state for disabling the CloseCaption output. + /// + public class DisableCloseCaptionData : Widget.Data + { + /// + /// Default constructor. + /// + public DisableCloseCaptionData() + { } + /// + /// Data constructor. + /// + /// Disable DisableCloseCaptionData state. + public DisableCloseCaptionData(bool b) + { + Boolean = b; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "DisableCloseCaptionData"; + } + /// + /// Disable DisableCloseCaptionData state, true for disabled, false for not. + /// + public bool Boolean { get; set; } + } + + /// + /// This class is for audio level data. + /// + public class LevelData : Widget.Data + { + /// + /// Default constructor. + /// + public LevelData() + { } + /// + /// Data constructor. + /// + /// The level data. + public LevelData(float f, float m = 1.0f) + { + Float = f; + Modifier = m; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "Level"; + } + /// + /// The level data. + /// + public float Float { get; set; } - /// - /// Modifier of Level data. Default is 1.0 - /// - /// The modifier. - public float Modifier { get; set; } + /// + /// Modifier of Level data. Default is 1.0 + /// + /// The modifier. + public float Modifier { get; set; } - public float NormalizedFloat { get{ if(Modifier == 0.0f) Modifier = 1.0f; return Float / Modifier;}} - }; + public float NormalizedFloat { get { if (Modifier == 0.0f) Modifier = 1.0f; return Float / Modifier; } } + }; + /// + /// This class is for SpeechToText results. + /// + public class SpeechToTextData : Widget.Data + { /// - /// This class is for SpeechToText results. + /// Default constructor. /// - public class SpeechToTextData : Widget.Data + public SpeechToTextData() + { } + /// + /// Data constructor. + /// + /// The SpeechToText results. + public SpeechToTextData(SpeechRecognitionEvent result) { - /// - /// Default constructor. - /// - public SpeechToTextData() - { } - /// - /// Data constructor. - /// - /// The SpeechToText results. - public SpeechToTextData(SpeechRecognitionEvent result) - { - Results = result; - } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() + Results = result; + } + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "SpeechToText"; + } + /// + /// The Result object. + /// + public SpeechRecognitionEvent Results { get; set; } + + /// + /// Gets a value indicating whether the result text is final. + /// + /// true if the result text is final; otherwise, false. + public bool IsFinal + { + get + { + bool isFinal = false; + if (Results != null && Results.results.Length > 0) { - return "SpeechToText"; + isFinal = Results.results[0].final; } - /// - /// The Result object. - /// - public SpeechRecognitionEvent Results { get; set; } - - /// - /// Gets a value indicating whether the result text is final. - /// - /// true if the result text is final; otherwise, false. - public bool IsFinal + + return isFinal; + } + } + + public string _Text = null; + /// + /// Gets the highest confident text. + /// + /// The text with highest confidence or final text + public string Text + { + get + { + if (string.IsNullOrEmpty(_Text)) { - get{ - bool isFinal = false; - if (Results != null && Results.results.Length > 0) - { - isFinal = Results.results[0].final; - } - - return isFinal; + if (Results != null && Results.results.Length > 0) + { + SpeechRecognitionResult speechResult = Results.results[0]; + if (speechResult.alternatives != null && speechResult.alternatives.Length > 0) + { + _Text = speechResult.alternatives[0].transcript; } + } } + return _Text; - public string _Text = null; - /// - /// Gets the highest confident text. - /// - /// The text with highest confidence or final text - public string Text - { - get{ - if (string.IsNullOrEmpty(_Text)) - { - if (Results != null && Results.results.Length > 0) - { - SpeechRecognitionResult speechResult = Results.results[0]; - if (speechResult.alternatives != null && speechResult.alternatives.Length > 0) - { - _Text = speechResult.alternatives[0].transcript; - } - } - } - return _Text; - - } + } - } - }; + } + }; + /// + /// This class is for Natural Language Classify results. + /// + public class ClassifyResultData : Widget.Data + { + /// + /// Default constructor. + /// + public ClassifyResultData() + { } /// - /// This class is for Natural Language Classify results. + /// Data constructor. /// - public class ClassifyResultData : Widget.Data + /// The ClassifyResult object. + public ClassifyResultData(ClassifyResult result) { - /// - /// Default constructor. - /// - public ClassifyResultData() - { } - /// - /// Data constructor. - /// - /// The ClassifyResult object. - public ClassifyResultData( ClassifyResult result ) - { - Result = result; - } + Result = result; + } - /// - /// Name of this data type. - /// - /// The readable name. - public override string GetName() - { - return "ClassifyResult"; - } - /// - /// The ClassifyResult object. - /// - public ClassifyResult Result { get; set; } - }; + /// + /// Name of this data type. + /// + /// The readable name. + public override string GetName() + { + return "ClassifyResult"; + } + /// + /// The ClassifyResult object. + /// + public ClassifyResult Result { get; set; } + }; } diff --git a/Scripts/Widgets/EventWidget.cs b/Scripts/Widgets/EventWidget.cs old mode 100644 new mode 100755 index e3a96dab7..083ed5680 --- a/Scripts/Widgets/EventWidget.cs +++ b/Scripts/Widgets/EventWidget.cs @@ -24,48 +24,48 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// This Event Widget class maps events to a SerializedDelegate. - /// - public class EventWidget : Widget + /// + /// This Event Widget class maps events to a SerializedDelegate. + /// + public class EventWidget : Widget + { + #region Widget interface + /// + protected override string GetName() { - #region Widget interface - /// - protected override string GetName() - { - return "Event"; - } - #endregion + return "Event"; + } + #endregion - #region Private Data - [Serializable] - private class Mapping - { - public string m_Event = ""; - public SerializedDelegate m_Callback = new SerializedDelegate(typeof(EventManager.OnReceiveEvent)); - }; + #region Private Data + [Serializable] + private class Mapping + { + public string m_Event = ""; + public SerializedDelegate m_Callback = new SerializedDelegate(typeof(EventManager.OnReceiveEvent)); + }; - [SerializeField] - private List m_Mappings = new List(); - #endregion + [SerializeField] + private List m_Mappings = new List(); + #endregion - #region Event Handlers - private void OnEnable() - { - foreach (var mapping in m_Mappings) - { - EventManager.Instance.RegisterEventReceiver(mapping.m_Event, mapping.m_Callback.ResolveDelegate() as EventManager.OnReceiveEvent); - } - } + #region Event Handlers + private void OnEnable() + { + foreach (var mapping in m_Mappings) + { + EventManager.Instance.RegisterEventReceiver(mapping.m_Event, mapping.m_Callback.ResolveDelegate() as EventManager.OnReceiveEvent); + } + } - private void OnDisable() - { - foreach (var mapping in m_Mappings) - { - EventManager.Instance.UnregisterEventReceiver(mapping.m_Event, mapping.m_Callback.ResolveDelegate() as EventManager.OnReceiveEvent); - } - } - #endregion + private void OnDisable() + { + foreach (var mapping in m_Mappings) + { + EventManager.Instance.UnregisterEventReceiver(mapping.m_Event, mapping.m_Callback.ResolveDelegate() as EventManager.OnReceiveEvent); + } } + #endregion + } } \ No newline at end of file diff --git a/Scripts/Widgets/KeyboardWidget.cs b/Scripts/Widgets/KeyboardWidget.cs old mode 100644 new mode 100755 index 96ed1eb46..6bbffa36e --- a/Scripts/Widgets/KeyboardWidget.cs +++ b/Scripts/Widgets/KeyboardWidget.cs @@ -23,48 +23,48 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// This widget class maps key events to a SerializedDelegate. - /// - public class KeyboardWidget : Widget + /// + /// This widget class maps key events to a SerializedDelegate. + /// + public class KeyboardWidget : Widget + { + #region Widget interface + /// + protected override string GetName() { - #region Widget interface - /// - protected override string GetName() - { - return "Keyboard"; - } - #endregion + return "Keyboard"; + } + #endregion - #region Private Data - [Serializable] - private class Mapping - { - public KeyCode m_Key = (KeyCode)0; - public KeyModifiers m_Modifiers = KeyModifiers.NONE; - public string m_Event = ""; - }; + #region Private Data + [Serializable] + private class Mapping + { + public KeyCode m_Key = (KeyCode)0; + public KeyModifiers m_Modifiers = KeyModifiers.NONE; + public string m_Event = ""; + }; - [SerializeField] - private List m_Mappings = new List(); - #endregion + [SerializeField] + private List m_Mappings = new List(); + #endregion - #region Event Handlers - private void OnEnable() - { - foreach (var mapping in m_Mappings) - { - KeyEventManager.Instance.RegisterKeyEvent(mapping.m_Key, mapping.m_Modifiers, mapping.m_Event); - } - } + #region Event Handlers + private void OnEnable() + { + foreach (var mapping in m_Mappings) + { + KeyEventManager.Instance.RegisterKeyEvent(mapping.m_Key, mapping.m_Modifiers, mapping.m_Event); + } + } - private void OnDisable() - { - foreach (var mapping in m_Mappings) - { - KeyEventManager.Instance.UnregisterKeyEvent(mapping.m_Key, mapping.m_Modifiers, mapping.m_Event); - } - } - #endregion + private void OnDisable() + { + foreach (var mapping in m_Mappings) + { + KeyEventManager.Instance.UnregisterKeyEvent(mapping.m_Key, mapping.m_Modifiers, mapping.m_Event); + } } + #endregion + } } diff --git a/Scripts/Widgets/LanguageTranslatorWidget.cs b/Scripts/Widgets/LanguageTranslatorWidget.cs index b1c21ebfd..e3c63c953 100755 --- a/Scripts/Widgets/LanguageTranslatorWidget.cs +++ b/Scripts/Widgets/LanguageTranslatorWidget.cs @@ -30,384 +30,384 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// Translation widget to handle translation service calls + /// + public class LanguageTranslatorWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_SpeechInput = new Input("SpeechInput", typeof(SpeechToTextData), "OnSpeechInput"); + #endregion + + #region Outputs + [SerializeField] + private Output m_RecognizeLanguageOutput = new Output(typeof(LanguageData)); + [SerializeField] + private Output m_SpeechOutput = new Output(typeof(TextToSpeechData)); + [SerializeField] + private Output m_VoiceOutput = new Output(typeof(VoiceData)); + #endregion + + #region Private Data + private LanguageTranslation m_Translate = new LanguageTranslation(); + + [SerializeField, Tooltip("Source language, if empty language will be auto-detected.")] + private string m_SourceLanguage = string.Empty; + [SerializeField, Tooltip("Target language to translate into.")] + private string m_TargetLanguage = "es"; + [SerializeField, Tooltip("Input field for inputting speech")] + private InputField m_Input = null; + [SerializeField, Tooltip("Output text for showing translated text")] + private Text m_Output = null; + [SerializeField] + private Dropdown m_DropDownSourceLanguage = null; + [SerializeField] + private Dropdown m_DropDownTargetLanguage = null; + [SerializeField] + private string m_DefaultDomainToUse = "conversational"; + [SerializeField] + private string m_DetectLanguageName = "Detect Language"; + private string m_DetectLanguageID = ""; + + // Mapping from language ID to it's Name + private Dictionary m_LanguageIDToName = new Dictionary(); + // Mapping from language name to ID + private Dictionary m_LanguageNameToID = new Dictionary(); + // Mapping from language to a list of languages that can be translated into.. + private Dictionary> m_LanguageToTranslate = new Dictionary>(); + // array of availablel languages; + private string[] m_Languages = null; + // Last string of input text + private string m_TranslateText = string.Empty; + #endregion + + #region Widget interface + /// + protected override string GetName() + { + return "Translate"; + } + #endregion + + #region Public Members /// - /// Translation widget to handle translation service calls + /// Set or get the source language ID. If set to null or empty, then the language will be auto-detected. /// - public class LanguageTranslatorWidget : Widget + public string SourceLanguage { - #region Inputs - [SerializeField] - private Input m_SpeechInput = new Input("SpeechInput", typeof(SpeechToTextData), "OnSpeechInput"); - #endregion - - #region Outputs - [SerializeField] - private Output m_RecognizeLanguageOutput = new Output(typeof(LanguageData)); - [SerializeField] - private Output m_SpeechOutput = new Output(typeof(TextToSpeechData)); - [SerializeField] - private Output m_VoiceOutput = new Output(typeof(VoiceData)); - #endregion - - #region Private Data - private LanguageTranslation m_Translate = new LanguageTranslation(); - - [SerializeField, Tooltip("Source language, if empty language will be auto-detected.")] - private string m_SourceLanguage = string.Empty; - [SerializeField, Tooltip("Target language to translate into.")] - private string m_TargetLanguage = "es"; - [SerializeField, Tooltip("Input field for inputting speech")] - private InputField m_Input = null; - [SerializeField, Tooltip("Output text for showing translated text")] - private Text m_Output = null; - [SerializeField] - private Dropdown m_DropDownSourceLanguage = null; - [SerializeField] - private Dropdown m_DropDownTargetLanguage = null; - [SerializeField] - private string m_DefaultDomainToUse = "conversational"; - [SerializeField] - private string m_DetectLanguageName = "Detect Language"; - private string m_DetectLanguageID = ""; - - // Mapping from language ID to it's Name - private Dictionary m_LanguageIDToName = new Dictionary(); - // Mapping from language name to ID - private Dictionary m_LanguageNameToID = new Dictionary(); - // Mapping from language to a list of languages that can be translated into.. - private Dictionary> m_LanguageToTranslate = new Dictionary>(); - // array of availablel languages; - private string[] m_Languages = null; - // Last string of input text - private string m_TranslateText = string.Empty; - #endregion - - #region Widget interface - /// - protected override string GetName() + set + { + if (m_SourceLanguage != value) { - return "Translate"; - } - #endregion + m_SourceLanguage = value; - #region Public Members - /// - /// Set or get the source language ID. If set to null or empty, then the language will be auto-detected. - /// - public string SourceLanguage - { - set - { - if (m_SourceLanguage != value) - { - m_SourceLanguage = value; - - if (m_RecognizeLanguageOutput.IsConnected && !string.IsNullOrEmpty(m_SourceLanguage)) - m_RecognizeLanguageOutput.SendData(new LanguageData(m_SourceLanguage)); - ResetSourceLanguageDropDown(); - ResetTargetLanguageDropDown(); - } - } - get { return m_SourceLanguage; } + if (m_RecognizeLanguageOutput.IsConnected && !string.IsNullOrEmpty(m_SourceLanguage)) + m_RecognizeLanguageOutput.SendData(new LanguageData(m_SourceLanguage)); + ResetSourceLanguageDropDown(); + ResetTargetLanguageDropDown(); } + } + get { return m_SourceLanguage; } + } - /// - /// Set or get the target language ID. - /// - public string TargetLanguage + /// + /// Set or get the target language ID. + /// + public string TargetLanguage + { + set + { + if (TargetLanguage != value) { - set - { - if (TargetLanguage != value) - { - m_TargetLanguage = value; - ResetVoiceForTargetLanguage(); - } - } - get { return m_TargetLanguage; } + m_TargetLanguage = value; + ResetVoiceForTargetLanguage(); } - #endregion + } + get { return m_TargetLanguage; } + } + #endregion - #region Event Handlers - private void OnEnable() - { - Log.Status("TranslatorWidget", "OnEnable"); - //UnityEngine.Debug.LogWarning("TranslatorWidget - OnEnable"); - m_Translate.GetLanguages(OnGetLanguages); - } + #region Event Handlers + private void OnEnable() + { + Log.Status("TranslatorWidget", "OnEnable"); + //UnityEngine.Debug.LogWarning("TranslatorWidget - OnEnable"); + m_Translate.GetLanguages(OnGetLanguages); + } - /// - protected override void Awake() - { - base.Awake(); - - if (m_Input != null) - m_Input.onEndEdit.AddListener(delegate { OnInputEnd(); }); - if (m_DropDownSourceLanguage != null) - m_DropDownSourceLanguage.onValueChanged.AddListener(delegate { DropDownSourceValueChanged(); }); - if (m_DropDownTargetLanguage != null) - m_DropDownTargetLanguage.onValueChanged.AddListener(delegate { DropDownTargetValueChanged(); }); - } + /// + protected override void Awake() + { + base.Awake(); + + if (m_Input != null) + m_Input.onEndEdit.AddListener(delegate { OnInputEnd(); }); + if (m_DropDownSourceLanguage != null) + m_DropDownSourceLanguage.onValueChanged.AddListener(delegate { DropDownSourceValueChanged(); }); + if (m_DropDownTargetLanguage != null) + m_DropDownTargetLanguage.onValueChanged.AddListener(delegate { DropDownTargetValueChanged(); }); + } - /// - protected override void Start() - { - base.Start(); + /// + protected override void Start() + { + base.Start(); - // resolve variables - m_SourceLanguage = Config.Instance.ResolveVariables(m_SourceLanguage); - m_TargetLanguage = Config.Instance.ResolveVariables(m_TargetLanguage); + // resolve variables + m_SourceLanguage = Config.Instance.ResolveVariables(m_SourceLanguage); + m_TargetLanguage = Config.Instance.ResolveVariables(m_TargetLanguage); - if (m_RecognizeLanguageOutput.IsConnected && !string.IsNullOrEmpty(m_SourceLanguage)) - m_RecognizeLanguageOutput.SendData(new LanguageData(m_SourceLanguage)); - } + if (m_RecognizeLanguageOutput.IsConnected && !string.IsNullOrEmpty(m_SourceLanguage)) + m_RecognizeLanguageOutput.SendData(new LanguageData(m_SourceLanguage)); + } - private void OnInputEnd() - { - if (m_Input != null) - { - if (!string.IsNullOrEmpty(TargetLanguage)) - Translate(m_Input.text); - else - Log.Error("TranslatorWidget", "OnTranslation - Target Language should be set!"); - } - } + private void OnInputEnd() + { + if (m_Input != null) + { + if (!string.IsNullOrEmpty(TargetLanguage)) + Translate(m_Input.text); + else + Log.Error("TranslatorWidget", "OnTranslation - Target Language should be set!"); + } + } - private void OnSpeechInput(Data data) - { - SpeechToTextData speech = data as SpeechToTextData; - if (speech != null && speech.Results.HasFinalResult()) - Translate(speech.Results.results[0].alternatives[0].transcript); - } + private void OnSpeechInput(Data data) + { + SpeechToTextData speech = data as SpeechToTextData; + if (speech != null && speech.Results.HasFinalResult()) + Translate(speech.Results.results[0].alternatives[0].transcript); + } - private void OnGetLanguages(Languages languages) - { - if (languages != null && languages.languages.Length > 0) - { - Log.Status("TranslatorWidget", "OnGetLanguagesAndGetModelsAfter as {0}", languages.languages.Length); - m_LanguageIDToName.Clear(); - - foreach (var lang in languages.languages) - { - m_LanguageIDToName[lang.language] = lang.name; - m_LanguageNameToID[lang.name] = lang.language; - } - - m_LanguageIDToName[m_DetectLanguageID] = m_DetectLanguageName; - m_LanguageNameToID[m_DetectLanguageName] = m_DetectLanguageID; - m_Translate.GetModels(OnGetModels); //To fill dropdown with models to use in Translation - } - else - { - Log.Error("TranslatorWidget", "OnGetLanguages - There is no language to translate. Check the connections and service of Translation Service."); - } - } + private void OnGetLanguages(Languages languages) + { + if (languages != null && languages.languages.Length > 0) + { + Log.Status("TranslatorWidget", "OnGetLanguagesAndGetModelsAfter as {0}", languages.languages.Length); + m_LanguageIDToName.Clear(); - private void OnGetModels(TranslationModels models) + foreach (var lang in languages.languages) { - Log.Status("TranslatorWidget", "OnGetModels, Count: {0}", models.models.Length); - if (models != null && models.models.Length > 0) - { - m_LanguageToTranslate.Clear(); - - List listLanguages = new List(); //From - To language list to use in translation - - //Adding initial language as detected! - listLanguages.Add(m_DetectLanguageID); - m_LanguageToTranslate.Add(m_DetectLanguageID, new List()); - - foreach (var model in models.models) - { - if (string.Equals(model.domain, m_DefaultDomainToUse)) - { - if (m_LanguageToTranslate.ContainsKey(model.source)) - { - if (!m_LanguageToTranslate[model.source].Contains(model.target)) - m_LanguageToTranslate[model.source].Add(model.target); - } - else - { - m_LanguageToTranslate.Add(model.source, new List()); - m_LanguageToTranslate[model.source].Add(model.target); - } - - if (!listLanguages.Contains(model.source)) - listLanguages.Add(model.source); - if (!listLanguages.Contains(model.target)) - listLanguages.Add(model.target); - - if (!m_LanguageToTranslate[m_DetectLanguageID].Contains(model.target)) - m_LanguageToTranslate[m_DetectLanguageID].Add(model.target); - } - } - - m_Languages = listLanguages.ToArray(); - ResetSourceLanguageDropDown(); - ResetVoiceForTargetLanguage(); - } + m_LanguageIDToName[lang.language] = lang.name; + m_LanguageNameToID[lang.name] = lang.language; } - #endregion - #region Private Functions - private void Translate(string text) - { - if (!string.IsNullOrEmpty(text)) - { - m_TranslateText = text; + m_LanguageIDToName[m_DetectLanguageID] = m_DetectLanguageName; + m_LanguageNameToID[m_DetectLanguageName] = m_DetectLanguageID; + m_Translate.GetModels(OnGetModels); //To fill dropdown with models to use in Translation + } + else + { + Log.Error("TranslatorWidget", "OnGetLanguages - There is no language to translate. Check the connections and service of Translation Service."); + } + } - if (m_Input != null) - m_Input.text = text; + private void OnGetModels(TranslationModels models) + { + Log.Status("TranslatorWidget", "OnGetModels, Count: {0}", models.models.Length); + if (models != null && models.models.Length > 0) + { + m_LanguageToTranslate.Clear(); - new TranslateRequest(this, text); - } - } + List listLanguages = new List(); //From - To language list to use in translation - private class TranslateRequest - { - private LanguageTranslatorWidget m_Widget; - private string m_Text; + //Adding initial language as detected! + listLanguages.Add(m_DetectLanguageID); + m_LanguageToTranslate.Add(m_DetectLanguageID, new List()); - public TranslateRequest(LanguageTranslatorWidget widget, string text) + foreach (var model in models.models) + { + if (string.Equals(model.domain, m_DefaultDomainToUse)) + { + if (m_LanguageToTranslate.ContainsKey(model.source)) { - m_Widget = widget; - m_Text = text; - - if (string.IsNullOrEmpty(m_Widget.SourceLanguage)) - m_Widget.m_Translate.Identify(m_Text, OnIdentified); - else - m_Widget.m_Translate.GetTranslation(m_Text, m_Widget.SourceLanguage, m_Widget.TargetLanguage, OnGetTranslation); + if (!m_LanguageToTranslate[model.source].Contains(model.target)) + m_LanguageToTranslate[model.source].Add(model.target); } - - private void OnIdentified(string language) + else { - if (!string.IsNullOrEmpty(language)) - { - m_Widget.SourceLanguage = language; - m_Widget.m_Translate.GetTranslation(m_Text, language, m_Widget.TargetLanguage, OnGetTranslation); - } - else - Log.Error("TranslateWidget", "Failed to identify language: {0}", m_Text); + m_LanguageToTranslate.Add(model.source, new List()); + m_LanguageToTranslate[model.source].Add(model.target); } - private void OnGetTranslation(Translations translations) - { - if (translations != null && translations.translations.Length > 0) - m_Widget.SetOutput(translations.translations[0].translation); - } - }; + if (!listLanguages.Contains(model.source)) + listLanguages.Add(model.source); + if (!listLanguages.Contains(model.target)) + listLanguages.Add(model.target); - private void SetOutput(string text) - { - Log.Debug("TranslateWidget", "SetOutput(): {0}", text); + if (!m_LanguageToTranslate[m_DetectLanguageID].Contains(model.target)) + m_LanguageToTranslate[m_DetectLanguageID].Add(model.target); + } + } - if (m_Output != null) - m_Output.text = text; + m_Languages = listLanguages.ToArray(); + ResetSourceLanguageDropDown(); + ResetVoiceForTargetLanguage(); + } + } + #endregion - if (m_SpeechOutput.IsConnected) - m_SpeechOutput.SendData(new TextToSpeechData(text)); - } + #region Private Functions + private void Translate(string text) + { + if (!string.IsNullOrEmpty(text)) + { + m_TranslateText = text; + + if (m_Input != null) + m_Input.text = text; - private void ResetSourceLanguageDropDown() + new TranslateRequest(this, text); + } + } + + private class TranslateRequest + { + private LanguageTranslatorWidget m_Widget; + private string m_Text; + + public TranslateRequest(LanguageTranslatorWidget widget, string text) + { + m_Widget = widget; + m_Text = text; + + if (string.IsNullOrEmpty(m_Widget.SourceLanguage)) + m_Widget.m_Translate.Identify(m_Text, OnIdentified); + else + m_Widget.m_Translate.GetTranslation(m_Text, m_Widget.SourceLanguage, m_Widget.TargetLanguage, OnGetTranslation); + } + + private void OnIdentified(string language) + { + if (!string.IsNullOrEmpty(language)) { - if (m_DropDownSourceLanguage != null) - { - m_DropDownSourceLanguage.options.Clear(); + m_Widget.SourceLanguage = language; + m_Widget.m_Translate.GetTranslation(m_Text, language, m_Widget.TargetLanguage, OnGetTranslation); + } + else + Log.Error("TranslateWidget", "Failed to identify language: {0}", m_Text); + } + + private void OnGetTranslation(Translations translations) + { + if (translations != null && translations.translations.Length > 0) + m_Widget.SetOutput(translations.translations[0].translation); + } + }; + + private void SetOutput(string text) + { + Log.Debug("TranslateWidget", "SetOutput(): {0}", text); - int selected = 0; - foreach (string itemLanguage in m_Languages) - { - if (m_LanguageIDToName.ContainsKey(itemLanguage)) - m_DropDownSourceLanguage.options.Add(new Dropdown.OptionData(m_LanguageIDToName[itemLanguage])); + if (m_Output != null) + m_Output.text = text; - if (String.Equals(SourceLanguage, itemLanguage)) - selected = m_DropDownSourceLanguage.options.Count - 1; - } + if (m_SpeechOutput.IsConnected) + m_SpeechOutput.SendData(new TextToSpeechData(text)); + } - m_DropDownSourceLanguage.value = selected; - } - } + private void ResetSourceLanguageDropDown() + { + if (m_DropDownSourceLanguage != null) + { + m_DropDownSourceLanguage.options.Clear(); - private void DropDownSourceValueChanged() + int selected = 0; + foreach (string itemLanguage in m_Languages) { - if (m_DropDownSourceLanguage != null && m_DropDownSourceLanguage.options.Count > 0) - { - string selected = m_DropDownSourceLanguage.options[m_DropDownSourceLanguage.value].text; - if (m_LanguageNameToID.ContainsKey(selected)) - { - selected = m_LanguageNameToID[selected]; - if (selected != SourceLanguage) - { - SourceLanguage = selected; - Translate(m_TranslateText); - } - } - } + if (m_LanguageIDToName.ContainsKey(itemLanguage)) + m_DropDownSourceLanguage.options.Add(new Dropdown.OptionData(m_LanguageIDToName[itemLanguage])); + + if (String.Equals(SourceLanguage, itemLanguage)) + selected = m_DropDownSourceLanguage.options.Count - 1; } - private void DropDownTargetValueChanged() + m_DropDownSourceLanguage.value = selected; + } + } + + private void DropDownSourceValueChanged() + { + if (m_DropDownSourceLanguage != null && m_DropDownSourceLanguage.options.Count > 0) + { + string selected = m_DropDownSourceLanguage.options[m_DropDownSourceLanguage.value].text; + if (m_LanguageNameToID.ContainsKey(selected)) { - if (m_DropDownTargetLanguage != null && m_DropDownTargetLanguage.options.Count > 0) - { - string selected = m_DropDownTargetLanguage.options[m_DropDownTargetLanguage.value].text; - if (m_LanguageNameToID.ContainsKey(selected)) - { - string target = m_LanguageNameToID[selected]; - if (target != TargetLanguage) - { - TargetLanguage = target; - Translate(m_TranslateText); - } - } - } + selected = m_LanguageNameToID[selected]; + if (selected != SourceLanguage) + { + SourceLanguage = selected; + Translate(m_TranslateText); + } } + } + } - private void ResetTargetLanguageDropDown() + private void DropDownTargetValueChanged() + { + if (m_DropDownTargetLanguage != null && m_DropDownTargetLanguage.options.Count > 0) + { + string selected = m_DropDownTargetLanguage.options[m_DropDownTargetLanguage.value].text; + if (m_LanguageNameToID.ContainsKey(selected)) { - if (m_DropDownTargetLanguage != null) - { - if (!string.IsNullOrEmpty(SourceLanguage) && m_LanguageToTranslate.ContainsKey(SourceLanguage)) - { - //Add target language corresponding source language - m_DropDownTargetLanguage.options.Clear(); - int selected = 0; - - foreach (string itemLanguage in m_LanguageToTranslate[SourceLanguage]) - { - if (string.Equals(itemLanguage, SourceLanguage)) - continue; - - m_DropDownTargetLanguage.options.Add(new Dropdown.OptionData(m_LanguageIDToName[itemLanguage])); - - if (String.Equals(TargetLanguage, itemLanguage)) - selected = m_DropDownTargetLanguage.options.Count - 1; - } - - m_DropDownTargetLanguage.captionText.text = m_DropDownTargetLanguage.options[selected].text; - m_DropDownTargetLanguage.value = selected; - } - } + string target = m_LanguageNameToID[selected]; + if (target != TargetLanguage) + { + TargetLanguage = target; + Translate(m_TranslateText); + } } + } + } - private void ResetVoiceForTargetLanguage() + private void ResetTargetLanguageDropDown() + { + if (m_DropDownTargetLanguage != null) + { + if (!string.IsNullOrEmpty(SourceLanguage) && m_LanguageToTranslate.ContainsKey(SourceLanguage)) { - if (m_VoiceOutput.IsConnected) - { - if (TargetLanguage == "en") - m_VoiceOutput.SendData(new VoiceData(VoiceType.en_US_Michael)); - else if (TargetLanguage == "de") - m_VoiceOutput.SendData(new VoiceData(VoiceType.de_DE_Dieter)); - else if (TargetLanguage == "es") - m_VoiceOutput.SendData(new VoiceData(VoiceType.es_ES_Enrique)); - else if (TargetLanguage == "fr") - m_VoiceOutput.SendData(new VoiceData(VoiceType.fr_FR_Renee)); - else if (TargetLanguage == "it") - m_VoiceOutput.SendData(new VoiceData(VoiceType.it_IT_Francesca)); - else if (TargetLanguage == "ja") - m_VoiceOutput.SendData(new VoiceData(VoiceType.ja_JP_Emi)); - else - Log.Warning("TranslateWidget", "Unsupported voice for language {0}", TargetLanguage); - } + //Add target language corresponding source language + m_DropDownTargetLanguage.options.Clear(); + int selected = 0; + + foreach (string itemLanguage in m_LanguageToTranslate[SourceLanguage]) + { + if (string.Equals(itemLanguage, SourceLanguage)) + continue; + + m_DropDownTargetLanguage.options.Add(new Dropdown.OptionData(m_LanguageIDToName[itemLanguage])); + + if (String.Equals(TargetLanguage, itemLanguage)) + selected = m_DropDownTargetLanguage.options.Count - 1; + } + + m_DropDownTargetLanguage.captionText.text = m_DropDownTargetLanguage.options[selected].text; + m_DropDownTargetLanguage.value = selected; } - #endregion + } + } + + private void ResetVoiceForTargetLanguage() + { + if (m_VoiceOutput.IsConnected) + { + if (TargetLanguage == "en") + m_VoiceOutput.SendData(new VoiceData(VoiceType.en_US_Michael)); + else if (TargetLanguage == "de") + m_VoiceOutput.SendData(new VoiceData(VoiceType.de_DE_Dieter)); + else if (TargetLanguage == "es") + m_VoiceOutput.SendData(new VoiceData(VoiceType.es_ES_Enrique)); + else if (TargetLanguage == "fr") + m_VoiceOutput.SendData(new VoiceData(VoiceType.fr_FR_Renee)); + else if (TargetLanguage == "it") + m_VoiceOutput.SendData(new VoiceData(VoiceType.it_IT_Francesca)); + else if (TargetLanguage == "ja") + m_VoiceOutput.SendData(new VoiceData(VoiceType.ja_JP_Emi)); + else + Log.Warning("TranslateWidget", "Unsupported voice for language {0}", TargetLanguage); + } } + #endregion + } } diff --git a/Scripts/Widgets/MicrophoneWidget.cs b/Scripts/Widgets/MicrophoneWidget.cs index dac89cf48..034521347 100755 --- a/Scripts/Widgets/MicrophoneWidget.cs +++ b/Scripts/Widgets/MicrophoneWidget.cs @@ -28,341 +28,341 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// This widget records audio from the microphone device. + /// + public class MicrophoneWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_DisableInput = new Input("Disable", typeof(DisableMicData), "OnDisableInput"); + #endregion + + #region Outputs + [SerializeField] + private Output m_AudioOutput = new Output(typeof(AudioData)); + [SerializeField] + private Output m_LevelOutput = new Output(typeof(LevelData)); + [SerializeField] + private Output m_ActivateOutput = new Output(typeof(BooleanData)); + #endregion + + #region Private Data + private bool m_Active = false; + private bool m_Disabled = false; + private bool m_Failure = false; + private DateTime m_LastFailure = DateTime.Now; + + [SerializeField] + private bool m_ActivateOnStart = true; + [SerializeField, Tooltip("Size of recording buffer in seconds.")] + private int m_RecordingBufferSize = 2; + [SerializeField] + private int m_RecordingHZ = 22050; // default recording HZ + [SerializeField, Tooltip("ID of the microphone to use.")] + private string m_MicrophoneID = null; // what microphone to use for recording. + [SerializeField, Tooltip("How often to sample for level output.")] + private float m_LevelOutputInterval = 0.05f; + [SerializeField] + private float m_LevelOutputModifier = 1.0f; + [SerializeField, Tooltip("If true, microphone will playback recorded audio on stop.")] + private bool m_PlaybackRecording = false; + [SerializeField] + private Text m_StatusText = null; + + private int m_RecordingRoutine = 0; // ID of our co-routine when recording, 0 if not recording currently. + private AudioClip m_Recording = null; + private List m_Playback = new List(); + #endregion + + #region Constants + // how often to retry the open the microphone on failure + private const int RETRY_INTERVAL = 10000; + #endregion + + #region Public Properties /// - /// This widget records audio from the microphone device. + /// Returns a list of available microphone devices. /// - public class MicrophoneWidget : Widget + public string[] Microphones { get { return Microphone.devices; } } + /// + /// True if microphone is active, false if inactive. + /// + public bool Active { - #region Inputs - [SerializeField] - private Input m_DisableInput = new Input("Disable", typeof(DisableMicData), "OnDisableInput"); - #endregion - - #region Outputs - [SerializeField] - private Output m_AudioOutput = new Output(typeof(AudioData)); - [SerializeField] - private Output m_LevelOutput = new Output(typeof(LevelData)); - [SerializeField] - private Output m_ActivateOutput = new Output(typeof(BooleanData)); - #endregion - - #region Private Data - private bool m_Active = false; - private bool m_Disabled = false; - private bool m_Failure = false; - private DateTime m_LastFailure = DateTime.Now; - - [SerializeField] - private bool m_ActivateOnStart = true; - [SerializeField, Tooltip("Size of recording buffer in seconds.")] - private int m_RecordingBufferSize = 2; - [SerializeField] - private int m_RecordingHZ = 22050; // default recording HZ - [SerializeField, Tooltip("ID of the microphone to use.")] - private string m_MicrophoneID = null; // what microphone to use for recording. - [SerializeField, Tooltip("How often to sample for level output.")] - private float m_LevelOutputInterval = 0.05f; - [SerializeField] - private float m_LevelOutputModifier = 1.0f; - [SerializeField, Tooltip("If true, microphone will playback recorded audio on stop.")] - private bool m_PlaybackRecording = false; - [SerializeField] - private Text m_StatusText = null; - - private int m_RecordingRoutine = 0; // ID of our co-routine when recording, 0 if not recording currently. - private AudioClip m_Recording = null; - private List m_Playback = new List(); - #endregion - - #region Constants - // how often to retry the open the microphone on failure - private const int RETRY_INTERVAL = 10000; - #endregion - - #region Public Properties - /// - /// Returns a list of available microphone devices. - /// - public string[] Microphones { get { return Microphone.devices; } } - /// - /// True if microphone is active, false if inactive. - /// - public bool Active + get { return m_Active; } + set + { + if (m_Active != value) { - get { return m_Active; } - set - { - if (m_Active != value) - { - m_Active = value; - if (m_Active && !m_Disabled) - StartRecording(); - else - StopRecording(); - } - } + m_Active = value; + if (m_Active && !m_Disabled) + StartRecording(); + else + StopRecording(); } - /// - /// True if microphone is disabled, false if enabled. - /// - public bool Disable + } + } + /// + /// True if microphone is disabled, false if enabled. + /// + public bool Disable + { + get { return m_Disabled; } + set + { + if (m_Disabled != value) { - get { return m_Disabled; } - set - { - if (m_Disabled != value) - { - m_Disabled = value; - if (m_Active && !m_Disabled) - StartRecording(); - else - StopRecording(); - } - } + m_Disabled = value; + if (m_Active && !m_Disabled) + StartRecording(); + else + StopRecording(); } - /// - /// This is set to true when the microhphone fails, the update will continue to try to start - /// the microphone so long as it's active. - /// - public bool Failure + } + } + /// + /// This is set to true when the microhphone fails, the update will continue to try to start + /// the microphone so long as it's active. + /// + public bool Failure + { + get { return m_Failure; } + private set + { + if (m_Failure != value) { - get { return m_Failure; } - private set - { - if (m_Failure != value) - { - m_Failure = value; - if (m_Failure) - m_LastFailure = DateTime.Now; - } - } + m_Failure = value; + if (m_Failure) + m_LastFailure = DateTime.Now; } + } + } - /// - /// Button handler for toggling the active state. - /// - public void OnToggleActive() - { - Active = !Active; - } - #endregion + /// + /// Button handler for toggling the active state. + /// + public void OnToggleActive() + { + Active = !Active; + } + #endregion - #region Public Functions - /// - /// Activates the microphone. - /// - public void ActivateMicrophone() - { - Active = true; - } + #region Public Functions + /// + /// Activates the microphone. + /// + public void ActivateMicrophone() + { + Active = true; + } - /// - /// Deactivates the microphone. - /// - public void DeactivateMicrophone() - { - Active = false; - } + /// + /// Deactivates the microphone. + /// + public void DeactivateMicrophone() + { + Active = false; + } - #endregion + #endregion - #region Widget interface - /// - protected override string GetName() - { - return "Microphone"; - } - #endregion + #region Widget interface + /// + protected override string GetName() + { + return "Microphone"; + } + #endregion - #region Event Handlers - /// - protected override void Start() - { - base.Start(); - if (m_ActivateOnStart) - Active = true; - } - private void Update() - { - if (Failure && Active && !Disable - && (DateTime.Now - m_LastFailure).TotalMilliseconds > RETRY_INTERVAL) - { - // try to restart the recording.. - StartRecording(); - } - } - private void OnDisableInput(Data data) - { - Disable = ((DisableMicData)data).Boolean; - } + #region Event Handlers + /// + protected override void Start() + { + base.Start(); + if (m_ActivateOnStart) + Active = true; + } + private void Update() + { + if (Failure && Active && !Disable + && (DateTime.Now - m_LastFailure).TotalMilliseconds > RETRY_INTERVAL) + { + // try to restart the recording.. + StartRecording(); + } + } + private void OnDisableInput(Data data) + { + Disable = ((DisableMicData)data).Boolean; + } - void OnDestroy() - { - Active = false; - Disable = true; - } + void OnDestroy() + { + Active = false; + Disable = true; + } - #endregion + #endregion - #region Recording Functions - private void StartRecording() - { - if (m_RecordingRoutine == 0) - { - UnityObjectUtil.StartDestroyQueue(); + #region Recording Functions + private void StartRecording() + { + if (m_RecordingRoutine == 0) + { + UnityObjectUtil.StartDestroyQueue(); - m_RecordingRoutine = Runnable.Run(RecordingHandler()); - m_ActivateOutput.SendData(new BooleanData(true)); + m_RecordingRoutine = Runnable.Run(RecordingHandler()); + m_ActivateOutput.SendData(new BooleanData(true)); - if (m_StatusText != null) - m_StatusText.text = "RECORDING"; - } - } + if (m_StatusText != null) + m_StatusText.text = "RECORDING"; + } + } - private void StopRecording() + private void StopRecording() + { + if (m_RecordingRoutine != 0) + { + Microphone.End(m_MicrophoneID); + Runnable.Stop(m_RecordingRoutine); + m_RecordingRoutine = 0; + + m_ActivateOutput.SendData(new BooleanData(false)); + if (m_StatusText != null) + m_StatusText.text = "STOPPED"; + + if (m_PlaybackRecording && m_Playback.Count > 0) { - if (m_RecordingRoutine != 0) + AudioClip combined = AudioClipUtil.Combine(m_Playback.ToArray()); + if (combined != null) + { + AudioSource source = GetComponentInChildren(); + if (source != null) { - Microphone.End(m_MicrophoneID); - Runnable.Stop(m_RecordingRoutine); - m_RecordingRoutine = 0; - - m_ActivateOutput.SendData(new BooleanData(false)); - if (m_StatusText != null) - m_StatusText.text = "STOPPED"; - - if (m_PlaybackRecording && m_Playback.Count > 0) - { - AudioClip combined = AudioClipUtil.Combine(m_Playback.ToArray()); - if (combined != null) - { - AudioSource source = GetComponentInChildren(); - if (source != null) - { - // destroy any previous audio clip.. - if (source.clip != null) - UnityObjectUtil.DestroyUnityObject(source.clip); - - source.spatialBlend = 0.0f; // 2D sound - source.loop = false; // do not loop - source.clip = combined; // clip - source.Play(); - } - else - Log.Warning("MicrophoneWidget", "Failed to find AudioSource."); - } - - foreach (var clip in m_Playback) - UnityObjectUtil.DestroyUnityObject(clip); - m_Playback.Clear(); - } + // destroy any previous audio clip.. + if (source.clip != null) + UnityObjectUtil.DestroyUnityObject(source.clip); + + source.spatialBlend = 0.0f; // 2D sound + source.loop = false; // do not loop + source.clip = combined; // clip + source.Play(); } + else + Log.Warning("MicrophoneWidget", "Failed to find AudioSource."); + } + + foreach (var clip in m_Playback) + UnityObjectUtil.DestroyUnityObject(clip); + m_Playback.Clear(); } + } + } - private IEnumerator RecordingHandler() - { - Failure = false; + private IEnumerator RecordingHandler() + { + Failure = false; #if UNITY_WEBPLAYER yield return Application.RequestUserAuthorization( UserAuthorization.Microphone ); #endif - m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ); - yield return null; // let m_RecordingRoutine get set.. + m_Recording = Microphone.Start(m_MicrophoneID, true, m_RecordingBufferSize, m_RecordingHZ); + yield return null; // let m_RecordingRoutine get set.. - if (m_Recording == null) - { - Failure = true; - StopRecording(); - yield break; - } + if (m_Recording == null) + { + Failure = true; + StopRecording(); + yield break; + } - bool bFirstBlock = true; - int midPoint = m_Recording.samples / 2; + bool bFirstBlock = true; + int midPoint = m_Recording.samples / 2; - bool bOutputLevelData = m_LevelOutput.IsConnected; - bool bOutputAudio = m_AudioOutput.IsConnected || m_PlaybackRecording; + bool bOutputLevelData = m_LevelOutput.IsConnected; + bool bOutputAudio = m_AudioOutput.IsConnected || m_PlaybackRecording; - int lastReadPos = 0; - float[] samples = null; + int lastReadPos = 0; + float[] samples = null; - while (m_RecordingRoutine != 0 && m_Recording != null) - { - int writePos = Microphone.GetPosition(m_MicrophoneID); - if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID)) - { - Log.Error("MicrophoneWidget", "Microphone disconnected."); - - Failure = true; - StopRecording(); - yield break; - } - - if (bOutputAudio) - { - if ((bFirstBlock && writePos >= midPoint) - || (!bFirstBlock && writePos < midPoint)) - { - // front block is recorded, make a RecordClip and pass it onto our callback. - samples = new float[midPoint]; - m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint); - - AudioData record = new AudioData(); - record.MaxLevel = Mathf.Max(samples); - record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false); - record.Clip.SetData(samples, 0); - - if (m_PlaybackRecording) - m_Playback.Add(record.Clip); - if (m_AudioOutput.IsConnected && !m_AudioOutput.SendData(record)) - StopRecording(); // automatically stop recording if the callback goes away. - - bFirstBlock = !bFirstBlock; - } - else - { - // calculate the number of samples remaining until we ready for a block of audio, - // and wait that amount of time it will take to record. - int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos); - float timeRemaining = (float)remaining / (float)m_RecordingHZ; - if (bOutputLevelData && timeRemaining > m_LevelOutputInterval) - timeRemaining = m_LevelOutputInterval; - yield return new WaitForSeconds(timeRemaining); - } - } - else - { - yield return new WaitForSeconds(m_LevelOutputInterval); - } - - if (m_Recording != null && bOutputLevelData) - { - float fLevel = 0.0f; - if (writePos < lastReadPos) - { - // write has wrapped, grab the last bit from the buffer.. - samples = new float[m_Recording.samples - lastReadPos]; - m_Recording.GetData(samples, lastReadPos); - fLevel = Mathf.Max(fLevel, Mathf.Max(samples)); - - lastReadPos = 0; - } - - if (lastReadPos < writePos) - { - samples = new float[writePos - lastReadPos]; - m_Recording.GetData(samples, lastReadPos); - fLevel = Mathf.Max(fLevel, Mathf.Max(samples)); - - lastReadPos = writePos; - } - - m_LevelOutput.SendData(new LevelData(fLevel * m_LevelOutputModifier, m_LevelOutputModifier)); - } - } + while (m_RecordingRoutine != 0 && m_Recording != null) + { + int writePos = Microphone.GetPosition(m_MicrophoneID); + if (writePos > m_Recording.samples || !Microphone.IsRecording(m_MicrophoneID)) + { + Log.Error("MicrophoneWidget", "Microphone disconnected."); + + Failure = true; + StopRecording(); + yield break; + } + + if (bOutputAudio) + { + if ((bFirstBlock && writePos >= midPoint) + || (!bFirstBlock && writePos < midPoint)) + { + // front block is recorded, make a RecordClip and pass it onto our callback. + samples = new float[midPoint]; + m_Recording.GetData(samples, bFirstBlock ? 0 : midPoint); + + AudioData record = new AudioData(); + record.MaxLevel = Mathf.Max(samples); + record.Clip = AudioClip.Create("Recording", midPoint, m_Recording.channels, m_RecordingHZ, false); + record.Clip.SetData(samples, 0); + + if (m_PlaybackRecording) + m_Playback.Add(record.Clip); + if (m_AudioOutput.IsConnected && !m_AudioOutput.SendData(record)) + StopRecording(); // automatically stop recording if the callback goes away. + + bFirstBlock = !bFirstBlock; + } + else + { + // calculate the number of samples remaining until we ready for a block of audio, + // and wait that amount of time it will take to record. + int remaining = bFirstBlock ? (midPoint - writePos) : (m_Recording.samples - writePos); + float timeRemaining = (float)remaining / (float)m_RecordingHZ; + if (bOutputLevelData && timeRemaining > m_LevelOutputInterval) + timeRemaining = m_LevelOutputInterval; + yield return new WaitForSeconds(timeRemaining); + } + } + else + { + yield return new WaitForSeconds(m_LevelOutputInterval); + } - yield break; + if (m_Recording != null && bOutputLevelData) + { + float fLevel = 0.0f; + if (writePos < lastReadPos) + { + // write has wrapped, grab the last bit from the buffer.. + samples = new float[m_Recording.samples - lastReadPos]; + m_Recording.GetData(samples, lastReadPos); + fLevel = Mathf.Max(fLevel, Mathf.Max(samples)); + + lastReadPos = 0; + } + + if (lastReadPos < writePos) + { + samples = new float[writePos - lastReadPos]; + m_Recording.GetData(samples, lastReadPos); + fLevel = Mathf.Max(fLevel, Mathf.Max(samples)); + + lastReadPos = writePos; + } + + m_LevelOutput.SendData(new LevelData(fLevel * m_LevelOutputModifier, m_LevelOutputModifier)); } - #endregion + } + + yield break; } + #endregion + } } diff --git a/Scripts/Widgets/NaturalLanguageClassifierWidget.cs b/Scripts/Widgets/NaturalLanguageClassifierWidget.cs index 5bb10f8eb..5103f88f4 100755 --- a/Scripts/Widgets/NaturalLanguageClassifierWidget.cs +++ b/Scripts/Widgets/NaturalLanguageClassifierWidget.cs @@ -29,332 +29,332 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// Natural Language Classifier Widget. + /// + public class NaturalLanguageClassifierWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_RecognizeInput = new Input("Recognize", typeof(SpeechToTextData), "OnRecognize"); + #endregion + + #region Outputs + [SerializeField] + private Output m_ClassifyOutput = new Output(typeof(ClassifyResultData), true); + #endregion + + #region Private Data + private NaturalLanguageClassifier m_NaturalLanguageClassifier = new NaturalLanguageClassifier(); + private Classifier m_Selected = null; + + [SerializeField] + private string m_ClassifierName = string.Empty; + [SerializeField] + private string m_ClassifierId = string.Empty; + [SerializeField, Tooltip("What is the minimum word confidence needed to send onto the Natural Language Classifier?")] + private float m_MinWordConfidence = 0f; + private float m_MinWordConfidenceDelta = 0.0f; + [SerializeField, Tooltip("Recognized speech below this confidence is just ignored.")] + private float m_IgnoreWordConfidence = 0f; + private float m_IgnoreWordConfidenceDelta = 0.0f; + [SerializeField, Tooltip("What is the minimum confidence for a classification event to be fired.")] + private float m_MinClassEventConfidence = 0f; + private float m_MinClassEventConfidenceDelta = 0.0f; + [SerializeField] + private string m_Language = "en"; + + [Serializable] + private class ClassEventMapping + { + public string m_Class = null; + public string m_Event = ""; + }; + [SerializeField] + private List m_ClassEventList = new List(); + private Dictionary m_ClassEventMap = new Dictionary(); + // private Dictionary m_ClassEventMap = new Dictionary(); + + [SerializeField] + private Text m_TopClassText = null; + #endregion + + #region Public Properties + /// + /// Returns the Natural Language Classifier service object. + /// + public NaturalLanguageClassifier NaturalLanguageClassifier { get { return m_NaturalLanguageClassifier; } } + /// - /// Natural Language Classifier Widget. + /// Gets or sets the value of ignore word confidence. /// - public class NaturalLanguageClassifierWidget : Widget + /// The ignore word confidence. + public float IgnoreWordConfidence { - #region Inputs - [SerializeField] - private Input m_RecognizeInput = new Input("Recognize", typeof(SpeechToTextData), "OnRecognize"); - #endregion - - #region Outputs - [SerializeField] - private Output m_ClassifyOutput = new Output(typeof(ClassifyResultData), true); - #endregion - - #region Private Data - private NaturalLanguageClassifier m_NaturalLanguageClassifier = new NaturalLanguageClassifier(); - private Classifier m_Selected = null; - - [SerializeField] - private string m_ClassifierName = string.Empty; - [SerializeField] - private string m_ClassifierId = string.Empty; - [SerializeField, Tooltip("What is the minimum word confidence needed to send onto the Natural Language Classifier?")] - private float m_MinWordConfidence = 0f; - private float m_MinWordConfidenceDelta = 0.0f; - [SerializeField, Tooltip("Recognized speech below this confidence is just ignored.")] - private float m_IgnoreWordConfidence = 0f; - private float m_IgnoreWordConfidenceDelta = 0.0f; - [SerializeField, Tooltip("What is the minimum confidence for a classification event to be fired.")] - private float m_MinClassEventConfidence = 0f; - private float m_MinClassEventConfidenceDelta = 0.0f; - [SerializeField] - private string m_Language = "en"; - - [Serializable] - private class ClassEventMapping - { - public string m_Class = null; - public string m_Event = ""; - }; - [SerializeField] - private List m_ClassEventList = new List(); - private Dictionary m_ClassEventMap = new Dictionary(); - // private Dictionary m_ClassEventMap = new Dictionary(); - - [SerializeField] - private Text m_TopClassText = null; - #endregion - - #region Public Properties - /// - /// Returns the Natural Language Classifier service object. - /// - public NaturalLanguageClassifier NaturalLanguageClassifier { get { return m_NaturalLanguageClassifier; } } - - /// - /// Gets or sets the value of ignore word confidence. - /// - /// The ignore word confidence. - public float IgnoreWordConfidence - { - get - { - return Mathf.Clamp01(m_IgnoreWordConfidence + m_IgnoreWordConfidenceDelta); - } - set - { - m_IgnoreWordConfidenceDelta = value + m_IgnoreWordConfidence; - if (IgnoreWordConfidence > MinWordConfidence) - MinWordConfidence = IgnoreWordConfidence; - PlayerPrefs.SetFloat("m_IgnoreWordConfidenceDelta", m_IgnoreWordConfidenceDelta); - PlayerPrefs.Save(); - } - } - /// - /// Gets or sets the value of ignore word confidence delta. - /// - /// The ignore word confidence delta. - public float IgnoreWordConfidenceDelta - { - get { return m_IgnoreWordConfidenceDelta; } - set - { - m_IgnoreWordConfidenceDelta = value; - PlayerPrefs.SetFloat("m_IgnoreWordConfidenceDelta", m_IgnoreWordConfidenceDelta); - PlayerPrefs.Save(); - } - } + get + { + return Mathf.Clamp01(m_IgnoreWordConfidence + m_IgnoreWordConfidenceDelta); + } + set + { + m_IgnoreWordConfidenceDelta = value + m_IgnoreWordConfidence; + if (IgnoreWordConfidence > MinWordConfidence) + MinWordConfidence = IgnoreWordConfidence; + PlayerPrefs.SetFloat("m_IgnoreWordConfidenceDelta", m_IgnoreWordConfidenceDelta); + PlayerPrefs.Save(); + } + } + /// + /// Gets or sets the value of ignore word confidence delta. + /// + /// The ignore word confidence delta. + public float IgnoreWordConfidenceDelta + { + get { return m_IgnoreWordConfidenceDelta; } + set + { + m_IgnoreWordConfidenceDelta = value; + PlayerPrefs.SetFloat("m_IgnoreWordConfidenceDelta", m_IgnoreWordConfidenceDelta); + PlayerPrefs.Save(); + } + } - /// - /// Gets or sets the minimum value of word confidence. - /// - /// The minimum word confidence. - public float MinWordConfidence - { - get - { - return Mathf.Clamp01(m_MinWordConfidence + m_MinWordConfidenceDelta); - // return Mathf.Clamp01(m_MinWordConfidenceDelta); - } - set - { - m_MinWordConfidenceDelta = value + m_MinWordConfidence; - if (MinWordConfidence < IgnoreWordConfidence) - IgnoreWordConfidence = MinWordConfidence; - PlayerPrefs.SetFloat("m_MinWordConfidenceDelta", m_MinWordConfidenceDelta); - PlayerPrefs.Save(); - } - } + /// + /// Gets or sets the minimum value of word confidence. + /// + /// The minimum word confidence. + public float MinWordConfidence + { + get + { + return Mathf.Clamp01(m_MinWordConfidence + m_MinWordConfidenceDelta); + // return Mathf.Clamp01(m_MinWordConfidenceDelta); + } + set + { + m_MinWordConfidenceDelta = value + m_MinWordConfidence; + if (MinWordConfidence < IgnoreWordConfidence) + IgnoreWordConfidence = MinWordConfidence; + PlayerPrefs.SetFloat("m_MinWordConfidenceDelta", m_MinWordConfidenceDelta); + PlayerPrefs.Save(); + } + } - /// - /// Gets or sets the minimum value of word confidence delta. - /// - /// The minimum word confidence delta. - public float MinWordConfidenceDelta - { - get { return m_MinWordConfidenceDelta; } - set - { - m_MinWordConfidenceDelta = value; - PlayerPrefs.SetFloat("m_MinWordConfidenceDelta", m_MinWordConfidenceDelta); - PlayerPrefs.Save(); - } - } + /// + /// Gets or sets the minimum value of word confidence delta. + /// + /// The minimum word confidence delta. + public float MinWordConfidenceDelta + { + get { return m_MinWordConfidenceDelta; } + set + { + m_MinWordConfidenceDelta = value; + PlayerPrefs.SetFloat("m_MinWordConfidenceDelta", m_MinWordConfidenceDelta); + PlayerPrefs.Save(); + } + } - /// - /// Gets or sets the minimum value of class event confidence. - /// - /// The minimum class event confidence. - public float MinClassEventConfidence - { - get - { - return Mathf.Clamp01(m_MinClassEventConfidence + m_MinClassEventConfidenceDelta); - } - set - { - m_MinClassEventConfidenceDelta = value + m_MinClassEventConfidence; - PlayerPrefs.SetFloat("m_MinClassEventConfidenceDelta", m_MinClassEventConfidenceDelta); - PlayerPrefs.Save(); - } - } + /// + /// Gets or sets the minimum value of class event confidence. + /// + /// The minimum class event confidence. + public float MinClassEventConfidence + { + get + { + return Mathf.Clamp01(m_MinClassEventConfidence + m_MinClassEventConfidenceDelta); + } + set + { + m_MinClassEventConfidenceDelta = value + m_MinClassEventConfidence; + PlayerPrefs.SetFloat("m_MinClassEventConfidenceDelta", m_MinClassEventConfidenceDelta); + PlayerPrefs.Save(); + } + } - /// - /// Gets or sets the minimum value of class event confidence delta. - /// - /// The minimum class event confidence delta. - public float MinClassEventConfidenceDelta - { - get { return m_MinClassEventConfidenceDelta; } - set - { - m_MinClassEventConfidenceDelta = value; - PlayerPrefs.SetFloat("m_MinClassEventConfidenceDelta", m_MinClassEventConfidenceDelta); - PlayerPrefs.Save(); - } - } - #endregion + /// + /// Gets or sets the minimum value of class event confidence delta. + /// + /// The minimum class event confidence delta. + public float MinClassEventConfidenceDelta + { + get { return m_MinClassEventConfidenceDelta; } + set + { + m_MinClassEventConfidenceDelta = value; + PlayerPrefs.SetFloat("m_MinClassEventConfidenceDelta", m_MinClassEventConfidenceDelta); + PlayerPrefs.Save(); + } + } + #endregion - #region Widget interface - /// - protected override string GetName() - { - return "Natural Language Classifier"; - } - #endregion + #region Widget interface + /// + protected override string GetName() + { + return "Natural Language Classifier"; + } + #endregion - #region Event Handlers - /// - protected override void Start() - { - base.Start(); + #region Event Handlers + /// + protected override void Start() + { + base.Start(); + + m_IgnoreWordConfidenceDelta = PlayerPrefs.GetFloat("m_IgnoreWordConfidenceDelta", 0.0f); + m_MinWordConfidenceDelta = PlayerPrefs.GetFloat("m_MinWordConfidenceDelta", 0.0f); + m_MinClassEventConfidenceDelta = PlayerPrefs.GetFloat("m_MinClassEventConfidenceDelta", 0.0f); + + // resolve configuration variables + m_ClassifierName = Config.Instance.ResolveVariables(m_ClassifierName); + m_ClassifierId = Config.Instance.ResolveVariables(m_ClassifierId); + + if (string.IsNullOrEmpty(m_ClassifierId)) + { + Log.Status("NaturalLanguageClassifierWidget", "Auto selecting a classifier."); + if (!m_NaturalLanguageClassifier.GetClassifiers(OnGetClassifiers)) + Log.Error("NaturalLanguageClassifierWidget", "Failed to request all classifiers."); + } + else + { + if (!m_NaturalLanguageClassifier.GetClassifier(m_ClassifierId, OnGetClassifier)) + Log.Equals("NaturalLanguageClassifierWidget", "Failed to request classifier."); + } + } - m_IgnoreWordConfidenceDelta = PlayerPrefs.GetFloat("m_IgnoreWordConfidenceDelta", 0.0f); - m_MinWordConfidenceDelta = PlayerPrefs.GetFloat("m_MinWordConfidenceDelta", 0.0f); - m_MinClassEventConfidenceDelta = PlayerPrefs.GetFloat("m_MinClassEventConfidenceDelta", 0.0f); + private void OnEnable() + { + EventManager.Instance.RegisterEventReceiver("OnDebugCommand", OnDebugCommand); + } + private void OnDisable() + { + EventManager.Instance.UnregisterEventReceiver("OnDebugCommand", OnDebugCommand); + } - // resolve configuration variables - m_ClassifierName = Config.Instance.ResolveVariables(m_ClassifierName); - m_ClassifierId = Config.Instance.ResolveVariables(m_ClassifierId); + private void OnGetClassifiers(Classifiers classifiers) + { + if (classifiers != null) + { + bool bFound = false; + foreach (var classifier in classifiers.classifiers) + { + if (!string.IsNullOrEmpty(m_ClassifierName) && !classifier.name.ToLower().StartsWith(m_ClassifierName.ToLower())) + continue; + if (classifier.language != m_Language) + continue; - if (string.IsNullOrEmpty(m_ClassifierId)) - { - Log.Status("NaturalLanguageClassifierWidget", "Auto selecting a classifier."); - if (!m_NaturalLanguageClassifier.GetClassifiers(OnGetClassifiers)) - Log.Error("NaturalLanguageClassifierWidget", "Failed to request all classifiers."); - } - else - { - if (!m_NaturalLanguageClassifier.GetClassifier(m_ClassifierId, OnGetClassifier)) - Log.Equals("NaturalLanguageClassifierWidget", "Failed to request classifier."); - } + m_NaturalLanguageClassifier.GetClassifier(classifier.classifier_id, OnGetClassifier); + bFound = true; } - private void OnEnable() - { - EventManager.Instance.RegisterEventReceiver("OnDebugCommand", OnDebugCommand); - } - private void OnDisable() - { - EventManager.Instance.UnregisterEventReceiver("OnDebugCommand", OnDebugCommand); - } + if (!bFound) + Log.Error("NaturalLanguageClassifierWidget", "No classifiers found that match {0}", m_ClassifierName); + } + } - private void OnGetClassifiers(Classifiers classifiers) + private void OnGetClassifier(Classifier classifier) + { + if (classifier != null && classifier.status == "Available") + { + if (m_Selected == null || m_Selected.created.CompareTo(classifier.created) < 0) { - if (classifiers != null) - { - bool bFound = false; - foreach (var classifier in classifiers.classifiers) - { - if (!string.IsNullOrEmpty(m_ClassifierName) && !classifier.name.ToLower().StartsWith(m_ClassifierName.ToLower())) - continue; - if (classifier.language != m_Language) - continue; - - m_NaturalLanguageClassifier.GetClassifier(classifier.classifier_id, OnGetClassifier); - bFound = true; - } - - if (!bFound) - Log.Error("NaturalLanguageClassifierWidget", "No classifiers found that match {0}", m_ClassifierName); - } + m_Selected = classifier; + m_ClassifierId = m_Selected.classifier_id; + + Log.Status("NaturalLanguageClassifierWidget", "Selected classifier {0}, Created: {1}, Name: {2}", + m_Selected.classifier_id, m_Selected.created, m_Selected.name); } + } + } - private void OnGetClassifier(Classifier classifier) + private void OnRecognize(Data data) + { + SpeechRecognitionEvent result = ((SpeechToTextData)data).Results; + if (result.HasFinalResult()) + { + string text = result.results[0].alternatives[0].transcript; + double textConfidence = result.results[0].alternatives[0].confidence; + + Log.Debug("NaturalLanguageClassifierWidget", "OnRecognize: {0} ({1:0.00})", text, textConfidence); + EventManager.Instance.SendEvent("OnDebugMessage", string.Format("{0} ({1:0.00})", text, textConfidence)); + + if (textConfidence > MinWordConfidence) { - if (classifier != null && classifier.status == "Available") - { - if (m_Selected == null || m_Selected.created.CompareTo(classifier.created) < 0) - { - m_Selected = classifier; - m_ClassifierId = m_Selected.classifier_id; - - Log.Status("NaturalLanguageClassifierWidget", "Selected classifier {0}, Created: {1}, Name: {2}", - m_Selected.classifier_id, m_Selected.created, m_Selected.name); - } - } + if (!string.IsNullOrEmpty(m_ClassifierId)) + { + if (!m_NaturalLanguageClassifier.Classify(m_ClassifierId, text, OnClassified)) + Log.Error("NaturalLanguageClassifierWidget", "Failed to send {0} to Natural Language Classifier.", text); + } + else + Log.Equals("NaturalLanguageClassifierWidget", "No valid classifier set."); } - - private void OnRecognize(Data data) + else { - SpeechRecognitionEvent result = ((SpeechToTextData)data).Results; - if (result.HasFinalResult()) - { - string text = result.results[0].alternatives[0].transcript; - double textConfidence = result.results[0].alternatives[0].confidence; - - Log.Debug("NaturalLanguageClassifierWidget", "OnRecognize: {0} ({1:0.00})", text, textConfidence); - EventManager.Instance.SendEvent("OnDebugMessage", string.Format("{0} ({1:0.00})", text, textConfidence)); - - if (textConfidence > MinWordConfidence) - { - if (!string.IsNullOrEmpty(m_ClassifierId)) - { - if (!m_NaturalLanguageClassifier.Classify(m_ClassifierId, text, OnClassified)) - Log.Error("NaturalLanguageClassifierWidget", "Failed to send {0} to Natural Language Classifier.", text); - } - else - Log.Equals("NaturalLanguageClassifierWidget", "No valid classifier set."); - } - else - { - Log.Debug("NaturalLanguagClassifierWidget", "Text confidence {0} < {1} (Min word confidence)", textConfidence, MinWordConfidence); - if (textConfidence > IgnoreWordConfidence) - { - Log.Debug("NaturalLanguageClassifierWidget", "Text confidence {0} > {1} (Ignore word confidence)", textConfidence, IgnoreWordConfidence); - EventManager.Instance.SendEvent("OnClassifyFailure", result); - } - } - } + Log.Debug("NaturalLanguagClassifierWidget", "Text confidence {0} < {1} (Min word confidence)", textConfidence, MinWordConfidence); + if (textConfidence > IgnoreWordConfidence) + { + Log.Debug("NaturalLanguageClassifierWidget", "Text confidence {0} > {1} (Ignore word confidence)", textConfidence, IgnoreWordConfidence); + EventManager.Instance.SendEvent("OnClassifyFailure", result); + } } + } + } - private void OnClassified(ClassifyResult result) - { - EventManager.Instance.SendEvent("OnClassifyResult", result); + private void OnClassified(ClassifyResult result) + { + EventManager.Instance.SendEvent("OnClassifyResult", result); - if (m_ClassifyOutput.IsConnected) - m_ClassifyOutput.SendData(new ClassifyResultData(result)); + if (m_ClassifyOutput.IsConnected) + m_ClassifyOutput.SendData(new ClassifyResultData(result)); - if (result != null) + if (result != null) + { + Log.Debug("NaturalLanguageClassifierWidget", "OnClassified: {0} ({1:0.00})", result.top_class, result.topConfidence); + + if (m_TopClassText != null) + m_TopClassText.text = result.top_class; + + if (!string.IsNullOrEmpty(result.top_class)) + { + if (result.topConfidence >= MinClassEventConfidence) + { + if (m_ClassEventList.Count > 0 && m_ClassEventMap.Count == 0) { - Log.Debug("NaturalLanguageClassifierWidget", "OnClassified: {0} ({1:0.00})", result.top_class, result.topConfidence); - - if (m_TopClassText != null) - m_TopClassText.text = result.top_class; - - if (!string.IsNullOrEmpty(result.top_class)) - { - if (result.topConfidence >= MinClassEventConfidence) - { - if (m_ClassEventList.Count > 0 && m_ClassEventMap.Count == 0) - { - // initialize the map - foreach (var ev in m_ClassEventList) - m_ClassEventMap[ev.m_Class] = ev.m_Event; - } - - string sendEvent; - // Constants.Event sendEvent; - if (!m_ClassEventMap.TryGetValue(result.top_class, out sendEvent)) - { - Log.Warning("NaturalLanguageClassifierWidget", "No class mapping found for {0}", result.top_class); - EventManager.Instance.SendEvent(result.top_class, result); - } - else - EventManager.Instance.SendEvent(sendEvent, result); - } - else - { - if (result.topConfidence > IgnoreWordConfidence) - EventManager.Instance.SendEvent("OnClassifyFailure", result); - } - } + // initialize the map + foreach (var ev in m_ClassEventList) + m_ClassEventMap[ev.m_Class] = ev.m_Event; } - } - private void OnDebugCommand(object[] args) - { - string text = args != null && args.Length > 0 ? args[0] as string : string.Empty; - if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(m_ClassifierId)) + string sendEvent; + // Constants.Event sendEvent; + if (!m_ClassEventMap.TryGetValue(result.top_class, out sendEvent)) { - if (!m_NaturalLanguageClassifier.Classify(m_ClassifierId, text, OnClassified)) - Log.Error("NaturalLanguageClassifierWidget", "Failed to send {0} to Natural Language Classifier.", (string)args[0]); + Log.Warning("NaturalLanguageClassifierWidget", "No class mapping found for {0}", result.top_class); + EventManager.Instance.SendEvent(result.top_class, result); } + else + EventManager.Instance.SendEvent(sendEvent, result); + } + else + { + if (result.topConfidence > IgnoreWordConfidence) + EventManager.Instance.SendEvent("OnClassifyFailure", result); + } } - #endregion + } + } + + private void OnDebugCommand(object[] args) + { + string text = args != null && args.Length > 0 ? args[0] as string : string.Empty; + if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(m_ClassifierId)) + { + if (!m_NaturalLanguageClassifier.Classify(m_ClassifierId, text, OnClassified)) + Log.Error("NaturalLanguageClassifierWidget", "Failed to send {0} to Natural Language Classifier.", (string)args[0]); + } } + #endregion + } } diff --git a/Scripts/Widgets/SpeechDisplayWidget.cs b/Scripts/Widgets/SpeechDisplayWidget.cs index 453a96e2e..4ce6000d0 100755 --- a/Scripts/Widgets/SpeechDisplayWidget.cs +++ b/Scripts/Widgets/SpeechDisplayWidget.cs @@ -25,99 +25,99 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// Simple class for displaying the SpeechToText result data in the UI. - /// - public class SpeechDisplayWidget : Widget + /// + /// Simple class for displaying the SpeechToText result data in the UI. + /// + public class SpeechDisplayWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_SpeechInput = new Input("SpeechInput", typeof(SpeechToTextData), "OnSpeechInput"); + #endregion + + #region Widget interface + /// + protected override string GetName() { - #region Inputs - [SerializeField] - private Input m_SpeechInput = new Input("SpeechInput", typeof(SpeechToTextData), "OnSpeechInput"); - #endregion - - #region Widget interface - /// - protected override string GetName() - { - return "SpeechDisplay"; - } - #endregion - - #region Private Data - - [SerializeField] - private bool m_ContinuousText = false; - [SerializeField] - private Text m_Output = null; - [SerializeField] - private InputField m_OutputAsInputField = null; - [SerializeField] - private Text m_OutputStatus = null; - [SerializeField] - private float m_MinConfidenceToShow = 0.5f; - - private string m_PreviousOutputTextWithStatus = ""; - private string m_PreviousOutputText = ""; - private float m_ThresholdTimeFromLastInput = 3.0f; //3 secs as threshold time. After 3 secs from last OnSpeechInput, we are considering input as new input - private float m_TimeAtLastInterim = 0.0f; - #endregion - - #region Event Handlers - private void OnSpeechInput(Data data) + return "SpeechDisplay"; + } + #endregion + + #region Private Data + + [SerializeField] + private bool m_ContinuousText = false; + [SerializeField] + private Text m_Output = null; + [SerializeField] + private InputField m_OutputAsInputField = null; + [SerializeField] + private Text m_OutputStatus = null; + [SerializeField] + private float m_MinConfidenceToShow = 0.5f; + + private string m_PreviousOutputTextWithStatus = ""; + private string m_PreviousOutputText = ""; + private float m_ThresholdTimeFromLastInput = 3.0f; //3 secs as threshold time. After 3 secs from last OnSpeechInput, we are considering input as new input + private float m_TimeAtLastInterim = 0.0f; + #endregion + + #region Event Handlers + private void OnSpeechInput(Data data) + { + if (m_Output != null || m_OutputAsInputField != null) + { + SpeechRecognitionEvent result = ((SpeechToTextData)data).Results; + if (result != null && result.results.Length > 0) { - if (m_Output != null || m_OutputAsInputField != null) + string outputTextWithStatus = ""; + string outputText = ""; + + if (Time.time - m_TimeAtLastInterim > m_ThresholdTimeFromLastInput) + { + if (m_Output != null) + m_PreviousOutputTextWithStatus = m_Output.text; + if (m_OutputAsInputField != null) + m_PreviousOutputText = m_OutputAsInputField.text; + } + + if (m_Output != null && m_ContinuousText) + outputTextWithStatus = m_PreviousOutputTextWithStatus; + + if (m_OutputAsInputField != null && m_ContinuousText) + outputText = m_PreviousOutputText; + + foreach (var res in result.results) + { + foreach (var alt in res.alternatives) { - SpeechRecognitionEvent result = ((SpeechToTextData)data).Results; - if (result != null && result.results.Length > 0) + string text = alt.transcript; + if (m_Output != null) + { + m_Output.text = string.Concat(outputTextWithStatus, string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); + } + + if (m_OutputAsInputField != null) + { + if (!res.final || alt.confidence > m_MinConfidenceToShow) { - string outputTextWithStatus = ""; - string outputText = ""; - - if (Time.time - m_TimeAtLastInterim > m_ThresholdTimeFromLastInput) - { - if (m_Output != null) - m_PreviousOutputTextWithStatus = m_Output.text; - if (m_OutputAsInputField != null) - m_PreviousOutputText = m_OutputAsInputField.text; - } - - if (m_Output != null && m_ContinuousText) - outputTextWithStatus = m_PreviousOutputTextWithStatus; - - if (m_OutputAsInputField != null && m_ContinuousText) - outputText = m_PreviousOutputText; - - foreach (var res in result.results) - { - foreach (var alt in res.alternatives) - { - string text = alt.transcript; - if (m_Output != null) - { - m_Output.text = string.Concat(outputTextWithStatus, string.Format("{0} ({1}, {2:0.00})\n", text, res.final ? "Final" : "Interim", alt.confidence)); - } - - if (m_OutputAsInputField != null) - { - if (!res.final || alt.confidence > m_MinConfidenceToShow) - { - m_OutputAsInputField.text = string.Concat(outputText, " ", text); - - if (m_OutputStatus != null) - { - m_OutputStatus.text = string.Format("{0}, {1:0.00}", res.final ? "Final" : "Interim", alt.confidence); - } - } - } - - if (!res.final) - m_TimeAtLastInterim = Time.time; - - } - } + m_OutputAsInputField.text = string.Concat(outputText, " ", text); + + if (m_OutputStatus != null) + { + m_OutputStatus.text = string.Format("{0}, {1:0.00}", res.final ? "Final" : "Interim", alt.confidence); + } } + } + + if (!res.final) + m_TimeAtLastInterim = Time.time; + } + } } - #endregion + } } + #endregion + } } diff --git a/Scripts/Widgets/SpeechToTextWidget.cs b/Scripts/Widgets/SpeechToTextWidget.cs index 3b140312f..b78915f78 100755 --- a/Scripts/Widgets/SpeechToTextWidget.cs +++ b/Scripts/Widgets/SpeechToTextWidget.cs @@ -28,187 +28,188 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// SpeechToText Widget that wraps the SpeechToText service. + /// + public class SpeechToTextWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_AudioInput = new Input("Audio", typeof(AudioData), "OnAudio"); + [SerializeField] + private Input m_LanguageInput = new Input("Language", typeof(LanguageData), "OnLanguage"); + #endregion + + #region Outputs + [SerializeField] + private Output m_ResultOutput = new Output(typeof(SpeechToTextData), true); + #endregion + + #region Private Data + private SpeechToText m_SpeechToText = new SpeechToText(); + [SerializeField] + private Text m_StatusText = null; + [SerializeField] + private bool m_DetectSilence = true; + [SerializeField] + private float m_SilenceThreshold = 0.03f; + [SerializeField] + private bool m_WordConfidence = false; + [SerializeField] + private bool m_TimeStamps = false; + [SerializeField] + private int m_MaxAlternatives = 1; + [SerializeField] + private bool m_EnableContinous = false; + [SerializeField] + private bool m_EnableInterimResults = false; + [SerializeField] + private Text m_Transcript = null; + [SerializeField, Tooltip("Language ID to use in the speech recognition model.")] + private string m_Language = "en-US"; + #endregion + + #region Public Properties /// - /// SpeechToText Widget that wraps the SpeechToText service. + /// This property starts or stop's this widget listening for speech. /// - public class SpeechToTextWidget : Widget - { - #region Inputs - [SerializeField] - private Input m_AudioInput = new Input( "Audio", typeof(AudioData), "OnAudio" ); - [SerializeField] - private Input m_LanguageInput = new Input( "Language", typeof(LanguageData), "OnLanguage" ); - #endregion - - #region Outputs - [SerializeField] - private Output m_ResultOutput = new Output( typeof(SpeechToTextData), true ); - #endregion - - #region Private Data - private SpeechToText m_SpeechToText = new SpeechToText(); - [SerializeField] - private Text m_StatusText = null; - [SerializeField] - private bool m_DetectSilence = true; - [SerializeField] - private float m_SilenceThreshold = 0.03f; - [SerializeField] - private bool m_WordConfidence = false; - [SerializeField] - private bool m_TimeStamps = false; - [SerializeField] - private int m_MaxAlternatives = 1; - [SerializeField] - private bool m_EnableContinous = false; - [SerializeField] - private bool m_EnableInterimResults = false; - [SerializeField] - private Text m_Transcript = null; - [SerializeField, Tooltip( "Language ID to use in the speech recognition model.") ] - private string m_Language = "en-US"; - #endregion - - #region Public Properties - /// - /// This property starts or stop's this widget listening for speech. - /// - public bool Active + public bool Active + { + get { return m_SpeechToText.IsListening; } + set + { + if (value && !m_SpeechToText.IsListening) { - get { return m_SpeechToText.IsListening; } - set { - if ( value && !m_SpeechToText.IsListening ) - { - m_SpeechToText.DetectSilence = m_DetectSilence; - m_SpeechToText.EnableWordConfidence = m_WordConfidence; - m_SpeechToText.EnableTimestamps = m_TimeStamps; - m_SpeechToText.SilenceThreshold = m_SilenceThreshold; - m_SpeechToText.MaxAlternatives = m_MaxAlternatives; - m_SpeechToText.EnableContinousRecognition = m_EnableContinous; - m_SpeechToText.EnableInterimResults = m_EnableInterimResults; - m_SpeechToText.OnError = OnError; - m_SpeechToText.StartListening( OnRecognize ); - if ( m_StatusText != null ) - m_StatusText.text = "LISTENING"; - } - else if ( !value && m_SpeechToText.IsListening ) - { - m_SpeechToText.StopListening(); - if ( m_StatusText != null ) - m_StatusText.text = "READY"; - } - } + m_SpeechToText.DetectSilence = m_DetectSilence; + m_SpeechToText.EnableWordConfidence = m_WordConfidence; + m_SpeechToText.EnableTimestamps = m_TimeStamps; + m_SpeechToText.SilenceThreshold = m_SilenceThreshold; + m_SpeechToText.MaxAlternatives = m_MaxAlternatives; + m_SpeechToText.EnableContinousRecognition = m_EnableContinous; + m_SpeechToText.EnableInterimResults = m_EnableInterimResults; + m_SpeechToText.OnError = OnError; + m_SpeechToText.StartListening(OnRecognize); + if (m_StatusText != null) + m_StatusText.text = "LISTENING"; } - #endregion - - #region Widget Interface - /// - protected override string GetName() - { - return "SpeechToText"; - } - #endregion - - #region Event handlers - /// - /// Button handler to toggle the active state of this widget. - /// - public void OnListenButton() - { - Active = !Active; - } - - /// - protected override void Start() - { - base.Start(); - - if ( m_StatusText != null ) - m_StatusText.text = "READY"; - if (! m_SpeechToText.GetModels( OnGetModels ) ) - Log.Error( "SpeechToTextWidget", "Failed to request models." ); - } - - private void OnDisable() + else if (!value && m_SpeechToText.IsListening) { - if ( Active ) - Active = false; + m_SpeechToText.StopListening(); + if (m_StatusText != null) + m_StatusText.text = "READY"; } + } + } + #endregion - private void OnError( string error ) - { - Active = false; - if ( m_StatusText != null ) - m_StatusText.text = "ERROR: " + error; - } - - private void OnAudio( Data data ) - { - if (! Active ) - Active = true; + #region Widget Interface + /// + protected override string GetName() + { + return "SpeechToText"; + } + #endregion - m_SpeechToText.OnListen( (AudioData)data ); - } + #region Event handlers + /// + /// Button handler to toggle the active state of this widget. + /// + public void OnListenButton() + { + Active = !Active; + } - private void OnLanguage(Data data) - { - LanguageData language = data as LanguageData; - if ( language == null ) - throw new WatsonException( "Unexpected data type" ); + /// + protected override void Start() + { + base.Start(); - if (! string.IsNullOrEmpty( language.Language ) ) - { - m_Language = language.Language; + if (m_StatusText != null) + m_StatusText.text = "READY"; + if (!m_SpeechToText.GetModels(OnGetModels)) + Log.Error("SpeechToTextWidget", "Failed to request models."); + } - if (! m_SpeechToText.GetModels( OnGetModels ) ) - Log.Error( "SpeechToTextWidget", "Failed to rquest models." ); - } + private void OnDisable() + { + if (Active) + Active = false; + } + + private void OnError(string error) + { + Active = false; + if (m_StatusText != null) + m_StatusText.text = "ERROR: " + error; + } + + private void OnAudio(Data data) + { + if (!Active) + Active = true; + + m_SpeechToText.OnListen((AudioData)data); + } + + private void OnLanguage(Data data) + { + LanguageData language = data as LanguageData; + if (language == null) + throw new WatsonException("Unexpected data type"); + + if (!string.IsNullOrEmpty(language.Language)) + { + m_Language = language.Language; + + if (!m_SpeechToText.GetModels(OnGetModels)) + Log.Error("SpeechToTextWidget", "Failed to rquest models."); + } + } + + private void OnGetModels(Model[] models) + { + if (models != null) + { + Model bestModel = null; + foreach (var model in models) + { + if (model.language.StartsWith(m_Language) + && (bestModel == null || model.rate > bestModel.rate)) + { + bestModel = model; + } } - private void OnGetModels( Model [] models ) + if (bestModel != null) { - if ( models != null ) - { - Model bestModel = null; - foreach( var model in models ) - { - if ( model.language.StartsWith( m_Language ) - && (bestModel == null || model.rate > bestModel.rate) ) - { - bestModel = model; - } - } - - if ( bestModel != null ) - { - Log.Status( "SpeechToTextWidget", "Selecting Recognize Model: {0} ", bestModel.name ); - m_SpeechToText.RecognizeModel = bestModel.name; - } - } + Log.Status("SpeechToTextWidget", "Selecting Recognize Model: {0} ", bestModel.name); + m_SpeechToText.RecognizeModel = bestModel.name; } + } + } + + private void OnRecognize(SpeechRecognitionEvent result) + { + m_ResultOutput.SendData(new SpeechToTextData(result)); - private void OnRecognize(SpeechRecognitionEvent result) - { - m_ResultOutput.SendData( new SpeechToTextData( result ) ); - - if (result != null && result.results.Length > 0) - { - if ( m_Transcript != null ) - m_Transcript.text = ""; - - foreach( var res in result.results ) - { - foreach( var alt in res.alternatives ) - { - string text = alt.transcript; - - if ( m_Transcript != null ) - m_Transcript.text += string.Format( "{0} ({1}, {2:0.00})\n", - text, res.final ? "Final" : "Interim", alt.confidence ); - } - } - } - } - #endregion + if (result != null && result.results.Length > 0) + { + if (m_Transcript != null) + m_Transcript.text = ""; + + foreach (var res in result.results) + { + foreach (var alt in res.alternatives) + { + string text = alt.transcript; + + if (m_Transcript != null) + m_Transcript.text += string.Format("{0} ({1}, {2:0.00})\n", + text, res.final ? "Final" : "Interim", alt.confidence); + } + } + } } + #endregion + } } diff --git a/Scripts/Widgets/TextToSpeechWidget.cs b/Scripts/Widgets/TextToSpeechWidget.cs old mode 100644 new mode 100755 index f06ec9cf2..3a9cb31ca --- a/Scripts/Widgets/TextToSpeechWidget.cs +++ b/Scripts/Widgets/TextToSpeechWidget.cs @@ -27,228 +27,228 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// TextToSpeech widget class wraps the TextToSpeech serivce. + /// + [RequireComponent(typeof(AudioSource))] + public class TextToSpeechWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_TextInput = new Input("Text", typeof(TextToSpeechData), "OnTextInput"); + [SerializeField] + private Input m_VoiceInput = new Input("Voice", typeof(VoiceData), "OnVoiceSelect"); + #endregion + + #region Outputs + [SerializeField] + private Output m_Speaking = new Output(typeof(SpeakingStateData)); + [SerializeField] + private Output m_DisableMic = new Output(typeof(DisableMicData)); + [SerializeField] + private Output m_LevelOut = new Output(typeof(LevelData)); + #endregion + + #region Private Data + TextToSpeech m_TextToSpeech = new TextToSpeech(); + + [SerializeField, Tooltip("How often to send level out data in seconds.")] + private float m_LevelOutInterval = 0.05f; + [SerializeField] + private float m_LevelOutputModifier = 1.0f; + [SerializeField] + private Button m_TextToSpeechButton = null; + [SerializeField] + private InputField m_Input = null; + [SerializeField] + private Text m_StatusText = null; + [SerializeField] + private VoiceType m_Voice = VoiceType.en_US_Michael; + [SerializeField] + private bool m_UsePost = false; + + private AudioSource m_Source = null; + private int m_LastPlayPos = 0; + + private class Speech + { + ~Speech() + { + if (Clip != null) + UnityObjectUtil.DestroyUnityObject(Clip); + } + + public bool Ready { get; set; } + public AudioClip Clip { get; set; } + + public Speech(TextToSpeech textToSpeech, string text, bool usePost) + { + textToSpeech.ToSpeech(text, OnAudioClip, usePost); + } + + private void OnAudioClip(AudioClip clip) + { + Clip = clip; + Ready = true; + } + + }; + + private Queue m_SpeechQueue = new Queue(); + private Speech m_ActiveSpeech = null; + #endregion + + #region Public Memebers + /// - /// TextToSpeech widget class wraps the TextToSpeech serivce. + /// Gets or sets the voice. Default voice is English, US - Michael /// - [RequireComponent(typeof(AudioSource))] - public class TextToSpeechWidget : Widget + /// The voice. + public VoiceType Voice { - #region Inputs - [SerializeField] - private Input m_TextInput = new Input("Text", typeof(TextToSpeechData), "OnTextInput"); - [SerializeField] - private Input m_VoiceInput = new Input("Voice", typeof(VoiceData), "OnVoiceSelect"); - #endregion - - #region Outputs - [SerializeField] - private Output m_Speaking = new Output(typeof(SpeakingStateData)); - [SerializeField] - private Output m_DisableMic = new Output(typeof(DisableMicData)); - [SerializeField] - private Output m_LevelOut = new Output(typeof(LevelData)); - #endregion - - #region Private Data - TextToSpeech m_TextToSpeech = new TextToSpeech(); - - [SerializeField, Tooltip("How often to send level out data in seconds.")] - private float m_LevelOutInterval = 0.05f; - [SerializeField] - private float m_LevelOutputModifier = 1.0f; - [SerializeField] - private Button m_TextToSpeechButton = null; - [SerializeField] - private InputField m_Input = null; - [SerializeField] - private Text m_StatusText = null; - [SerializeField] - private VoiceType m_Voice = VoiceType.en_US_Michael; - [SerializeField] - private bool m_UsePost = false; - - private AudioSource m_Source = null; - private int m_LastPlayPos = 0; - - private class Speech - { - ~Speech() - { - if (Clip != null) - UnityObjectUtil.DestroyUnityObject(Clip); - } - - public bool Ready { get; set; } - public AudioClip Clip { get; set; } - - public Speech(TextToSpeech textToSpeech, string text, bool usePost) - { - textToSpeech.ToSpeech(text, OnAudioClip, usePost); - } - - private void OnAudioClip(AudioClip clip) - { - Clip = clip; - Ready = true; - } - - }; - - private Queue m_SpeechQueue = new Queue(); - private Speech m_ActiveSpeech = null; - #endregion - - #region Public Memebers - - /// - /// Gets or sets the voice. Default voice is English, US - Michael - /// - /// The voice. - public VoiceType Voice - { - get - { - return m_Voice; - } - set - { - m_Voice = value; - } - } - - #endregion + get + { + return m_Voice; + } + set + { + m_Voice = value; + } + } - #region Event Handlers - /// - /// Button event handler. - /// - public void OnTextToSpeech() - { - if (m_TextToSpeech.Voice != m_Voice) - m_TextToSpeech.Voice = m_Voice; - if (m_Input != null) - m_SpeechQueue.Enqueue(new Speech(m_TextToSpeech, m_Input.text, m_UsePost)); - if (m_StatusText != null) - m_StatusText.text = "THINKING"; - if (m_TextToSpeechButton != null) - m_TextToSpeechButton.interactable = false; - } - #endregion + #endregion - #region Private Functions - private void OnTextInput(Data data) - { - TextToSpeechData text = data as TextToSpeechData; - if (text == null) - throw new WatsonException("Wrong data type received."); + #region Event Handlers + /// + /// Button event handler. + /// + public void OnTextToSpeech() + { + if (m_TextToSpeech.Voice != m_Voice) + m_TextToSpeech.Voice = m_Voice; + if (m_Input != null) + m_SpeechQueue.Enqueue(new Speech(m_TextToSpeech, m_Input.text, m_UsePost)); + if (m_StatusText != null) + m_StatusText.text = "THINKING"; + if (m_TextToSpeechButton != null) + m_TextToSpeechButton.interactable = false; + } + #endregion - if (!string.IsNullOrEmpty(text.Text)) - { - if (m_TextToSpeech.Voice != m_Voice) - m_TextToSpeech.Voice = m_Voice; + #region Private Functions + private void OnTextInput(Data data) + { + TextToSpeechData text = data as TextToSpeechData; + if (text == null) + throw new WatsonException("Wrong data type received."); - m_SpeechQueue.Enqueue(new Speech(m_TextToSpeech, text.Text, m_UsePost)); - } - } + if (!string.IsNullOrEmpty(text.Text)) + { + if (m_TextToSpeech.Voice != m_Voice) + m_TextToSpeech.Voice = m_Voice; - private void OnVoiceSelect(Data data) - { - VoiceData voice = data as VoiceData; - if (voice == null) - throw new WatsonException("Unexpected data type"); + m_SpeechQueue.Enqueue(new Speech(m_TextToSpeech, text.Text, m_UsePost)); + } + } - m_Voice = voice.Voice; - } + private void OnVoiceSelect(Data data) + { + VoiceData voice = data as VoiceData; + if (voice == null) + throw new WatsonException("Unexpected data type"); - private void OnEnable() - { - UnityObjectUtil.StartDestroyQueue(); + m_Voice = voice.Voice; + } - if (m_StatusText != null) - m_StatusText.text = "READY"; - } + private void OnEnable() + { + UnityObjectUtil.StartDestroyQueue(); - /// - protected override void Start() - { - base.Start(); - m_Source = GetComponent(); - } + if (m_StatusText != null) + m_StatusText.text = "READY"; + } - private void Update() - { - if (m_Source != null && !m_Source.isPlaying - && m_SpeechQueue.Count > 0 - && m_SpeechQueue.Peek().Ready) - { - CancelInvoke("OnEndSpeech"); - - m_ActiveSpeech = m_SpeechQueue.Dequeue(); - if (m_ActiveSpeech.Clip != null) - { - if (m_Speaking.IsConnected) - m_Speaking.SendData(new SpeakingStateData(true)); - if (m_DisableMic.IsConnected) - m_DisableMic.SendData(new DisableMicData(true)); - - m_Source.spatialBlend = 0.0f; // 2D sound - m_Source.loop = false; // do not loop - m_Source.clip = m_ActiveSpeech.Clip; // clip - m_Source.Play(); - - Invoke("OnEndSpeech", ((float)m_ActiveSpeech.Clip.samples / (float)m_ActiveSpeech.Clip.frequency) + 0.1f); - if (m_LevelOut.IsConnected) - { - m_LastPlayPos = 0; - InvokeRepeating("OnLevelOut", m_LevelOutInterval, m_LevelOutInterval); - } - } - else - { - Log.Warning("TextToSpeechWidget", "Skipping null AudioClip"); - } - } - - if (m_TextToSpeechButton != null) - m_TextToSpeechButton.interactable = true; - if (m_StatusText != null) - m_StatusText.text = "READY"; - } + /// + protected override void Start() + { + base.Start(); + m_Source = GetComponent(); + } - private void OnLevelOut() + private void Update() + { + if (m_Source != null && !m_Source.isPlaying + && m_SpeechQueue.Count > 0 + && m_SpeechQueue.Peek().Ready) + { + CancelInvoke("OnEndSpeech"); + + m_ActiveSpeech = m_SpeechQueue.Dequeue(); + if (m_ActiveSpeech.Clip != null) { - if (m_Source != null && m_Source.isPlaying) - { - int currentPos = m_Source.timeSamples; - if (currentPos > m_LastPlayPos) - { - float[] samples = new float[currentPos - m_LastPlayPos]; - m_Source.clip.GetData(samples, m_LastPlayPos); - m_LevelOut.SendData(new LevelData(Mathf.Max(samples) * m_LevelOutputModifier, m_LevelOutputModifier)); - m_LastPlayPos = currentPos; - } - } - else - CancelInvoke("OnLevelOut"); + if (m_Speaking.IsConnected) + m_Speaking.SendData(new SpeakingStateData(true)); + if (m_DisableMic.IsConnected) + m_DisableMic.SendData(new DisableMicData(true)); + + m_Source.spatialBlend = 0.0f; // 2D sound + m_Source.loop = false; // do not loop + m_Source.clip = m_ActiveSpeech.Clip; // clip + m_Source.Play(); + + Invoke("OnEndSpeech", ((float)m_ActiveSpeech.Clip.samples / (float)m_ActiveSpeech.Clip.frequency) + 0.1f); + if (m_LevelOut.IsConnected) + { + m_LastPlayPos = 0; + InvokeRepeating("OnLevelOut", m_LevelOutInterval, m_LevelOutInterval); + } } - private void OnEndSpeech() + else { - if (m_Speaking.IsConnected) - m_Speaking.SendData(new SpeakingStateData(false)); - if (m_DisableMic.IsConnected) - m_DisableMic.SendData(new DisableMicData(false)); - if (m_Source.isPlaying) - m_Source.Stop(); - - m_ActiveSpeech = null; + Log.Warning("TextToSpeechWidget", "Skipping null AudioClip"); } + } - /// - protected override string GetName() + if (m_TextToSpeechButton != null) + m_TextToSpeechButton.interactable = true; + if (m_StatusText != null) + m_StatusText.text = "READY"; + } + + private void OnLevelOut() + { + if (m_Source != null && m_Source.isPlaying) + { + int currentPos = m_Source.timeSamples; + if (currentPos > m_LastPlayPos) { - return "TextToSpeech"; + float[] samples = new float[currentPos - m_LastPlayPos]; + m_Source.clip.GetData(samples, m_LastPlayPos); + m_LevelOut.SendData(new LevelData(Mathf.Max(samples) * m_LevelOutputModifier, m_LevelOutputModifier)); + m_LastPlayPos = currentPos; } - #endregion + } + else + CancelInvoke("OnLevelOut"); + } + private void OnEndSpeech() + { + if (m_Speaking.IsConnected) + m_Speaking.SendData(new SpeakingStateData(false)); + if (m_DisableMic.IsConnected) + m_DisableMic.SendData(new DisableMicData(false)); + if (m_Source.isPlaying) + m_Source.Stop(); + + m_ActiveSpeech = null; + } + + /// + protected override string GetName() + { + return "TextToSpeech"; } + #endregion + } } diff --git a/Scripts/Widgets/TouchWidget.cs b/Scripts/Widgets/TouchWidget.cs old mode 100644 new mode 100755 index 233d985e7..eb71dd461 --- a/Scripts/Widgets/TouchWidget.cs +++ b/Scripts/Widgets/TouchWidget.cs @@ -25,153 +25,153 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// This widget class maps Touch events to a SerializedDelegate. + /// + public class TouchWidget : Widget + { + #region Widget interface + /// + protected override string GetName() + { + return "Touch"; + } + #endregion + + #region Private Data + [Serializable] + public class TapEventMapping + { + public GameObject m_TapObject = null; + public bool m_TapOnObject = true; + public int m_SortingLayer = 0; + public LayerMask m_LayerMask = default(LayerMask); + public string m_Callback = ""; + }; + + [Serializable] + public class FullScreenDragEventMapping + { + [Tooltip("If there is no drag layer object set, it uses FullScreen")] + public GameObject m_DragLayerObject = null; + public int m_NumberOfFinger = 1; + public int m_SortingLayer = 0; + public bool m_IsDragInside = true; + public string m_Callback = ""; + }; + + [SerializeField] + private List m_TapMappings = new List(); + + [SerializeField] + private List m_FullScreenDragMappings = new List(); + #endregion + + #region Public Members + /// - /// This widget class maps Touch events to a SerializedDelegate. + /// Gets or sets the tap mappings. /// - public class TouchWidget : Widget + /// The tap mappings. + public List TapMappings + { + get + { + return m_TapMappings; + } + set + { + m_TapMappings = value; + } + } + + /// + /// Gets or sets the full screen drag mappings. + /// + /// The full screen drag mappings. + public List FullScreenDragMappings + { + get + { + return m_FullScreenDragMappings; + } + set + { + m_FullScreenDragMappings = value; + } + } + + #endregion + + #region Event Handlers + private void OnEnable() { - #region Widget interface - /// - protected override string GetName() + if (TouchEventManager.Instance == null) + { + Log.Error("TouchWidget", "There should be TouchEventManager in the scene! No TouchEventManager found."); + return; + } + + foreach (var mapping in m_TapMappings) + { + if (!string.IsNullOrEmpty(mapping.m_Callback)) { - return "Touch"; + TouchEventManager.Instance.RegisterTapEvent(mapping.m_TapObject, mapping.m_Callback, mapping.m_SortingLayer, mapping.m_TapOnObject, mapping.m_LayerMask); } - #endregion - - #region Private Data - [Serializable] - public class TapEventMapping + else { - public GameObject m_TapObject = null; - public bool m_TapOnObject = true; - public int m_SortingLayer = 0; - public LayerMask m_LayerMask = default(LayerMask); - public string m_Callback = ""; - }; - - [Serializable] - public class FullScreenDragEventMapping + Log.Warning("TouchWidget", "Callback function needs to be defined to register TouchWidget - Tap"); + } + } + + foreach (var mapping in m_FullScreenDragMappings) + { + if (!string.IsNullOrEmpty(mapping.m_Callback)) { - [Tooltip("If there is no drag layer object set, it uses FullScreen")] - public GameObject m_DragLayerObject = null; - public int m_NumberOfFinger = 1; - public int m_SortingLayer = 0; - public bool m_IsDragInside = true; - public string m_Callback = ""; - }; - - [SerializeField] - private List m_TapMappings = new List(); - - [SerializeField] - private List m_FullScreenDragMappings = new List(); - #endregion - - #region Public Members - - /// - /// Gets or sets the tap mappings. - /// - /// The tap mappings. - public List TapMappings + TouchEventManager.Instance.RegisterDragEvent(mapping.m_DragLayerObject, mapping.m_Callback, mapping.m_NumberOfFinger, mapping.m_SortingLayer, isDragInside: mapping.m_IsDragInside); + } + else { - get - { - return m_TapMappings; - } - set - { - m_TapMappings = value; - } + Log.Warning("TouchWidget", "Callback function needs to be defined to register TouchWidget - Drag"); } + } + } - /// - /// Gets or sets the full screen drag mappings. - /// - /// The full screen drag mappings. - public List FullScreenDragMappings + private void OnDisable() + { + if (TouchEventManager.Instance == null) + { + //Log.Error ("TouchWidget", "There should be TouchEventManager in the scene! No TouchEventManager found."); + return; + } + + foreach (var mapping in m_TapMappings) + { + if (!string.IsNullOrEmpty(mapping.m_Callback)) { - get - { - return m_FullScreenDragMappings; - } - set - { - m_FullScreenDragMappings = value; - } + TouchEventManager.Instance.UnregisterTapEvent(mapping.m_TapObject, mapping.m_Callback, mapping.m_SortingLayer, mapping.m_TapOnObject, mapping.m_LayerMask); } - - #endregion - - #region Event Handlers - private void OnEnable() + else { - if (TouchEventManager.Instance == null) - { - Log.Error ("TouchWidget", "There should be TouchEventManager in the scene! No TouchEventManager found."); - return; - } - - foreach (var mapping in m_TapMappings) - { - if (!string.IsNullOrEmpty(mapping.m_Callback)) - { - TouchEventManager.Instance.RegisterTapEvent(mapping.m_TapObject, mapping.m_Callback, mapping.m_SortingLayer, mapping.m_TapOnObject, mapping.m_LayerMask); - } - else - { - Log.Warning("TouchWidget", "Callback function needs to be defined to register TouchWidget - Tap"); - } - } - - foreach (var mapping in m_FullScreenDragMappings) - { - if (!string.IsNullOrEmpty(mapping.m_Callback)) - { - TouchEventManager.Instance.RegisterDragEvent(mapping.m_DragLayerObject, mapping.m_Callback, mapping.m_NumberOfFinger, mapping.m_SortingLayer, isDragInside: mapping.m_IsDragInside); - } - else - { - Log.Warning("TouchWidget", "Callback function needs to be defined to register TouchWidget - Drag"); - } - } + Log.Warning("TouchWidget", "Callback function needs to be defined to unregister TouchWidget - Tap"); } + } - private void OnDisable() + foreach (var mapping in m_FullScreenDragMappings) + { + if (!string.IsNullOrEmpty(mapping.m_Callback)) { - if (TouchEventManager.Instance == null) - { - //Log.Error ("TouchWidget", "There should be TouchEventManager in the scene! No TouchEventManager found."); - return; - } - - foreach (var mapping in m_TapMappings) - { - if (!string.IsNullOrEmpty(mapping.m_Callback)) - { - TouchEventManager.Instance.UnregisterTapEvent(mapping.m_TapObject, mapping.m_Callback, mapping.m_SortingLayer, mapping.m_TapOnObject, mapping.m_LayerMask); - } - else - { - Log.Warning("TouchWidget", "Callback function needs to be defined to unregister TouchWidget - Tap"); - } - } - - foreach (var mapping in m_FullScreenDragMappings) - { - if (!string.IsNullOrEmpty(mapping.m_Callback)) - { - TouchEventManager.Instance.UnregisterDragEvent(mapping.m_DragLayerObject, mapping.m_Callback, mapping.m_NumberOfFinger, mapping.m_SortingLayer, isDragInside: mapping.m_IsDragInside); - } - else - { - Log.Warning("TouchWidget", "Callback function needs to be defined to unregister TouchWidget - Drag"); - } - - - } + TouchEventManager.Instance.UnregisterDragEvent(mapping.m_DragLayerObject, mapping.m_Callback, mapping.m_NumberOfFinger, mapping.m_SortingLayer, isDragInside: mapping.m_IsDragInside); } - #endregion + else + { + Log.Warning("TouchWidget", "Callback function needs to be defined to unregister TouchWidget - Drag"); + } + + + } } + #endregion + } } \ No newline at end of file diff --git a/Scripts/Widgets/WebCamDisplayWidget.cs b/Scripts/Widgets/WebCamDisplayWidget.cs index 069e6ef8e..ac417028f 100755 --- a/Scripts/Widgets/WebCamDisplayWidget.cs +++ b/Scripts/Widgets/WebCamDisplayWidget.cs @@ -25,89 +25,89 @@ namespace IBM.Watson.DeveloperCloud.Widgets { - /// - /// This widget displays WebCam video. - /// - public class WebCamDisplayWidget : Widget - { - #region Inputs - [SerializeField] - private Input m_WebCamTextureInput = new Input("WebCamTexture", typeof(WebCamTextureData), "OnWebCamTexture"); - #endregion + /// + /// This widget displays WebCam video. + /// + public class WebCamDisplayWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_WebCamTextureInput = new Input("WebCamTexture", typeof(WebCamTextureData), "OnWebCamTexture"); + #endregion - #region Outputs - #endregion + #region Outputs + #endregion - #region Private Data - [SerializeField] - private RawImage m_RawImage; - [SerializeField] - private Material m_Material; + #region Private Data + [SerializeField] + private RawImage m_RawImage; + [SerializeField] + private Material m_Material; - private WebCamTexture m_WebCamTexture; - private int m_RequestedWidth; - private int m_RequestedHeight; - private int m_RequestedFPS; - #endregion + private WebCamTexture m_WebCamTexture; + private int m_RequestedWidth; + private int m_RequestedHeight; + private int m_RequestedFPS; + #endregion - #region Constants - #endregion + #region Constants + #endregion - #region Public Properties - /// - /// The Raw Image displaying the WebCam stream in UI. - /// - public RawImage RawImage - { - get { return m_RawImage; } - set { m_RawImage = value; } - } - /// - /// The Material displaying the WebCam stream on Geometry. - /// - public Material Material - { - get { return m_Material; } - } - #endregion + #region Public Properties + /// + /// The Raw Image displaying the WebCam stream in UI. + /// + public RawImage RawImage + { + get { return m_RawImage; } + set { m_RawImage = value; } + } + /// + /// The Material displaying the WebCam stream on Geometry. + /// + public Material Material + { + get { return m_Material; } + } + #endregion - #region Public Functions - #endregion + #region Public Functions + #endregion - #region Widget Interface - protected override string GetName() - { - return "WebCamDisplay"; - } - #endregion + #region Widget Interface + protected override string GetName() + { + return "WebCamDisplay"; + } + #endregion - #region Private Functions - #endregion + #region Private Functions + #endregion - #region Event Handlers - private void OnWebCamTexture(Data data) - { - Log.Debug("WebCamDisplayWidget", "OnWebCamTexture()"); - if (Material == null && RawImage == null) - throw new ArgumentNullException("A Material or RawImage is required to display WebCamTexture"); + #region Event Handlers + private void OnWebCamTexture(Data data) + { + Log.Debug("WebCamDisplayWidget", "OnWebCamTexture()"); + if (Material == null && RawImage == null) + throw new ArgumentNullException("A Material or RawImage is required to display WebCamTexture"); - WebCamTextureData webCamTextureData = (WebCamTextureData)data; - m_WebCamTexture = webCamTextureData.CamTexture; - m_RequestedWidth = webCamTextureData.RequestedWidth; - m_RequestedHeight = webCamTextureData.RequestedHeight; - m_RequestedFPS = webCamTextureData.RequestedFPS; + WebCamTextureData webCamTextureData = (WebCamTextureData)data; + m_WebCamTexture = webCamTextureData.CamTexture; + m_RequestedWidth = webCamTextureData.RequestedWidth; + m_RequestedHeight = webCamTextureData.RequestedHeight; + m_RequestedFPS = webCamTextureData.RequestedFPS; - if (Material != null) - Material.mainTexture = m_WebCamTexture; + if (Material != null) + Material.mainTexture = m_WebCamTexture; - if (RawImage != null) - { - RawImage.texture = m_WebCamTexture; - RawImage.material.mainTexture = m_WebCamTexture; - } - if (!m_WebCamTexture.isPlaying) - m_WebCamTexture.Play(); - } - #endregion + if (RawImage != null) + { + RawImage.texture = m_WebCamTexture; + RawImage.material.mainTexture = m_WebCamTexture; + } + if (!m_WebCamTexture.isPlaying) + m_WebCamTexture.Play(); } + #endregion + } } diff --git a/Scripts/Widgets/WebCamWidget.cs b/Scripts/Widgets/WebCamWidget.cs index 47d9e3e59..560d49ef0 100755 --- a/Scripts/Widgets/WebCamWidget.cs +++ b/Scripts/Widgets/WebCamWidget.cs @@ -25,292 +25,292 @@ #pragma warning disable 0414 namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// This widget gets video from the WebCam. Note: there are issues with WebCamTexture. Do not + /// start the WebCamTexture at too low resolution! + /// + public class WebCamWidget : Widget + { + #region Inputs + [SerializeField] + private Input m_DisableInput = new Input("Disable", typeof(DisableWebCamData), "OnDisableInput"); + #endregion + + #region Outputs + [SerializeField] + private Output m_WebCamTextureOutput = new Output(typeof(WebCamTextureData)); + [SerializeField] + private Output m_ActivateOutput = new Output(typeof(BooleanData)); + #endregion + + #region Private Data + private bool m_Active = false; + private bool m_Disabled = false; + private bool m_Failure = false; + private DateTime m_LastFailure = DateTime.Now; + + [SerializeField] + private bool m_ActivateOnStart = true; + [SerializeField] + private int m_RequestedWidth = 640; + [SerializeField] + private int m_RequestedHeight = 480; + [SerializeField] + private int m_RequestedFPS = 60; + [SerializeField] + private Text m_StatusText = null; + + private int m_RecordingRoutine = 0; // ID of our co-routine when recording, 0 if not recording currently. + private WebCamTexture m_WebCamTexture; + private int m_WebCamIndex = 0; + #endregion + + #region Public Properties /// - /// This widget gets video from the WebCam. Note: there are issues with WebCamTexture. Do not - /// start the WebCamTexture at too low resolution! + /// True if WebCam is active, false if inactive. /// - public class WebCamWidget : Widget + public bool Active { - #region Inputs - [SerializeField] - private Input m_DisableInput = new Input("Disable", typeof(DisableWebCamData), "OnDisableInput"); - #endregion - - #region Outputs - [SerializeField] - private Output m_WebCamTextureOutput = new Output(typeof(WebCamTextureData)); - [SerializeField] - private Output m_ActivateOutput = new Output(typeof(BooleanData)); - #endregion - - #region Private Data - private bool m_Active = false; - private bool m_Disabled = false; - private bool m_Failure = false; - private DateTime m_LastFailure = DateTime.Now; - - [SerializeField] - private bool m_ActivateOnStart = true; - [SerializeField] - private int m_RequestedWidth = 640; - [SerializeField] - private int m_RequestedHeight = 480; - [SerializeField] - private int m_RequestedFPS = 60; - [SerializeField] - private Text m_StatusText = null; - - private int m_RecordingRoutine = 0; // ID of our co-routine when recording, 0 if not recording currently. - private WebCamTexture m_WebCamTexture; - private int m_WebCamIndex = 0; - #endregion - - #region Public Properties - /// - /// True if WebCam is active, false if inactive. - /// - public bool Active + get { return m_Active; } + set + { + if (m_Active != value) { - get { return m_Active; } - set - { - if (m_Active != value) - { - m_Active = value; - if (m_Active && !m_Disabled) - StartRecording(); - else - StopRecording(); - } - } + m_Active = value; + if (m_Active && !m_Disabled) + StartRecording(); + else + StopRecording(); } - /// - /// True if WebCamera is disabled, false if enabled. - /// - public bool Disable - { - get { return m_Disabled; } - set - { - if (m_Disabled != value) - { - m_Disabled = value; - if (m_Active && !m_Disabled) - StartRecording(); - else - StopRecording(); - } - } - } - /// - /// This is set to true when the WebCam fails, the update will continue to try to start - /// the microphone so long as it's active. - /// - public bool Failure - { - get { return m_Failure; } - private set - { - if (m_Failure != value) - { - m_Failure = value; - if (m_Failure) - m_LastFailure = DateTime.Now; - } - } - } - /// - /// Returns all available WebCameras. - /// - public WebCamDevice[] Devices - { - get { return WebCamTexture.devices; } - } - /// - /// The curent WebCamTexture - /// - public WebCamTexture WebCamTexture - { - get { return m_WebCamTexture; } - } - /// - /// The requested width of the WebCamTexture. - /// - public int RequestedWidth + } + } + /// + /// True if WebCamera is disabled, false if enabled. + /// + public bool Disable + { + get { return m_Disabled; } + set + { + if (m_Disabled != value) { - get { return m_RequestedWidth; } - set { m_RequestedWidth = value; } + m_Disabled = value; + if (m_Active && !m_Disabled) + StartRecording(); + else + StopRecording(); } - /// - /// The requested height of the WebCamTexture. - /// - public int RequestedHeight + } + } + /// + /// This is set to true when the WebCam fails, the update will continue to try to start + /// the microphone so long as it's active. + /// + public bool Failure + { + get { return m_Failure; } + private set + { + if (m_Failure != value) { - get { return m_RequestedHeight; } - set { m_RequestedHeight = value; } + m_Failure = value; + if (m_Failure) + m_LastFailure = DateTime.Now; } + } + } + /// + /// Returns all available WebCameras. + /// + public WebCamDevice[] Devices + { + get { return WebCamTexture.devices; } + } + /// + /// The curent WebCamTexture + /// + public WebCamTexture WebCamTexture + { + get { return m_WebCamTexture; } + } + /// + /// The requested width of the WebCamTexture. + /// + public int RequestedWidth + { + get { return m_RequestedWidth; } + set { m_RequestedWidth = value; } + } + /// + /// The requested height of the WebCamTexture. + /// + public int RequestedHeight + { + get { return m_RequestedHeight; } + set { m_RequestedHeight = value; } + } - /// - /// The requested frame rate of the WebCamTexture. - /// - public int RequestedFPS - { - get { return m_RequestedFPS; } - set { m_RequestedFPS = value; } - } - #endregion + /// + /// The requested frame rate of the WebCamTexture. + /// + public int RequestedFPS + { + get { return m_RequestedFPS; } + set { m_RequestedFPS = value; } + } + #endregion - #region Public Funtions - /// - /// Activates the WebCam. - /// - public void ActivateWebCam() - { - Active = true; - } + #region Public Funtions + /// + /// Activates the WebCam. + /// + public void ActivateWebCam() + { + Active = true; + } - /// - /// Deactivates the WebCam. - /// - public void DeactivateWebCam() - { - Active = false; - } + /// + /// Deactivates the WebCam. + /// + public void DeactivateWebCam() + { + Active = false; + } - /// - /// Switches WebCamDevice to the next device. - /// - public void SwitchWebCam() - { - WebCamDevice[] devices = Devices; - - if (devices.Length == 0) - throw new WatsonException(string.Format("There are no WebCam devices!")); - if (devices.Length == 1) - { - Log.Warning("WebCamWidget", "There is only one WebCam device!"); - return; - } - - m_WebCamTexture.Stop(); - int requestedIndex; - if (m_WebCamIndex == devices.Length - 1) - requestedIndex = 0; - else - requestedIndex = m_WebCamIndex + 1; - m_WebCamTexture.deviceName = devices[requestedIndex].name; - m_WebCamIndex = requestedIndex; - Log.Status("WebCamWidget", "Switched to WebCam {0}, name: {1}, isFontFacing: {2}.", m_WebCamIndex, devices[m_WebCamIndex].name, devices[m_WebCamIndex].isFrontFacing); - m_WebCamTexture.Play(); - } + /// + /// Switches WebCamDevice to the next device. + /// + public void SwitchWebCam() + { + WebCamDevice[] devices = Devices; + + if (devices.Length == 0) + throw new WatsonException(string.Format("There are no WebCam devices!")); + if (devices.Length == 1) + { + Log.Warning("WebCamWidget", "There is only one WebCam device!"); + return; + } + + m_WebCamTexture.Stop(); + int requestedIndex; + if (m_WebCamIndex == devices.Length - 1) + requestedIndex = 0; + else + requestedIndex = m_WebCamIndex + 1; + m_WebCamTexture.deviceName = devices[requestedIndex].name; + m_WebCamIndex = requestedIndex; + Log.Status("WebCamWidget", "Switched to WebCam {0}, name: {1}, isFontFacing: {2}.", m_WebCamIndex, devices[m_WebCamIndex].name, devices[m_WebCamIndex].isFrontFacing); + m_WebCamTexture.Play(); + } - /// - /// Switches the WebCam device based on index. - /// - /// The WebCam index. - public void SwitchWebCam(int index) - { - WebCamDevice[] devices = Devices; - - if (index < devices.Length) - { - throw new WatsonException(string.Format("Requested WebCam index {0} does not exist! There are {1} available WebCams.", index, devices.Length)); - } - - m_WebCamTexture.Stop(); - m_WebCamTexture.deviceName = devices[index].name; - m_WebCamIndex = index; - Log.Status("WebCamWidget", "Switched to WebCam {0}, name: {1}, isFontFacing: {2}.", m_WebCamIndex, devices[m_WebCamIndex].name, devices[m_WebCamIndex].isFrontFacing); - m_WebCamTexture.Play(); - } + /// + /// Switches the WebCam device based on index. + /// + /// The WebCam index. + public void SwitchWebCam(int index) + { + WebCamDevice[] devices = Devices; + + if (index < devices.Length) + { + throw new WatsonException(string.Format("Requested WebCam index {0} does not exist! There are {1} available WebCams.", index, devices.Length)); + } + + m_WebCamTexture.Stop(); + m_WebCamTexture.deviceName = devices[index].name; + m_WebCamIndex = index; + Log.Status("WebCamWidget", "Switched to WebCam {0}, name: {1}, isFontFacing: {2}.", m_WebCamIndex, devices[m_WebCamIndex].name, devices[m_WebCamIndex].isFrontFacing); + m_WebCamTexture.Play(); + } - /// - /// Toggles between Active and Inactive states. - /// - public void ToggleActive() - { - Active = !Active; - } - #endregion + /// + /// Toggles between Active and Inactive states. + /// + public void ToggleActive() + { + Active = !Active; + } + #endregion - #region EventHandlers - protected override void Start() - { - base.Start(); - LogSystem.InstallDefaultReactors(); - Log.Debug("WebCamWidget", "WebCamWidget.Start();"); + #region EventHandlers + protected override void Start() + { + base.Start(); + LogSystem.InstallDefaultReactors(); + Log.Debug("WebCamWidget", "WebCamWidget.Start();"); - if (m_ActivateOnStart) - Active = true; - } + if (m_ActivateOnStart) + Active = true; + } - private void OnDisableInput(Data data) - { - Disable = ((DisableWebCamData)data).Boolean; - } - #endregion + private void OnDisableInput(Data data) + { + Disable = ((DisableWebCamData)data).Boolean; + } + #endregion - #region Widget Interface - protected override string GetName() - { - return "WebCam"; - } - #endregion + #region Widget Interface + protected override string GetName() + { + return "WebCam"; + } + #endregion - #region Recording Functions - private void StartRecording() - { - Log.Debug("WebCamWidget", "StartRecording(); m_RecordingRoutine: {0}", m_RecordingRoutine); - if (m_RecordingRoutine == 0) - { - //UnityObjectUtil.StartDestroyQueue(); + #region Recording Functions + private void StartRecording() + { + Log.Debug("WebCamWidget", "StartRecording(); m_RecordingRoutine: {0}", m_RecordingRoutine); + if (m_RecordingRoutine == 0) + { + //UnityObjectUtil.StartDestroyQueue(); - m_RecordingRoutine = Runnable.Run(RecordingHandler()); - m_ActivateOutput.SendData(new BooleanData(true)); + m_RecordingRoutine = Runnable.Run(RecordingHandler()); + m_ActivateOutput.SendData(new BooleanData(true)); - if (m_StatusText != null) - m_StatusText.text = "WEB CAMERA ON"; - } - } + if (m_StatusText != null) + m_StatusText.text = "WEB CAMERA ON"; + } + } - private void StopRecording() - { - Log.Debug("WebCamWidget", "StopRecording();"); - if (m_RecordingRoutine != 0) - { - Runnable.Stop(m_RecordingRoutine); - m_RecordingRoutine = 0; + private void StopRecording() + { + Log.Debug("WebCamWidget", "StopRecording();"); + if (m_RecordingRoutine != 0) + { + Runnable.Stop(m_RecordingRoutine); + m_RecordingRoutine = 0; - m_ActivateOutput.SendData(new BooleanData(false)); + m_ActivateOutput.SendData(new BooleanData(false)); - m_WebCamTexture.Stop(); + m_WebCamTexture.Stop(); - if (m_StatusText != null) - m_StatusText.text = "WEB CAMERA OFF"; - } - } + if (m_StatusText != null) + m_StatusText.text = "WEB CAMERA OFF"; + } + } - private IEnumerator RecordingHandler() - { - Failure = false; + private IEnumerator RecordingHandler() + { + Failure = false; #if !UNITY_EDITOR yield return Application.RequestUserAuthorization(UserAuthorization.WebCam); #endif - m_WebCamTexture = new WebCamTexture(m_RequestedWidth, m_RequestedHeight, m_RequestedFPS); - yield return null; + m_WebCamTexture = new WebCamTexture(m_RequestedWidth, m_RequestedHeight, m_RequestedFPS); + yield return null; - if (m_WebCamTexture == null) - { - Failure = true; - StopRecording(); - yield break; - } + if (m_WebCamTexture == null) + { + Failure = true; + StopRecording(); + yield break; + } - WebCamTextureData camData = new WebCamTextureData(m_WebCamTexture, m_RequestedWidth, m_RequestedHeight, m_RequestedFPS); - m_WebCamTextureOutput.SendData(camData); - } - #endregion + WebCamTextureData camData = new WebCamTextureData(m_WebCamTexture, m_RequestedWidth, m_RequestedHeight, m_RequestedFPS); + m_WebCamTextureOutput.SendData(camData); } + #endregion + } } diff --git a/Scripts/Widgets/Widget.cs b/Scripts/Widgets/Widget.cs old mode 100644 new mode 100755 index b399228cb..10bf9f472 --- a/Scripts/Widgets/Widget.cs +++ b/Scripts/Widgets/Widget.cs @@ -24,584 +24,584 @@ namespace IBM.Watson.DeveloperCloud.Widgets { + /// + /// This is the base class for all widgets. A Widget has any number of inputs and outputs that carry a specific type of data. + /// + public abstract class Widget : MonoBehaviour + { + #region Public Types /// - /// This is the base class for all widgets. A Widget has any number of inputs and outputs that carry a specific type of data. + /// This is the base class for any type of data that can be passed through a connection. /// - public abstract class Widget : MonoBehaviour + public abstract class Data { - #region Public Types - /// - /// This is the base class for any type of data that can be passed through a connection. - /// - public abstract class Data + /// + /// Name of this data type. + /// + public string Name { get { return GetName(); } } + + /// + /// Should return a print friendly name for this data. + /// + /// Returns a user-friendly name for this type of data. + public abstract string GetName(); + }; + + /// + /// The callback object used by Widget for receiving data from an input. + /// + /// + public delegate void OnReceiveData(Data data); + + /// + /// This object handles input on a widget. + /// + [Serializable] + public class Input + { + #region Private Data + [NonSerialized] + private List m_Connections = new List(); + #endregion + + #region Construction + /// + /// Constructs an input object for a Widget. + /// + /// The name of the input. + /// The type of data the input takes. + /// The name of the function to invoke with the input. The input function must match + /// If true, then allow more than one output to connect to this input. + /// the OnReceiveData callback. + public Input(string name, Type dataType, string receiverFunction, bool allowMany = true) + { + InputName = name; + DataType = dataType; + ReceiverFunction = receiverFunction; + AllowMany = allowMany; + } + #endregion + + #region Object Interface + /// + public override string ToString() + { + return (Owner != null ? Owner.name : "null") + "." + InputName + " (" + DataType.Name + ")"; + } + #endregion + + #region Public Properties + /// + /// A reference to the widget that contains this input, this is initialized when the Widget starts. + /// + public Widget Owner { get; set; } + /// + /// The name of the owning widget. + /// + public string OwnerName { get { return Owner.WidgetName; } } + /// + /// The name of this input. + /// + public string InputName { get; private set; } + /// + /// The fully qualified name of this input. + /// + public string FullInputName { get { return OwnerName + "/" + InputName; } } + /// + /// The type of data this input accepts. + /// + public Type DataType { get; private set; } + /// + /// If true, then more than one output may connect to this input. + /// + public bool AllowMany { get; private set; } + /// + /// The array of outputs connected to this input. + /// + public Output[] Connections { get { return m_Connections.ToArray(); } } + /// + /// The name of the data type. + /// + public string DataTypeName { get { return DataType.Name; } } + /// + /// The name of the receiver function. + /// + public string ReceiverFunction { get; private set; } + /// + /// The delegate to the receiver function, this is set when Start() is called on this input. + /// + public OnReceiveData DataReceiver { get; private set; } + #endregion + + #region Public Functions + /// + /// Add output to input. + /// + /// + /// + public bool AddOutput(Output output) + { + if (!AllowMany && m_Connections.Count > 0) + return false; + if (m_Connections.Contains(output)) + return false; + m_Connections.Add(output); + return true; + } + /// + /// Remove the output. + /// + /// + /// + public bool RemoveOutput(Output output) + { + return m_Connections.Remove(output); + } + + /// + /// Start this Input. + /// + /// The owning widget. + public virtual void Start(Widget owner) + { + Owner = owner; + + if (!string.IsNullOrEmpty(ReceiverFunction)) { - /// - /// Name of this data type. - /// - public string Name { get { return GetName(); } } - - /// - /// Should return a print friendly name for this data. - /// - /// Returns a user-friendly name for this type of data. - public abstract string GetName(); - }; + MethodInfo info = Owner.GetType().GetMethod(ReceiverFunction, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | + BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod); + if (info != null) + { + DataReceiver = Delegate.CreateDelegate(typeof(OnReceiveData), Owner, info) as OnReceiveData; + if (DataReceiver == null) + Log.Error("Widget", "CreateDelegate failed for function {0}", ReceiverFunction); + } + else + Log.Error("Widget", "Failed to find receiver function {0} in object {1}.", ReceiverFunction, Owner.gameObject.name); + } + } + + /// + /// Receives input and forwards that input onto the assigned delegate. Optionally, the user may inherit from Input and + /// override the ReceiveData() function. + /// + /// The received data object. + public virtual void ReceiveData(Data data) + { + if (DataReceiver != null) + DataReceiver(data); + } + #endregion + }; + + /// + /// This object handles output on a widget. + /// + [Serializable] + public class Output + { + /// + /// The connection between widgets. + /// + #region Public Types + [Serializable] + public class Connection + { + #region Private Data + [NonSerialized] + private Output m_Owner = null; + [SerializeField] + private GameObject m_TargetObject = null; + [SerializeField] + private string m_TargetConnection = null; + [NonSerialized] + private bool m_TargetInputResolved = false; + [NonSerialized] + private Input m_TargetInput = null; + #endregion + #region Public Properties /// - /// The callback object used by Widget for receiving data from an input. + /// This returns a reference to the target object. /// - /// - public delegate void OnReceiveData(Data data); - + public GameObject TargetObject { get { return m_TargetObject; } set { m_TargetObject = value; m_TargetInputResolved = false; } } /// - /// This object handles input on a widget. + /// The name of the target connection on the target object. /// - [Serializable] - public class Input + public string TargetConnection { get { return m_TargetConnection; } set { m_TargetConnection = value; m_TargetInputResolved = false; } } + /// + /// This returns a reference to the target input object. + /// + public Input TargetInput { - #region Private Data - [NonSerialized] - private List m_Connections = new List(); - #endregion - - #region Construction - /// - /// Constructs an input object for a Widget. - /// - /// The name of the input. - /// The type of data the input takes. - /// The name of the function to invoke with the input. The input function must match - /// If true, then allow more than one output to connect to this input. - /// the OnReceiveData callback. - public Input(string name, Type dataType, string receiverFunction, bool allowMany = true) - { - InputName = name; - DataType = dataType; - ReceiverFunction = receiverFunction; - AllowMany = allowMany; - } - #endregion + get { return m_TargetInput; } + set + { + if (m_TargetInput != null) + m_TargetInput.RemoveOutput(m_Owner); - #region Object Interface - /// - public override string ToString() + if (value != null && value.AddOutput(m_Owner)) { - return (Owner != null ? Owner.name : "null") + "." + InputName + " (" + DataType.Name + ")"; + m_TargetInput = value; + m_TargetObject = m_TargetInput.Owner.gameObject; + m_TargetConnection = m_TargetInput.FullInputName; } - #endregion - - #region Public Properties - /// - /// A reference to the widget that contains this input, this is initialized when the Widget starts. - /// - public Widget Owner { get; set; } - /// - /// The name of the owning widget. - /// - public string OwnerName { get { return Owner.WidgetName; } } - /// - /// The name of this input. - /// - public string InputName { get; private set; } - /// - /// The fully qualified name of this input. - /// - public string FullInputName { get { return OwnerName + "/" + InputName; } } - /// - /// The type of data this input accepts. - /// - public Type DataType { get; private set; } - /// - /// If true, then more than one output may connect to this input. - /// - public bool AllowMany { get; private set; } - /// - /// The array of outputs connected to this input. - /// - public Output[] Connections { get { return m_Connections.ToArray(); } } - /// - /// The name of the data type. - /// - public string DataTypeName { get { return DataType.Name; } } - /// - /// The name of the receiver function. - /// - public string ReceiverFunction { get; private set; } - /// - /// The delegate to the receiver function, this is set when Start() is called on this input. - /// - public OnReceiveData DataReceiver { get; private set; } - #endregion - - #region Public Functions - /// - /// Add output to input. - /// - /// - /// - public bool AddOutput(Output output) + else { - if (!AllowMany && m_Connections.Count > 0) - return false; - if (m_Connections.Contains(output)) - return false; - m_Connections.Add(output); - return true; - } - /// - /// Remove the output. - /// - /// - /// - public bool RemoveOutput(Output output) - { - return m_Connections.Remove(output); + m_TargetObject = null; + m_TargetConnection = string.Empty; } + m_TargetInputResolved = true; + } + } + #endregion - /// - /// Start this Input. - /// - /// The owning widget. - public virtual void Start(Widget owner) - { - Owner = owner; - - if (!string.IsNullOrEmpty(ReceiverFunction)) - { - MethodInfo info = Owner.GetType().GetMethod(ReceiverFunction, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | - BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod); - if (info != null) - { - DataReceiver = Delegate.CreateDelegate(typeof(OnReceiveData), Owner, info) as OnReceiveData; - if (DataReceiver == null) - Log.Error("Widget", "CreateDelegate failed for function {0}", ReceiverFunction); - } - else - Log.Error("Widget", "Failed to find receiver function {0} in object {1}.", ReceiverFunction, Owner.gameObject.name); - } - } - - /// - /// Receives input and forwards that input onto the assigned delegate. Optionally, the user may inherit from Input and - /// override the ReceiveData() function. - /// - /// The received data object. - public virtual void ReceiveData(Data data) - { - if (DataReceiver != null) - DataReceiver(data); - } - #endregion - }; - + #region Public Functions /// - /// This object handles output on a widget. + /// Resolve the target input. /// - [Serializable] - public class Output + /// + public bool ResolveTargetInput() { - /// - /// The connection between widgets. - /// - #region Public Types - [Serializable] - public class Connection - { - #region Private Data - [NonSerialized] - private Output m_Owner = null; - [SerializeField] - private GameObject m_TargetObject = null; - [SerializeField] - private string m_TargetConnection = null; - [NonSerialized] - private bool m_TargetInputResolved = false; - [NonSerialized] - private Input m_TargetInput = null; - #endregion - - #region Public Properties - /// - /// This returns a reference to the target object. - /// - public GameObject TargetObject { get { return m_TargetObject; } set { m_TargetObject = value; m_TargetInputResolved = false; } } - /// - /// The name of the target connection on the target object. - /// - public string TargetConnection { get { return m_TargetConnection; } set { m_TargetConnection = value; m_TargetInputResolved = false; } } - /// - /// This returns a reference to the target input object. - /// - public Input TargetInput - { - get { return m_TargetInput; } - set - { - if (m_TargetInput != null) - m_TargetInput.RemoveOutput(m_Owner); - - if (value != null && value.AddOutput(m_Owner)) - { - m_TargetInput = value; - m_TargetObject = m_TargetInput.Owner.gameObject; - m_TargetConnection = m_TargetInput.FullInputName; - } - else - { - m_TargetObject = null; - m_TargetConnection = string.Empty; - } - m_TargetInputResolved = true; - } - } - #endregion - - #region Public Functions - /// - /// Resolve the target input. - /// - /// - public bool ResolveTargetInput() - { - if (!m_TargetInputResolved) - { - m_TargetInputResolved = true; - m_TargetInput = null; - - if (m_TargetObject == null) - return false; - - string inputName = m_TargetConnection; - string componentName = null; - - int seperator = inputName.IndexOf('/'); - if (seperator >= 0) - { - componentName = inputName.Substring(0, seperator); - inputName = inputName.Substring(seperator + 1); - } - - Widget[] widgets = m_TargetObject.GetComponents(); - foreach (var widget in widgets) - { - if (!string.IsNullOrEmpty(componentName) - && widget.WidgetName != componentName) - continue; // widget is the wrong type, the target is not here.. - - foreach (Input input in widget.Inputs) - { - if (!string.IsNullOrEmpty(inputName) - && input.InputName != inputName) - continue; - if (input.DataType != m_Owner.DataType) - continue; - if (!m_TargetInput.AddOutput(m_Owner)) - continue; - - m_TargetInput = input; - return true; - } - } - - Log.Error("Widget", "Failed to resolve target {0} for object {1}.", m_TargetConnection, m_TargetObject.name); - return false; - } - - return m_TargetInput != null; - } + if (!m_TargetInputResolved) + { + m_TargetInputResolved = true; + m_TargetInput = null; - /// - /// Start ouput. - /// - /// - public void Start(Output owner) - { - m_Owner = owner; - } - #endregion - }; - #endregion - - #region Constructor - /// - /// The constructor for an widget output object. - /// - /// The type of data this widget outputs. - /// If true, then this output will connect to more than one input. - public Output(Type dataType, bool allowMany = false) - { - DataType = dataType; - AllowMany = allowMany; - } - #endregion + if (m_TargetObject == null) + return false; - #region Object Interface - /// - public override string ToString() - { - return (Owner != null ? Owner.name : "null") + " (" + DataType.Name + ")"; - } - #endregion - - #region Public Properties - /// - /// Returns true if this output is connected to a input. - /// - public bool IsConnected - { - get - { - foreach (var c in m_Connections) - if (c.ResolveTargetInput()) - return true; - return false; - } - } + string inputName = m_TargetConnection; + string componentName = null; - /// - /// Connections between widgets. - /// - public Connection[] Connections { get { return m_Connections.ToArray(); } } - /// - /// Returns a reference to the Widget owner, this is set when the Widget initializes. - /// - public Widget Owner { get; set; } - /// - /// The type of data this output sends. - /// - public Type DataType { get; set; } - /// - /// If true, allows more than one input to be connected to this output. - /// - public bool AllowMany { get; private set; } - #endregion - - #region Public Functions - /// - /// Starts this Output. - /// - /// The Widget owner of this Output. - public virtual void Start(Widget owner) + int seperator = inputName.IndexOf('/'); + if (seperator >= 0) { - Owner = owner; - foreach (var c in m_Connections) - c.Start(this); - } - /// - /// Sends a data object to the target of this output. - /// - /// Data object to send. - /// Returns true if the data was sent to another widget. - public virtual bool SendData(Data data) - { - bool sent = false; - foreach (var c in m_Connections) - { - if (c.ResolveTargetInput()) - { - try - { - c.TargetInput.ReceiveData(data); - sent = true; - } - catch (Exception e) - { - Log.Error("Widget", "Exception sending data {0} to input {1} on object {2}: {3}", - data.Name, c.TargetInput.InputName, c.TargetObject.name, e.ToString()); - } - } - } - return sent; - } - - /// - /// Add a connection to this output, returns false if the connection can't be made. - /// - /// A reference to the connection to establish. - /// Returns true on success. - public bool AddConnection(Input input) - { - if (!AllowMany && m_Connections.Count > 0) - return false; // already connected. - if (input.DataType != DataType) - return false; // wrong data type - - Connection c = new Connection(); - c.Start(this); - c.TargetInput = input; - m_Connections.Add(c); - - return true; + componentName = inputName.Substring(0, seperator); + inputName = inputName.Substring(seperator + 1); } - /// - /// Add a connect to a given object and optional target input. - /// - /// The object to target. - /// A optional argument of the target input on the object. - /// Returns true if a Connection object was added. - public bool AddConnection(GameObject targetObject, string targetConnection = null) + Widget[] widgets = m_TargetObject.GetComponents(); + foreach (var widget in widgets) { - if (!AllowMany && m_Connections.Count > 0) - return false; // already connected. - - Connection c = new Connection(); - c.Start(this); - c.TargetObject = targetObject; - if (targetConnection != null) - c.TargetConnection = targetConnection; - if (!c.ResolveTargetInput()) - return false; // couldn't resolve a input - m_Connections.Add(c); - + if (!string.IsNullOrEmpty(componentName) + && widget.WidgetName != componentName) + continue; // widget is the wrong type, the target is not here.. + + foreach (Input input in widget.Inputs) + { + if (!string.IsNullOrEmpty(inputName) + && input.InputName != inputName) + continue; + if (input.DataType != m_Owner.DataType) + continue; + if (!m_TargetInput.AddOutput(m_Owner)) + continue; + + m_TargetInput = input; return true; + } } - /// - /// Remove the connection between widgets. - /// - /// - /// - public bool RemoveConnection(Connection c) - { - return m_Connections.Remove(c); - } - #endregion - - #region Private Data - [SerializeField] - List m_Connections = new List(); - #endregion - }; - #endregion - - #region Private Data - [SerializeField] - private bool m_AutoConnect = true; - private bool m_Initialized = false; - private Input[] m_Inputs = null; - private Output[] m_Outputs = null; - #endregion + Log.Error("Widget", "Failed to resolve target {0} for object {1}.", m_TargetConnection, m_TargetObject.name); + return false; + } - #region Public Properties - /// - /// Returns the name of this widget. - /// - public string WidgetName { get { return GetName(); } } - /// - /// This returns an array of all inputs on this widget. - /// - public Input[] Inputs { get { if (!m_Initialized) InitializeIO(); return m_Inputs; } } - /// - /// This returns an array of all outputs on this widget. - /// - public Output[] Outputs { get { if (!m_Initialized) InitializeIO(); return m_Outputs; } } - #endregion + return m_TargetInput != null; + } - #region Public Functions /// - /// Call this function to go ahead and resolve auto-connections to other widgets. Normally, - /// we would try to auto connect when the Awake() is called, this can be called to resolve - /// the auto connections ahead of time. + /// Start ouput. /// - public void ResolveConnections() + /// + public void Start(Output owner) { - InitializeIO(); - InitializeConnections(); + m_Owner = owner; } #endregion - - #region Private Functions - private void InitializeIO() + }; + #endregion + + #region Constructor + /// + /// The constructor for an widget output object. + /// + /// The type of data this widget outputs. + /// If true, then this output will connect to more than one input. + public Output(Type dataType, bool allowMany = false) + { + DataType = dataType; + AllowMany = allowMany; + } + #endregion + + #region Object Interface + /// + public override string ToString() + { + return (Owner != null ? Owner.name : "null") + " (" + DataType.Name + ")"; + } + #endregion + + #region Public Properties + /// + /// Returns true if this output is connected to a input. + /// + public bool IsConnected + { + get { - m_Outputs = GetMembersByType(); - foreach (var output in m_Outputs) - output.Start(this); - m_Inputs = GetMembersByType(); - foreach (var input in m_Inputs) - input.Start(this); - m_Initialized = true; + foreach (var c in m_Connections) + if (c.ResolveTargetInput()) + return true; + return false; } - - private void InitializeConnections() + } + + /// + /// Connections between widgets. + /// + public Connection[] Connections { get { return m_Connections.ToArray(); } } + /// + /// Returns a reference to the Widget owner, this is set when the Widget initializes. + /// + public Widget Owner { get; set; } + /// + /// The type of data this output sends. + /// + public Type DataType { get; set; } + /// + /// If true, allows more than one input to be connected to this output. + /// + public bool AllowMany { get; private set; } + #endregion + + #region Public Functions + /// + /// Starts this Output. + /// + /// The Widget owner of this Output. + public virtual void Start(Widget owner) + { + Owner = owner; + foreach (var c in m_Connections) + c.Start(this); + } + /// + /// Sends a data object to the target of this output. + /// + /// Data object to send. + /// Returns true if the data was sent to another widget. + public virtual bool SendData(Data data) + { + bool sent = false; + foreach (var c in m_Connections) { - // we only auto-connect when running in the editor. Doing this run-time might be very dangerous. - if (m_AutoConnect) + if (c.ResolveTargetInput()) + { + try { - // this boolean is serialized, so we only ever do this once. Set this at the start - // so we don't end up in a circular loop of widgets. - m_AutoConnect = false; - - Widget[] widgets = FindObjectsOfType(); - foreach (var widget in widgets) - { - if (widget == null || widget == this) - continue; // we never connect to ourselves - - if (widget.Outputs != null) - { - foreach (var output in widget.Outputs) - { - if (m_Inputs != null) - { - foreach (var input in m_Inputs) - { - if (input.DataType == output.DataType) - { - if (output.AddConnection(input)) - Log.Status("Widget", "Auto-Connecting {0} -> {1}", output.ToString(), input.ToString()); - } - } - } - } - } - - } + c.TargetInput.ReceiveData(data); + sent = true; + } + catch (Exception e) + { + Log.Error("Widget", "Exception sending data {0} to input {1} on object {2}: {3}", + data.Name, c.TargetInput.InputName, c.TargetObject.name, e.ToString()); } + } } + return sent; + } + + /// + /// Add a connection to this output, returns false if the connection can't be made. + /// + /// A reference to the connection to establish. + /// Returns true on success. + public bool AddConnection(Input input) + { + if (!AllowMany && m_Connections.Count > 0) + return false; // already connected. + if (input.DataType != DataType) + return false; // wrong data type + + Connection c = new Connection(); + c.Start(this); + c.TargetInput = input; + m_Connections.Add(c); + + return true; + } + + /// + /// Add a connect to a given object and optional target input. + /// + /// The object to target. + /// A optional argument of the target input on the object. + /// Returns true if a Connection object was added. + public bool AddConnection(GameObject targetObject, string targetConnection = null) + { + if (!AllowMany && m_Connections.Count > 0) + return false; // already connected. + + Connection c = new Connection(); + c.Start(this); + c.TargetObject = targetObject; + if (targetConnection != null) + c.TargetConnection = targetConnection; + if (!c.ResolveTargetInput()) + return false; // couldn't resolve a input + m_Connections.Add(c); + + return true; + } + + /// + /// Remove the connection between widgets. + /// + /// + /// + public bool RemoveConnection(Connection c) + { + return m_Connections.Remove(c); + } + #endregion + + #region Private Data + [SerializeField] + List m_Connections = new List(); + #endregion + }; + #endregion + + #region Private Data + [SerializeField] + private bool m_AutoConnect = true; + private bool m_Initialized = false; + private Input[] m_Inputs = null; + private Output[] m_Outputs = null; + #endregion + + #region Public Properties + /// + /// Returns the name of this widget. + /// + public string WidgetName { get { return GetName(); } } + /// + /// This returns an array of all inputs on this widget. + /// + public Input[] Inputs { get { if (!m_Initialized) InitializeIO(); return m_Inputs; } } + /// + /// This returns an array of all outputs on this widget. + /// + public Output[] Outputs { get { if (!m_Initialized) InitializeIO(); return m_Outputs; } } + #endregion + + #region Public Functions + /// + /// Call this function to go ahead and resolve auto-connections to other widgets. Normally, + /// we would try to auto connect when the Awake() is called, this can be called to resolve + /// the auto connections ahead of time. + /// + public void ResolveConnections() + { + InitializeIO(); + InitializeConnections(); + } + #endregion - private T[] GetMembersByType() where T : class + #region Private Functions + private void InitializeIO() + { + m_Outputs = GetMembersByType(); + foreach (var output in m_Outputs) + output.Start(this); + m_Inputs = GetMembersByType(); + foreach (var input in m_Inputs) + input.Start(this); + m_Initialized = true; + } + + private void InitializeConnections() + { + // we only auto-connect when running in the editor. Doing this run-time might be very dangerous. + if (m_AutoConnect) + { + // this boolean is serialized, so we only ever do this once. Set this at the start + // so we don't end up in a circular loop of widgets. + m_AutoConnect = false; + + Widget[] widgets = FindObjectsOfType(); + foreach (var widget in widgets) { - List inputs = new List(); + if (widget == null || widget == this) + continue; // we never connect to ourselves - MemberInfo[] members = GetType().GetMembers(BindingFlags.Instance | BindingFlags.GetField - | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public); - foreach (MemberInfo info in members) + if (widget.Outputs != null) + { + foreach (var output in widget.Outputs) { - FieldInfo field = info as FieldInfo; - if (field == null) - continue; - if (!typeof(T).IsAssignableFrom(field.FieldType)) - continue; - T input = field.GetValue(this) as T; - if (input == null) - throw new WatsonException("Expected a Connection type."); - - inputs.Add(input); + if (m_Inputs != null) + { + foreach (var input in m_Inputs) + { + if (input.DataType == output.DataType) + { + if (output.AddConnection(input)) + Log.Status("Widget", "Auto-Connecting {0} -> {1}", output.ToString(), input.ToString()); + } + } + } } + } - return inputs.ToArray(); } + } + } - /// - protected virtual void Start() - { - InitializeConnections(); - } + private T[] GetMembersByType() where T : class + { + List inputs = new List(); + + MemberInfo[] members = GetType().GetMembers(BindingFlags.Instance | BindingFlags.GetField + | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public); + foreach (MemberInfo info in members) + { + FieldInfo field = info as FieldInfo; + if (field == null) + continue; + if (!typeof(T).IsAssignableFrom(field.FieldType)) + continue; + T input = field.GetValue(this) as T; + if (input == null) + throw new WatsonException("Expected a Connection type."); + + inputs.Add(input); + } + + return inputs.ToArray(); + } - /// - protected virtual void Awake() - { - InitializeIO(); - } - #endregion + /// + protected virtual void Start() + { + InitializeConnections(); + } - #region Widget Interface - /// - /// Implemented to provide a friendly name for a widget object. - /// - /// A string containing the name for this widget. - protected abstract string GetName(); - #endregion + /// + protected virtual void Awake() + { + InitializeIO(); } + #endregion + + #region Widget Interface + /// + /// Implemented to provide a friendly name for a widget object. + /// + /// A string containing the name for this widget. + protected abstract string GetName(); + #endregion + } } From 4260495895076f07f646af35e4d5fa5c6c888c36 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Wed, 26 Oct 2016 12:00:36 -0500 Subject: [PATCH 24/28] format travis scripts --- Travis/TravisBuild.cs | 63 ++++++++++++++++---------- Travis/TravisIntegrationTests.cs | 76 ++++++++++++++++---------------- 2 files changed, 78 insertions(+), 61 deletions(-) mode change 100644 => 100755 Travis/TravisBuild.cs diff --git a/Travis/TravisBuild.cs b/Travis/TravisBuild.cs old mode 100644 new mode 100755 index 1bbdb9be1..e56536058 --- a/Travis/TravisBuild.cs +++ b/Travis/TravisBuild.cs @@ -1,33 +1,50 @@ -#if UNITY_EDITOR +/** + * Copyright 2015 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. + * + */ + +#if UNITY_EDITOR using UnityEditor; using UnityEngine; public static class RunTravisBuild { - public static string[] BuildScenes = { - "Assets/Watson/Scenes/UnitTests/Main.unity", - "Assets/Watson/Scenes/UnitTests/TestMic.unity", - "Assets/Watson/Scenes/UnitTests/TestNaturalLanguageClassifier.unity", - "Assets/Watson/Scenes/UnitTests/TestSpeechToText.unity", - "Assets/Watson/Scenes/UnitTests/TestTextToSpeech.unity", - "Assets/Watson/Scenes/UnitTests/UnitTests.unity", - "Assets/Watson/Examples/WidgetExamples/ExampleDialog.unity", - "Assets/Watson/Examples/WidgetExamples/ExampleLanguageTranslator.unity" - }; + public static string[] BuildScenes = { + "Assets/Watson/Scenes/UnitTests/Main.unity", + "Assets/Watson/Scenes/UnitTests/TestMic.unity", + "Assets/Watson/Scenes/UnitTests/TestNaturalLanguageClassifier.unity", + "Assets/Watson/Scenes/UnitTests/TestSpeechToText.unity", + "Assets/Watson/Scenes/UnitTests/TestTextToSpeech.unity", + "Assets/Watson/Scenes/UnitTests/UnitTests.unity", + "Assets/Watson/Examples/WidgetExamples/ExampleDialog.unity", + "Assets/Watson/Examples/WidgetExamples/ExampleLanguageTranslator.unity" + }; - static public void OSX() - { - BuildPipeline.BuildPlayer(BuildScenes, Application.dataPath + "TestBuildOSX", BuildTarget.StandaloneOSXIntel64, BuildOptions.None); - } + static public void OSX() + { + BuildPipeline.BuildPlayer(BuildScenes, Application.dataPath + "TestBuildOSX", BuildTarget.StandaloneOSXIntel64, BuildOptions.None); + } - static public void Windows() - { - BuildPipeline.BuildPlayer(BuildScenes, Application.dataPath + "TestBuildWindows", BuildTarget.StandaloneWindows64, BuildOptions.None); - } + static public void Windows() + { + BuildPipeline.BuildPlayer(BuildScenes, Application.dataPath + "TestBuildWindows", BuildTarget.StandaloneWindows64, BuildOptions.None); + } - static public void Linux() - { - BuildPipeline.BuildPlayer(BuildScenes, Application.dataPath + "TestBuildLinux", BuildTarget.StandaloneLinux64, BuildOptions.None); - } + static public void Linux() + { + BuildPipeline.BuildPlayer(BuildScenes, Application.dataPath + "TestBuildLinux", BuildTarget.StandaloneLinux64, BuildOptions.None); + } } #endif \ No newline at end of file diff --git a/Travis/TravisIntegrationTests.cs b/Travis/TravisIntegrationTests.cs index 0e6729f0b..d3e439ffd 100755 --- a/Travis/TravisIntegrationTests.cs +++ b/Travis/TravisIntegrationTests.cs @@ -23,50 +23,50 @@ namespace IBM.Watson.DeveloperCloud.Editor { - /// - /// This class is executed from batch mode during Travis continuous integration. - /// - public class TravisIntegrationTests : MonoBehaviour + /// + /// This class is executed from batch mode during Travis continuous integration. + /// + public class TravisIntegrationTests : MonoBehaviour + { + public static void RunTests() { - public static void RunTests() - { - Log.Debug("TravisIntegrationTests", "***** Running Integration tests!"); + Log.Debug("TravisIntegrationTests", "***** Running Integration tests!"); #if UNITY_EDITOR - Runnable.EnableRunnableInEditor(); + Runnable.EnableRunnableInEditor(); #endif - string ProjectToTest = ""; - string[] args = Environment.GetCommandLineArgs(); - for (int i = 0; i < args.Length; ++i) - { - if (args[i] == "-packageOptions" && (i + 1) < args.Length) - { - string[] options = args[i + 1].Split(','); - foreach (string option in options) - { - if (string.IsNullOrEmpty(option)) - continue; + string ProjectToTest = ""; + string[] args = Environment.GetCommandLineArgs(); + for (int i = 0; i < args.Length; ++i) + { + if (args[i] == "-packageOptions" && (i + 1) < args.Length) + { + string[] options = args[i + 1].Split(','); + foreach (string option in options) + { + if (string.IsNullOrEmpty(option)) + continue; - string[] kv = option.Split('='); - if (kv[0] == "ProjectName") - { - ProjectToTest = kv.Length > 1 ? kv[1] : ""; - Log.Status("RunUnitTest", "AutoLunchOptions ProjectToTest:{0}", ProjectToTest); - break; - } - } - } + string[] kv = option.Split('='); + if (kv[0] == "ProjectName") + { + ProjectToTest = kv.Length > 1 ? kv[1] : ""; + Log.Status("RunUnitTest", "AutoLunchOptions ProjectToTest:{0}", ProjectToTest); + break; } - - IBM.Watson.DeveloperCloud.Editor.UnitTestManager.ProjectToTest = ProjectToTest; - IBM.Watson.DeveloperCloud.Editor.UnitTestManager instance = IBM.Watson.DeveloperCloud.Editor.UnitTestManager.Instance; - instance.QuitOnTestsComplete = true; - instance.OnTestCompleteCallback = OnTravisIntegrationTestsComplete; - instance.QueueTests(Utility.FindAllDerivedTypes(typeof(UnitTest)), true); - } - static void OnTravisIntegrationTestsComplete() - { - Log.Debug("TravisIntegrationTests", " ***** Integration tests complete!"); + } } + } + + UnitTestManager.ProjectToTest = ProjectToTest; + UnitTestManager instance = UnitTestManager.Instance; + instance.QuitOnTestsComplete = true; + instance.OnTestCompleteCallback = OnTravisIntegrationTestsComplete; + instance.QueueTests(Utility.FindAllDerivedTypes(typeof(UnitTest)), true); + } + static void OnTravisIntegrationTestsComplete() + { + Log.Debug("TravisIntegrationTests", " ***** Integration tests complete!"); } + } } From f4a59d9385021684f843d69b3a270cd282823f2c Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Wed, 26 Oct 2016 12:06:04 -0500 Subject: [PATCH 25/28] reformat services --- Scripts/Services/AlchemyAPI/AlchemyAPI.cs | 4388 ++++++------- Scripts/Services/AlchemyAPI/DataModels.cs | 5420 ++++++++--------- .../Conversation-Experimental.cs | 348 +- .../Conversation-Experimental/DataModels.cs | 744 +-- Scripts/Services/Conversation/Conversation.cs | 428 +- Scripts/Services/Conversation/DataModels.cs | 487 +- Scripts/Services/DeepQA/DataModels.cs | 1014 +-- Scripts/Services/DeepQA/DeepQA.cs | 356 +- .../Services/DocumentConversion/DataModels.cs | 272 +- .../DocumentConversion/DocumentConversion.cs | 326 +- Scripts/Services/IWatsonService.cs | 88 +- .../LanguageTranslation/DataModels.cs | 226 +- .../LanguageTranslation.cs | 778 +-- .../Services/LanguageTranslator/DataModels.cs | 226 +- .../LanguageTranslator/LanguageTranslator.cs | 778 +-- .../NaturalLanguageClassifier/DataModels.cs | 196 +- .../NaturalLanguageClassifier.cs | 1084 ++-- .../PersonalityInsights/v2/DataModels.cs | 504 +- .../v2/PersonalityInsights.cs | 298 +- .../v3/PersonalityInsights.cs | 0 .../Services/RetrieveAndRank/DataModels.cs | 808 +-- .../RetrieveAndRank/RetrieveAndRank.cs | 3108 +++++----- Scripts/Services/SpeechToText/DataModels.cs | 1312 ++-- Scripts/Services/SpeechToText/SpeechToText.cs | 3470 +++++------ Scripts/Services/TextToSpeech/DataModels.cs | 706 +-- Scripts/Services/TextToSpeech/TextToSpeech.cs | 2152 +++---- Scripts/Services/ToneAnalyzer/DataModels.cs | 406 +- Scripts/Services/ToneAnalyzer/ToneAnalyzer.cs | 230 +- .../Services/TradeoffAnalytics/DataModels.cs | 778 +-- .../TradeoffAnalytics/TradeoffAnalytics.cs | 306 +- .../Services/VisualRecognition/DataModels.cs | 1358 ++--- .../VisualRecognition/VisualRecognition.cs | 4394 ++++++------- 32 files changed, 18496 insertions(+), 18493 deletions(-) mode change 100644 => 100755 Scripts/Services/DeepQA/DataModels.cs mode change 100644 => 100755 Scripts/Services/DeepQA/DeepQA.cs mode change 100644 => 100755 Scripts/Services/IWatsonService.cs mode change 100644 => 100755 Scripts/Services/LanguageTranslation/DataModels.cs mode change 100644 => 100755 Scripts/Services/LanguageTranslator/DataModels.cs mode change 100644 => 100755 Scripts/Services/LanguageTranslator/LanguageTranslator.cs mode change 100644 => 100755 Scripts/Services/NaturalLanguageClassifier/DataModels.cs mode change 100644 => 100755 Scripts/Services/NaturalLanguageClassifier/NaturalLanguageClassifier.cs mode change 100644 => 100755 Scripts/Services/PersonalityInsights/v2/DataModels.cs mode change 100644 => 100755 Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs mode change 100644 => 100755 Scripts/Services/ToneAnalyzer/DataModels.cs mode change 100644 => 100755 Scripts/Services/ToneAnalyzer/ToneAnalyzer.cs mode change 100644 => 100755 Scripts/Services/TradeoffAnalytics/DataModels.cs mode change 100644 => 100755 Scripts/Services/TradeoffAnalytics/TradeoffAnalytics.cs diff --git a/Scripts/Services/AlchemyAPI/AlchemyAPI.cs b/Scripts/Services/AlchemyAPI/AlchemyAPI.cs index 94aca5ab7..270b93a59 100755 --- a/Scripts/Services/AlchemyAPI/AlchemyAPI.cs +++ b/Scripts/Services/AlchemyAPI/AlchemyAPI.cs @@ -29,2347 +29,2347 @@ namespace IBM.Watson.DeveloperCloud.Services.AlchemyAPI.v1 { - /// - /// This class wraps the Alchemy API Services. - /// Alchemy Language - /// AlchemyData News - /// - public class AlchemyAPI : IWatsonService + /// + /// This class wraps the Alchemy API Services. + /// Alchemy Language + /// AlchemyData News + /// + public class AlchemyAPI : IWatsonService + { + + #region Private Data + private const string SERVICE_ID = "AlchemyAPIV1"; + private static string mp_ApiKey = null; + + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region SetCredentials + private void SetCredentials() { + mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID); - #region Private Data - private const string SERVICE_ID = "AlchemyAPIV1"; - private static string mp_ApiKey = null; - - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region SetCredentials - private void SetCredentials() - { - mp_ApiKey = Config.Instance.GetAPIKey(SERVICE_ID); - - if (string.IsNullOrEmpty(mp_ApiKey)) - throw new WatsonException("Alchemy API Key required in config.json"); - } - #endregion - - #region GetAuthors - private const string SERVICE_GET_AUTHORS_URL = "/url/URLGetAuthors"; - private const string SERVICE_GET_AUTHORS_HTML = "/html/HTMLGetAuthors"; - - /// - /// On get authors delegate. - /// - public delegate void OnGetAuthors(AuthorsData authorExtractionData, string data); - - /// - /// Extracts authors from a source. - /// - /// true, if authors was gotten, false otherwise. - /// Callback. - /// URL or HTML source. - /// Custom data. - public bool GetAuthors(OnGetAuthors callback, string source, string customData = default(string)) + if (string.IsNullOrEmpty(mp_ApiKey)) + throw new WatsonException("Alchemy API Key required in config.json"); + } + #endregion + + #region GetAuthors + private const string SERVICE_GET_AUTHORS_URL = "/url/URLGetAuthors"; + private const string SERVICE_GET_AUTHORS_HTML = "/html/HTMLGetAuthors"; + + /// + /// On get authors delegate. + /// + public delegate void OnGetAuthors(AuthorsData authorExtractionData, string data); + + /// + /// Extracts authors from a source. + /// + /// true, if authors was gotten, false otherwise. + /// Callback. + /// URL or HTML source. + /// Custom data. + public bool GetAuthors(OnGetAuthors callback, string source, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new ArgumentNullException("Please provide a source for GetAuthors."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetAuthorsRequest req = new GetAuthorsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_AUTHORS_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new ArgumentNullException("Please provide a source for GetAuthors."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetAuthorsRequest req = new GetAuthorsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_AUTHORS_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_AUTHORS_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetAuthors"); - } - else - { - Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetAuthors!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetAuthorsResponse; - return connector.Send(req); + service = SERVICE_GET_AUTHORS_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetAuthors"); + } + else + { + Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetAuthors!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetAuthorsResponse; + return connector.Send(req); + } - /// - /// Get authors request. - /// - public class GetAuthorsRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetAuthors Callback { get; set; } - } + /// + /// Get authors request. + /// + public class GetAuthorsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetAuthors Callback { get; set; } + } - private void OnGetAuthorsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetAuthorsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + AuthorsData authorsData = new AuthorsData(); + if (resp.Success) + { + try { - AuthorsData authorsData = new AuthorsData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = authorsData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetAuthorsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetAuthorsRequest)req).Callback != null) - ((GetAuthorsRequest)req).Callback(resp.Success ? authorsData : null, ((GetAuthorsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = authorsData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetRankedConcepts - private const string SERVICE_GET_RANKED_CONCEPTS_HTML = "/html/HTMLGetRankedConcepts"; - private const string SERVICE_GET_RANKED_CONCEPTS_URL = "/url/URLGetRankedConcepts"; - private const string SERVICE_GET_RANKED_CONCEPTS_TEXT = "/text/TextGetRankedConcepts"; - - /// - /// On get ranked concepts delegate. - /// - public delegate void OnGetRankedConcepts(ConceptsData conceptExtractionData, string data); - - /// - /// Extracts concepts from a source. - /// - /// true, if ranked concepts was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text Source. - /// Maximum results retreived. - /// If set to true include knowledge graph. - /// If set to true include linked data. - /// If set to true include source text. - /// Custom data. - public bool GetRankedConcepts(OnGetRankedConcepts callback, string source, - int maxRetrieve = 8, - bool includeKnowledgeGraph = false, - bool includeLinkedData = true, - bool includeSourceText = false, - string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetAuthors."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetRankedConceptsRequest req = new GetRankedConceptsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["maxRetrieve"] = maxRetrieve; - req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); - req.Parameters["linkedData"] = Convert.ToInt32(includeLinkedData).ToString(); - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_RANKED_CONCEPTS_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (!normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://") && source.StartsWith(Application.dataPath)) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_RANKED_CONCEPTS_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetRankedConcepts"); - } - else - { - service = SERVICE_GET_RANKED_CONCEPTS_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetRankedConceptsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetAuthorsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get ranked concepts request. - /// - public class GetRankedConceptsRequest : RESTConnector.Request + if (((GetAuthorsRequest)req).Callback != null) + ((GetAuthorsRequest)req).Callback(resp.Success ? authorsData : null, ((GetAuthorsRequest)req).Data); + } + #endregion + + #region GetRankedConcepts + private const string SERVICE_GET_RANKED_CONCEPTS_HTML = "/html/HTMLGetRankedConcepts"; + private const string SERVICE_GET_RANKED_CONCEPTS_URL = "/url/URLGetRankedConcepts"; + private const string SERVICE_GET_RANKED_CONCEPTS_TEXT = "/text/TextGetRankedConcepts"; + + /// + /// On get ranked concepts delegate. + /// + public delegate void OnGetRankedConcepts(ConceptsData conceptExtractionData, string data); + + /// + /// Extracts concepts from a source. + /// + /// true, if ranked concepts was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text Source. + /// Maximum results retreived. + /// If set to true include knowledge graph. + /// If set to true include linked data. + /// If set to true include source text. + /// Custom data. + public bool GetRankedConcepts(OnGetRankedConcepts callback, string source, + int maxRetrieve = 8, + bool includeKnowledgeGraph = false, + bool includeLinkedData = true, + bool includeSourceText = false, + string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetAuthors."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetRankedConceptsRequest req = new GetRankedConceptsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["maxRetrieve"] = maxRetrieve; + req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); + req.Parameters["linkedData"] = Convert.ToInt32(includeLinkedData).ToString(); + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_RANKED_CONCEPTS_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (!normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://") && source.StartsWith(Application.dataPath)) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetRankedConcepts Callback { get; set; } + service = SERVICE_GET_RANKED_CONCEPTS_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetRankedConcepts"); + } + else + { + service = SERVICE_GET_RANKED_CONCEPTS_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetRankedConceptsResponse; + return connector.Send(req); + } - private void OnGetRankedConceptsResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Get ranked concepts request. + /// + public class GetRankedConceptsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetRankedConcepts Callback { get; set; } + } + + private void OnGetRankedConceptsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + ConceptsData conceptsData = new ConceptsData(); + if (resp.Success) + { + try { - ConceptsData conceptsData = new ConceptsData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = conceptsData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetRankedConceptsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetRankedConceptsRequest)req).Callback != null) - ((GetRankedConceptsRequest)req).Callback(resp.Success ? conceptsData : null, ((GetRankedConceptsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = conceptsData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region ExtractDates - private const string SERVICE_GET_DATES_HTML = "/html/HTMLExtractDates"; - private const string SERVICE_GET_DATES_URL = "/url/URLExtractDates"; - private const string SERVICE_GET_DATES_TEXT = "/text/TextExtractDates"; - - /// - /// On get dates delegate. - /// - public delegate void OnGetDates(DateData dateData, string data); - - /// - /// Extracts dates from a source. - /// - /// true, if dates was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// Anchor date in the yyyy-mm-dd hh:mm:ss format. If this is not set, anchor date is set to today's date and time. - /// If set to true include source text. - /// Custom data. - public bool GetDates(OnGetDates callback, string source, string anchorDate = default(string), bool includeSourceText = false, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetAuthors."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - if (string.IsNullOrEmpty(anchorDate)) - anchorDate = GetCurrentDatetime(); - - GetDatesRequest req = new GetDatesRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - req.Forms["anchorDate"] = new RESTConnector.Form(anchorDate); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_DATES_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_DATES_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for ExtractDates!"); - } - else - { - service = SERVICE_GET_DATES_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetDatesResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetRankedConceptsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get dates request. - /// - public class GetDatesRequest : RESTConnector.Request + if (((GetRankedConceptsRequest)req).Callback != null) + ((GetRankedConceptsRequest)req).Callback(resp.Success ? conceptsData : null, ((GetRankedConceptsRequest)req).Data); + } + #endregion + + #region ExtractDates + private const string SERVICE_GET_DATES_HTML = "/html/HTMLExtractDates"; + private const string SERVICE_GET_DATES_URL = "/url/URLExtractDates"; + private const string SERVICE_GET_DATES_TEXT = "/text/TextExtractDates"; + + /// + /// On get dates delegate. + /// + public delegate void OnGetDates(DateData dateData, string data); + + /// + /// Extracts dates from a source. + /// + /// true, if dates was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// Anchor date in the yyyy-mm-dd hh:mm:ss format. If this is not set, anchor date is set to today's date and time. + /// If set to true include source text. + /// Custom data. + public bool GetDates(OnGetDates callback, string source, string anchorDate = default(string), bool includeSourceText = false, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetAuthors."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + if (string.IsNullOrEmpty(anchorDate)) + anchorDate = GetCurrentDatetime(); + + GetDatesRequest req = new GetDatesRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + req.Forms["anchorDate"] = new RESTConnector.Form(anchorDate); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_DATES_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetDates Callback { get; set; } + service = SERVICE_GET_DATES_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for ExtractDates!"); + } + else + { + service = SERVICE_GET_DATES_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetDatesResponse; + return connector.Send(req); + } - private void OnGetDatesResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - DateData dateData = new DateData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = dateData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnDatesResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetDatesRequest)req).Callback != null) - ((GetDatesRequest)req).Callback(resp.Success ? dateData : null, ((GetDatesRequest)req).Data); - } + /// + /// Get dates request. + /// + public class GetDatesRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetDates Callback { get; set; } + } - private string GetCurrentDatetime() + private void OnGetDatesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DateData dateData = new DateData(); + if (resp.Success) + { + try { - // date format is yyyy-mm-dd hh:mm:ss - string dateFormat = "{0}-{1}-{2} {3}:{4}:{5}"; - return string.Format(dateFormat, System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day, System.DateTime.Now.Hour, System.DateTime.Now.Minute, System.DateTime.Now.Second); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = dateData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetEmotion - private const string SERVICE_GET_EMOTION_HTML = "/html/HTMLGetEmotion"; - private const string SERVICE_GET_EMOTION_URL = "/url/URLGetEmotion"; - private const string SERVICE_GET_EMOTION_TEXT = "/text/TextGetEmotion"; - - /// - /// On get emotions delegate. - /// - public delegate void OnGetEmotions(EmotionData emotionData, string data); - - /// - /// Gets the emotions from a source. - /// - /// true, if emotions was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// If set to true include source text. - /// Custom data. - public bool GetEmotions(OnGetEmotions callback, string source, bool includeSourceText = false, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetEmotions."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetEmotionsRequest req = new GetEmotionsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_EMOTION_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_EMOTION_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetEmotions!"); - } - else - { - service = SERVICE_GET_EMOTION_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetEmotionsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnDatesResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } + + if (((GetDatesRequest)req).Callback != null) + ((GetDatesRequest)req).Callback(resp.Success ? dateData : null, ((GetDatesRequest)req).Data); + } - /// - /// Get emotions request. - /// - public class GetEmotionsRequest : RESTConnector.Request + private string GetCurrentDatetime() + { + // date format is yyyy-mm-dd hh:mm:ss + string dateFormat = "{0}-{1}-{2} {3}:{4}:{5}"; + return string.Format(dateFormat, System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day, System.DateTime.Now.Hour, System.DateTime.Now.Minute, System.DateTime.Now.Second); + } + #endregion + + #region GetEmotion + private const string SERVICE_GET_EMOTION_HTML = "/html/HTMLGetEmotion"; + private const string SERVICE_GET_EMOTION_URL = "/url/URLGetEmotion"; + private const string SERVICE_GET_EMOTION_TEXT = "/text/TextGetEmotion"; + + /// + /// On get emotions delegate. + /// + public delegate void OnGetEmotions(EmotionData emotionData, string data); + + /// + /// Gets the emotions from a source. + /// + /// true, if emotions was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// If set to true include source text. + /// Custom data. + public bool GetEmotions(OnGetEmotions callback, string source, bool includeSourceText = false, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetEmotions."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetEmotionsRequest req = new GetEmotionsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_EMOTION_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetEmotions Callback { get; set; } + service = SERVICE_GET_EMOTION_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetEmotions!"); + } + else + { + service = SERVICE_GET_EMOTION_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetEmotionsResponse; + return connector.Send(req); + } + + /// + /// Get emotions request. + /// + public class GetEmotionsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetEmotions Callback { get; set; } + } - private void OnGetEmotionsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetEmotionsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + EmotionData emotionData = new EmotionData(); + if (resp.Success) + { + try { - EmotionData emotionData = new EmotionData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = emotionData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetEmotionsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetEmotionsRequest)req).Callback != null) - ((GetEmotionsRequest)req).Callback(resp.Success ? emotionData : null, ((GetEmotionsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = emotionData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Entity Extraction - private const string SERVICE_GET_ENTITY_EXTRACTION_HTML = "/html/HTMLGetRankedNamedEntities"; - private const string SERVICE_GET_ENTITY_EXTRACTION_URL = "/url/URLGetRankedNamedEntities"; - private const string SERVICE_GET_ENTITY_EXTRACTION_TEXT = "/text/TextGetRankedNamedEntities"; - - /// - /// On get entities delegate. - /// - public delegate void OnGetEntities(EntityData entityData, string data); - - /// - /// Extracts the entities from a source. - /// - /// true, if entities was extracted, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// Maximum results retreived. - /// If set to true resolve coreference. - /// If set to true disambiguate. - /// If set to true include knowledge graph. - /// If set to true include linked data. - /// If set to true include quotations. - /// If set to true analyze sentiment. - /// If set to true include source text. - /// If set to true extract structured entities. - /// Custom data. - public bool ExtractEntities(OnGetEntities callback, string source, - int maxRetrieve = 50, - bool resolveCoreference = true, - bool disambiguate = true, - bool includeKnowledgeGraph = false, - bool includeLinkedData = true, - bool includeQuotations = false, - bool analyzeSentiment = false, - bool includeSourceText = false, - bool extractStructuredEntities = true, - string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for ExtractEntities."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetEntitiesRequest req = new GetEntitiesRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["maxRetrieve"] = Convert.ToInt32(maxRetrieve).ToString(); - req.Parameters["coreference"] = Convert.ToInt32(resolveCoreference).ToString(); - req.Parameters["disambiguate"] = Convert.ToInt32(disambiguate).ToString(); - req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); - req.Parameters["linkedData"] = Convert.ToInt32(includeLinkedData).ToString(); - req.Parameters["quotations"] = Convert.ToInt32(includeQuotations).ToString(); - req.Parameters["sentiment"] = Convert.ToInt32(analyzeSentiment).ToString(); - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - req.Parameters["structuredEntities"] = Convert.ToInt32(extractStructuredEntities).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_ENTITY_EXTRACTION_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_ENTITY_EXTRACTION_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for ExtractEntities!"); - } - else - { - service = SERVICE_GET_ENTITY_EXTRACTION_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetEntitiesResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetEmotionsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get entities request. - /// - public class GetEntitiesRequest : RESTConnector.Request + if (((GetEmotionsRequest)req).Callback != null) + ((GetEmotionsRequest)req).Callback(resp.Success ? emotionData : null, ((GetEmotionsRequest)req).Data); + } + #endregion + + #region Entity Extraction + private const string SERVICE_GET_ENTITY_EXTRACTION_HTML = "/html/HTMLGetRankedNamedEntities"; + private const string SERVICE_GET_ENTITY_EXTRACTION_URL = "/url/URLGetRankedNamedEntities"; + private const string SERVICE_GET_ENTITY_EXTRACTION_TEXT = "/text/TextGetRankedNamedEntities"; + + /// + /// On get entities delegate. + /// + public delegate void OnGetEntities(EntityData entityData, string data); + + /// + /// Extracts the entities from a source. + /// + /// true, if entities was extracted, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// Maximum results retreived. + /// If set to true resolve coreference. + /// If set to true disambiguate. + /// If set to true include knowledge graph. + /// If set to true include linked data. + /// If set to true include quotations. + /// If set to true analyze sentiment. + /// If set to true include source text. + /// If set to true extract structured entities. + /// Custom data. + public bool ExtractEntities(OnGetEntities callback, string source, + int maxRetrieve = 50, + bool resolveCoreference = true, + bool disambiguate = true, + bool includeKnowledgeGraph = false, + bool includeLinkedData = true, + bool includeQuotations = false, + bool analyzeSentiment = false, + bool includeSourceText = false, + bool extractStructuredEntities = true, + string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for ExtractEntities."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetEntitiesRequest req = new GetEntitiesRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["maxRetrieve"] = Convert.ToInt32(maxRetrieve).ToString(); + req.Parameters["coreference"] = Convert.ToInt32(resolveCoreference).ToString(); + req.Parameters["disambiguate"] = Convert.ToInt32(disambiguate).ToString(); + req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); + req.Parameters["linkedData"] = Convert.ToInt32(includeLinkedData).ToString(); + req.Parameters["quotations"] = Convert.ToInt32(includeQuotations).ToString(); + req.Parameters["sentiment"] = Convert.ToInt32(analyzeSentiment).ToString(); + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + req.Parameters["structuredEntities"] = Convert.ToInt32(extractStructuredEntities).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_ENTITY_EXTRACTION_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetEntities Callback { get; set; } + service = SERVICE_GET_ENTITY_EXTRACTION_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for ExtractEntities!"); + } + else + { + service = SERVICE_GET_ENTITY_EXTRACTION_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetEntitiesResponse; + return connector.Send(req); + } - private void OnGetEntitiesResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Get entities request. + /// + public class GetEntitiesRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetEntities Callback { get; set; } + } + + private void OnGetEntitiesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + EntityData entityData = new EntityData(); + if (resp.Success) + { + try { - EntityData entityData = new EntityData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = entityData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetEntitiesResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetEntitiesRequest)req).Callback != null) - ((GetEntitiesRequest)req).Callback(resp.Success ? entityData : null, ((GetEntitiesRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = entityData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region FeedDetection - private const string SERVICE_DETECT_FEEDS_URL = "/url/URLGetFeedLinks"; - private const string SERVICE_DETECT_FEEDS_HTML = "/html/HTMLGetFeedLinks"; - - /// - /// On detect feeds delegate. - /// - public delegate void OnDetectFeeds(FeedData feedData, string data); - - /// - /// Detects RSS feeds in a source. - /// - /// true, if feeds was detected, false otherwise. - /// Callback. - /// URL to detect feeds. - /// Custom data. - public bool DetectFeeds(OnDetectFeeds callback, string source, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetEmotions."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - DetectFeedsRequest req = new DetectFeedsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_DETECT_FEEDS_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - Log.Error("Alchemy Language", "A URL source is required for DetectFeeds!"); - return false; - // service = SERVICE_DETECT_FEEDS_HTML; - // string htmlData = default(string); - // htmlData = File.ReadAllText(source); - // req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - { - Log.Error("Alchemy Language", "A URL source is required for DetectFeeds!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnDetectFeedsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetEntitiesResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Detect feeds request. - /// - public class DetectFeedsRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnDetectFeeds Callback { get; set; } - } + if (((GetEntitiesRequest)req).Callback != null) + ((GetEntitiesRequest)req).Callback(resp.Success ? entityData : null, ((GetEntitiesRequest)req).Data); + } + #endregion + + #region FeedDetection + private const string SERVICE_DETECT_FEEDS_URL = "/url/URLGetFeedLinks"; + private const string SERVICE_DETECT_FEEDS_HTML = "/html/HTMLGetFeedLinks"; + + /// + /// On detect feeds delegate. + /// + public delegate void OnDetectFeeds(FeedData feedData, string data); + + /// + /// Detects RSS feeds in a source. + /// + /// true, if feeds was detected, false otherwise. + /// Callback. + /// URL to detect feeds. + /// Custom data. + public bool DetectFeeds(OnDetectFeeds callback, string source, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetEmotions."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + DetectFeedsRequest req = new DetectFeedsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_DETECT_FEEDS_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + Log.Error("Alchemy Language", "A URL source is required for DetectFeeds!"); + return false; + // service = SERVICE_DETECT_FEEDS_HTML; + // string htmlData = default(string); + // htmlData = File.ReadAllText(source); + // req.Forms["html"] = new RESTConnector.Form(htmlData); + } + else + { + Log.Error("Alchemy Language", "A URL source is required for DetectFeeds!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnDetectFeedsResponse; + return connector.Send(req); + } - private void OnDetectFeedsResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Detect feeds request. + /// + public class DetectFeedsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnDetectFeeds Callback { get; set; } + } + + private void OnDetectFeedsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + FeedData feedData = new FeedData(); + if (resp.Success) + { + try { - FeedData feedData = new FeedData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = feedData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnDetectFeedsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((DetectFeedsRequest)req).Callback != null) - ((DetectFeedsRequest)req).Callback(resp.Success ? feedData : null, ((DetectFeedsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = feedData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Keyword Extraction - private const string SERVICE_GET_KEYWORD_EXTRACTION_HTML = "/html/HTMLGetRankedKeywords"; - private const string SERVICE_GET_KEYWORD_EXTRACTION_URL = "/url/URLGetRankedKeywords"; - private const string SERVICE_GET_KEYWORD_EXTRACTION_TEXT = "/text/TextGetRankedKeywords"; - - /// - /// On get keywords delegate. - /// - public delegate void OnGetKeywords(KeywordData keywordData, string data); - - /// - /// Extracts the keywords from a source. - /// - /// true, if keywords was extracted, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// Maximum results retreived. - /// If set to true include knowledge graph. - /// If set to true analyze sentiment. - /// If set to true include source text. - /// Custom data. - public bool ExtractKeywords(OnGetKeywords callback, string source, - int maxRetrieve = 50, - bool includeKnowledgeGraph = false, - bool analyzeSentiment = false, - bool includeSourceText = false, - string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for ExtractKeywords."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetKeywordsRequest req = new GetKeywordsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["maxRetrieve"] = Convert.ToInt32(maxRetrieve).ToString(); - req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); - req.Parameters["sentiment"] = Convert.ToInt32(analyzeSentiment).ToString(); - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - req.Parameters["keywordExtractMode"] = "strict"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_KEYWORD_EXTRACTION_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_KEYWORD_EXTRACTION_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for Getkeywords!"); - } - else - { - service = SERVICE_GET_KEYWORD_EXTRACTION_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetKeywordsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnDetectFeedsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get keywords request. - /// - public class GetKeywordsRequest : RESTConnector.Request + if (((DetectFeedsRequest)req).Callback != null) + ((DetectFeedsRequest)req).Callback(resp.Success ? feedData : null, ((DetectFeedsRequest)req).Data); + } + #endregion + + #region Keyword Extraction + private const string SERVICE_GET_KEYWORD_EXTRACTION_HTML = "/html/HTMLGetRankedKeywords"; + private const string SERVICE_GET_KEYWORD_EXTRACTION_URL = "/url/URLGetRankedKeywords"; + private const string SERVICE_GET_KEYWORD_EXTRACTION_TEXT = "/text/TextGetRankedKeywords"; + + /// + /// On get keywords delegate. + /// + public delegate void OnGetKeywords(KeywordData keywordData, string data); + + /// + /// Extracts the keywords from a source. + /// + /// true, if keywords was extracted, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// Maximum results retreived. + /// If set to true include knowledge graph. + /// If set to true analyze sentiment. + /// If set to true include source text. + /// Custom data. + public bool ExtractKeywords(OnGetKeywords callback, string source, + int maxRetrieve = 50, + bool includeKnowledgeGraph = false, + bool analyzeSentiment = false, + bool includeSourceText = false, + string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for ExtractKeywords."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetKeywordsRequest req = new GetKeywordsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["maxRetrieve"] = Convert.ToInt32(maxRetrieve).ToString(); + req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); + req.Parameters["sentiment"] = Convert.ToInt32(analyzeSentiment).ToString(); + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + req.Parameters["keywordExtractMode"] = "strict"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_KEYWORD_EXTRACTION_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetKeywords Callback { get; set; } + service = SERVICE_GET_KEYWORD_EXTRACTION_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for Getkeywords!"); + } + else + { + service = SERVICE_GET_KEYWORD_EXTRACTION_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetKeywordsResponse; + return connector.Send(req); + } + + /// + /// Get keywords request. + /// + public class GetKeywordsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetKeywords Callback { get; set; } + } - private void OnGetKeywordsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetKeywordsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + KeywordData keywordData = new KeywordData(); + if (resp.Success) + { + try { - KeywordData keywordData = new KeywordData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = keywordData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetKeywordsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetKeywordsRequest)req).Callback != null) - ((GetKeywordsRequest)req).Callback(resp.Success ? keywordData : null, ((GetKeywordsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = keywordData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetLanguage - private const string SERVICE_GET_LANGUAGE_HTML = "/html/HTMLGetLanguage"; - private const string SERVICE_GET_LANGUAGE_URL = "/url/URLGetLanguage"; - private const string SERVICE_GET_LANGUAGE_TEXT = "/text/TextGetLanguage"; - - /// - /// On get languages. - /// - public delegate void OnGetLanguages(LanguageData languageData, string data); - - /// - /// Extracts the language a source is written. - /// - /// true, if languages was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// If set to true include source text. - /// Custom data. - public bool GetLanguages(OnGetLanguages callback, string source, bool includeSourceText = false, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetLanguages."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetLanguagesRequest req = new GetLanguagesRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_LANGUAGE_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_LANGUAGE_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetLanguages!"); - } - else - { - service = SERVICE_GET_LANGUAGE_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetLanguagesResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetKeywordsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get languages request. - /// - public class GetLanguagesRequest : RESTConnector.Request + if (((GetKeywordsRequest)req).Callback != null) + ((GetKeywordsRequest)req).Callback(resp.Success ? keywordData : null, ((GetKeywordsRequest)req).Data); + } + #endregion + + #region GetLanguage + private const string SERVICE_GET_LANGUAGE_HTML = "/html/HTMLGetLanguage"; + private const string SERVICE_GET_LANGUAGE_URL = "/url/URLGetLanguage"; + private const string SERVICE_GET_LANGUAGE_TEXT = "/text/TextGetLanguage"; + + /// + /// On get languages. + /// + public delegate void OnGetLanguages(LanguageData languageData, string data); + + /// + /// Extracts the language a source is written. + /// + /// true, if languages was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// If set to true include source text. + /// Custom data. + public bool GetLanguages(OnGetLanguages callback, string source, bool includeSourceText = false, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetLanguages."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetLanguagesRequest req = new GetLanguagesRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_LANGUAGE_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetLanguages Callback { get; set; } + service = SERVICE_GET_LANGUAGE_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetLanguages!"); + } + else + { + service = SERVICE_GET_LANGUAGE_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetLanguagesResponse; + return connector.Send(req); + } + + /// + /// Get languages request. + /// + public class GetLanguagesRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetLanguages Callback { get; set; } + } - private void OnGetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + LanguageData languageData = new LanguageData(); + if (resp.Success) + { + try { - LanguageData languageData = new LanguageData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = languageData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetEmotionsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetLanguagesRequest)req).Callback != null) - ((GetLanguagesRequest)req).Callback(resp.Success ? languageData : null, ((GetLanguagesRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = languageData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetMicroformat - private const string SERVICE_GET_MICROFORMAT_URL = "/url/URLGetMicroformatData"; - private const string SERVICE_GET_MICROFORMAT_HTML = "/html/HTMLGetMicroformatData"; - - /// - /// On get microformats. - /// - public delegate void OnGetMicroformats(MicroformatData microformatData, string data); - - /// - /// Extracts microformats from a URL source. - /// - /// true, if microformats was gotten, false otherwise. - /// Callback. - /// URL to extract microformats from. - /// Custom data. - public bool GetMicroformats(OnGetMicroformats callback, string source, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a url for GetMicroformats."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetMicroformatsRequest req = new GetMicroformatsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service = ""; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_MICROFORMAT_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - Log.Error("Alchemy Language", "A URL source is required for GetMicroformats!"); - return false; - // service = SERVICE_GET_MICROFORMAT_HTML; - // string htmlData = default(string); - // htmlData = File.ReadAllText(source); - // req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - { - Log.Error("Alchemy Language", "A URL source is required for GetMicroformats!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetMicroformatsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetEmotionsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get microformats request. - /// - public class GetMicroformatsRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetMicroformats Callback { get; set; } - } + if (((GetLanguagesRequest)req).Callback != null) + ((GetLanguagesRequest)req).Callback(resp.Success ? languageData : null, ((GetLanguagesRequest)req).Data); + } + #endregion + + #region GetMicroformat + private const string SERVICE_GET_MICROFORMAT_URL = "/url/URLGetMicroformatData"; + private const string SERVICE_GET_MICROFORMAT_HTML = "/html/HTMLGetMicroformatData"; + + /// + /// On get microformats. + /// + public delegate void OnGetMicroformats(MicroformatData microformatData, string data); + + /// + /// Extracts microformats from a URL source. + /// + /// true, if microformats was gotten, false otherwise. + /// Callback. + /// URL to extract microformats from. + /// Custom data. + public bool GetMicroformats(OnGetMicroformats callback, string source, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a url for GetMicroformats."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetMicroformatsRequest req = new GetMicroformatsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service = ""; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_MICROFORMAT_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + Log.Error("Alchemy Language", "A URL source is required for GetMicroformats!"); + return false; + // service = SERVICE_GET_MICROFORMAT_HTML; + // string htmlData = default(string); + // htmlData = File.ReadAllText(source); + // req.Forms["html"] = new RESTConnector.Form(htmlData); + } + else + { + Log.Error("Alchemy Language", "A URL source is required for GetMicroformats!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetMicroformatsResponse; + return connector.Send(req); + } + + /// + /// Get microformats request. + /// + public class GetMicroformatsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetMicroformats Callback { get; set; } + } - private void OnGetMicroformatsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetMicroformatsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + MicroformatData microformatData = new MicroformatData(); + if (resp.Success) + { + try { - MicroformatData microformatData = new MicroformatData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = microformatData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetMicroformatsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetMicroformatsRequest)req).Callback != null) - ((GetMicroformatsRequest)req).Callback(resp.Success ? microformatData : null, ((GetMicroformatsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = microformatData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetPubDate - private const string SERVICE_GET_PUBLICATION_DATE_URL = "/url/URLGetPubDate"; - private const string SERVICE_GET_PUBLICATION_DATE_HTML = "/html/HTMLGetPubDate"; - - /// - /// On get publication date delegate. - /// - public delegate void OnGetPublicationDate(PubDateData pubDateData, string data); - - /// - /// Extracts the publication date from a source. - /// - /// true, if publication date was gotten, false otherwise. - /// Callback. - /// URL or HTML sources. - /// Custom data. - public bool GetPublicationDate(OnGetPublicationDate callback, string source, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a url for GetPublicationDate."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetPublicationDateRequest req = new GetPublicationDateRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service = ""; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_PUBLICATION_DATE_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_PUBLICATION_DATE_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetPubicationDate!"); - } - else - { - Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetPublicationDate!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetPublicationDateResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetMicroformatsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get publication date request. - /// - public class GetPublicationDateRequest : RESTConnector.Request + if (((GetMicroformatsRequest)req).Callback != null) + ((GetMicroformatsRequest)req).Callback(resp.Success ? microformatData : null, ((GetMicroformatsRequest)req).Data); + } + #endregion + + #region GetPubDate + private const string SERVICE_GET_PUBLICATION_DATE_URL = "/url/URLGetPubDate"; + private const string SERVICE_GET_PUBLICATION_DATE_HTML = "/html/HTMLGetPubDate"; + + /// + /// On get publication date delegate. + /// + public delegate void OnGetPublicationDate(PubDateData pubDateData, string data); + + /// + /// Extracts the publication date from a source. + /// + /// true, if publication date was gotten, false otherwise. + /// Callback. + /// URL or HTML sources. + /// Custom data. + public bool GetPublicationDate(OnGetPublicationDate callback, string source, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a url for GetPublicationDate."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetPublicationDateRequest req = new GetPublicationDateRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service = ""; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_PUBLICATION_DATE_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetPublicationDate Callback { get; set; } + service = SERVICE_GET_PUBLICATION_DATE_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetPubicationDate!"); + } + else + { + Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetPublicationDate!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetPublicationDateResponse; + return connector.Send(req); + } - private void OnGetPublicationDateResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Get publication date request. + /// + public class GetPublicationDateRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetPublicationDate Callback { get; set; } + } + + private void OnGetPublicationDateResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + PubDateData pubDateData = new PubDateData(); + if (resp.Success) + { + try { - PubDateData pubDateData = new PubDateData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = pubDateData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetPublicationDateResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetPublicationDateRequest)req).Callback != null) - ((GetPublicationDateRequest)req).Callback(resp.Success ? pubDateData : null, ((GetPublicationDateRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = pubDateData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetRelations - private const string SERVICE_GET_RELATIONS_HTML = "/html/HTMLGetRelations"; - private const string SERVICE_GET_RELATIONS_URL = "/url/URLGetRelations"; - private const string SERVICE_GET_RELATIONS_TEXT = "/text/TextGetRelations"; - - /// - /// On get relations delegate. - /// - public delegate void OnGetRelations(RelationsData relationData, string data); - - /// - /// Extracts the relations from a source. - /// - /// true, if relations was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// Max retrieve. - /// If set to true include keywords. - /// If set to true include entities. - /// If set to true require entities. - /// If set to true resolve coreferences. - /// If set to true disambiguate entities. - /// If set to true include knowledge graph. - /// If set to true include linked data. - /// If set to true analyze sentiment. - /// If set to true exclude entities in sentiment. - /// If set to true include source text. - /// Custom data. - public bool GetRelations(OnGetRelations callback, string source, - int maxRetrieve = 50, - bool includeKeywords = false, - bool includeEntities = false, - bool requireEntities = false, - bool resolveCoreferences = true, - bool disambiguateEntities = true, - bool includeKnowledgeGraph = false, - bool includeLinkedData = true, - bool analyzeSentiment = false, - bool excludeEntitiesInSentiment = false, - bool includeSourceText = false, - string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetRelations."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetRelationsRequest req = new GetRelationsRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["maxRetrieve"] = Convert.ToInt32(maxRetrieve).ToString(); - req.Parameters["keywords"] = Convert.ToInt32(includeKeywords).ToString(); - req.Parameters["entities"] = Convert.ToInt32(includeEntities).ToString(); - req.Parameters["requireEntities"] = Convert.ToInt32(requireEntities).ToString(); - req.Parameters["coreference"] = Convert.ToInt32(resolveCoreferences).ToString(); - req.Parameters["disambiguate"] = Convert.ToInt32(disambiguateEntities).ToString(); - req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); - req.Parameters["linkedData"] = Convert.ToInt32(includeLinkedData).ToString(); - req.Parameters["sentiment"] = Convert.ToInt32(analyzeSentiment).ToString(); - req.Parameters["sentimentExcludeEntities"] = Convert.ToInt32(excludeEntitiesInSentiment).ToString(); - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - req.Parameters["keywordExtractMode"] = "strict"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_RELATIONS_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_RELATIONS_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetRelations!"); - } - else - { - service = SERVICE_GET_RELATIONS_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetRelationsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetPublicationDateResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get relations request. - /// - public class GetRelationsRequest : RESTConnector.Request + if (((GetPublicationDateRequest)req).Callback != null) + ((GetPublicationDateRequest)req).Callback(resp.Success ? pubDateData : null, ((GetPublicationDateRequest)req).Data); + } + #endregion + + #region GetRelations + private const string SERVICE_GET_RELATIONS_HTML = "/html/HTMLGetRelations"; + private const string SERVICE_GET_RELATIONS_URL = "/url/URLGetRelations"; + private const string SERVICE_GET_RELATIONS_TEXT = "/text/TextGetRelations"; + + /// + /// On get relations delegate. + /// + public delegate void OnGetRelations(RelationsData relationData, string data); + + /// + /// Extracts the relations from a source. + /// + /// true, if relations was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// Max retrieve. + /// If set to true include keywords. + /// If set to true include entities. + /// If set to true require entities. + /// If set to true resolve coreferences. + /// If set to true disambiguate entities. + /// If set to true include knowledge graph. + /// If set to true include linked data. + /// If set to true analyze sentiment. + /// If set to true exclude entities in sentiment. + /// If set to true include source text. + /// Custom data. + public bool GetRelations(OnGetRelations callback, string source, + int maxRetrieve = 50, + bool includeKeywords = false, + bool includeEntities = false, + bool requireEntities = false, + bool resolveCoreferences = true, + bool disambiguateEntities = true, + bool includeKnowledgeGraph = false, + bool includeLinkedData = true, + bool analyzeSentiment = false, + bool excludeEntitiesInSentiment = false, + bool includeSourceText = false, + string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetRelations."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetRelationsRequest req = new GetRelationsRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["maxRetrieve"] = Convert.ToInt32(maxRetrieve).ToString(); + req.Parameters["keywords"] = Convert.ToInt32(includeKeywords).ToString(); + req.Parameters["entities"] = Convert.ToInt32(includeEntities).ToString(); + req.Parameters["requireEntities"] = Convert.ToInt32(requireEntities).ToString(); + req.Parameters["coreference"] = Convert.ToInt32(resolveCoreferences).ToString(); + req.Parameters["disambiguate"] = Convert.ToInt32(disambiguateEntities).ToString(); + req.Parameters["knowledgeGraph"] = Convert.ToInt32(includeKnowledgeGraph).ToString(); + req.Parameters["linkedData"] = Convert.ToInt32(includeLinkedData).ToString(); + req.Parameters["sentiment"] = Convert.ToInt32(analyzeSentiment).ToString(); + req.Parameters["sentimentExcludeEntities"] = Convert.ToInt32(excludeEntitiesInSentiment).ToString(); + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + req.Parameters["keywordExtractMode"] = "strict"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_RELATIONS_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetRelations Callback { get; set; } + service = SERVICE_GET_RELATIONS_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetRelations!"); + } + else + { + service = SERVICE_GET_RELATIONS_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetRelationsResponse; + return connector.Send(req); + } + + /// + /// Get relations request. + /// + public class GetRelationsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetRelations Callback { get; set; } + } - private void OnGetRelationsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetRelationsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + RelationsData relationsData = new RelationsData(); + if (resp.Success) + { + try { - RelationsData relationsData = new RelationsData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = relationsData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetRelationsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetRelationsRequest)req).Callback != null) - ((GetRelationsRequest)req).Callback(resp.Success ? relationsData : null, ((GetRelationsRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = relationsData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetTextSentiment - private const string SERVICE_GET_TEXT_SENTIMENT_HTML = "/html/HTMLGetTextSentiment"; - private const string SERVICE_GET_TEXT_SENTIMENT_URL = "/url/URLGetTextSentiment"; - private const string SERVICE_GET_TEXT_SENTIMENT_TEXT = "/text/TextGetTextSentiment"; - - /// - /// On get text sentiment delegate. - /// - public delegate void OnGetTextSentiment(SentimentData sentimentData, string data); - - /// - /// Extracts the sentiment from a source. - /// - /// true, if text sentiment was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// If set to true include source text. - /// Custom data. - public bool GetTextSentiment(OnGetTextSentiment callback, string source, bool includeSourceText = false, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetTextSentiment."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetTextSentimentRequest req = new GetTextSentimentRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_TEXT_SENTIMENT_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_TEXT_SENTIMENT_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetTextSentiment!"); - } - else - { - service = SERVICE_GET_TEXT_SENTIMENT_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetTextSentimentResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetRelationsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get text sentiment request. - /// - public class GetTextSentimentRequest : RESTConnector.Request + if (((GetRelationsRequest)req).Callback != null) + ((GetRelationsRequest)req).Callback(resp.Success ? relationsData : null, ((GetRelationsRequest)req).Data); + } + #endregion + + #region GetTextSentiment + private const string SERVICE_GET_TEXT_SENTIMENT_HTML = "/html/HTMLGetTextSentiment"; + private const string SERVICE_GET_TEXT_SENTIMENT_URL = "/url/URLGetTextSentiment"; + private const string SERVICE_GET_TEXT_SENTIMENT_TEXT = "/text/TextGetTextSentiment"; + + /// + /// On get text sentiment delegate. + /// + public delegate void OnGetTextSentiment(SentimentData sentimentData, string data); + + /// + /// Extracts the sentiment from a source. + /// + /// true, if text sentiment was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// If set to true include source text. + /// Custom data. + public bool GetTextSentiment(OnGetTextSentiment callback, string source, bool includeSourceText = false, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetTextSentiment."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetTextSentimentRequest req = new GetTextSentimentRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_TEXT_SENTIMENT_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetTextSentiment Callback { get; set; } + service = SERVICE_GET_TEXT_SENTIMENT_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetTextSentiment!"); + } + else + { + service = SERVICE_GET_TEXT_SENTIMENT_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetTextSentimentResponse; + return connector.Send(req); + } + + /// + /// Get text sentiment request. + /// + public class GetTextSentimentRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetTextSentiment Callback { get; set; } + } - private void OnGetTextSentimentResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetTextSentimentResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + SentimentData sentimentData = new SentimentData(); + if (resp.Success) + { + try { - SentimentData sentimentData = new SentimentData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = sentimentData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetTextSentimentResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetTextSentimentRequest)req).Callback != null) - ((GetTextSentimentRequest)req).Callback(resp.Success ? sentimentData : null, ((GetTextSentimentRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = sentimentData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetTargetedSentiment - private const string SERVICE_GET_TARGETED_SENTIMENT_HTML = "/html/HTMLGetTargetedSentiment"; - private const string SERVICE_GET_TARGETED_SENTIMENT_URL = "/url/URLGetTargetedSentiment"; - private const string SERVICE_GET_TARGETED_SENTIMENT_TEXT = "/text/TextGetTargetedSentiment"; - - /// - /// On get targeted sentiment delegate. - /// - public delegate void OnGetTargetedSentiment(TargetedSentimentData targetedSentimentData, string data); - - /// - /// Extracts targeted sentiment from a source. - /// - /// true, if targeted sentiment was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// Targets. - /// If set to true include source text. - /// Custom data. - public bool GetTargetedSentiment(OnGetTargetedSentiment callback, string source, string targets, bool includeSourceText = false, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetTargetedSentiment."); - if (string.IsNullOrEmpty(targets)) - throw new WatsonException("Please provide a target for GetTargetedSentiment."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetTargetedSentimentRequest req = new GetTargetedSentimentRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - req.Forms["targets"] = new RESTConnector.Form(targets); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_TARGETED_SENTIMENT_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_TARGETED_SENTIMENT_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetTargetedSentiment!"); - } - else - { - service = SERVICE_GET_TARGETED_SENTIMENT_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetTargetedSentimentResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetTextSentimentResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get targeted sentiment request. - /// - public class GetTargetedSentimentRequest : RESTConnector.Request + if (((GetTextSentimentRequest)req).Callback != null) + ((GetTextSentimentRequest)req).Callback(resp.Success ? sentimentData : null, ((GetTextSentimentRequest)req).Data); + } + #endregion + + #region GetTargetedSentiment + private const string SERVICE_GET_TARGETED_SENTIMENT_HTML = "/html/HTMLGetTargetedSentiment"; + private const string SERVICE_GET_TARGETED_SENTIMENT_URL = "/url/URLGetTargetedSentiment"; + private const string SERVICE_GET_TARGETED_SENTIMENT_TEXT = "/text/TextGetTargetedSentiment"; + + /// + /// On get targeted sentiment delegate. + /// + public delegate void OnGetTargetedSentiment(TargetedSentimentData targetedSentimentData, string data); + + /// + /// Extracts targeted sentiment from a source. + /// + /// true, if targeted sentiment was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// Targets. + /// If set to true include source text. + /// Custom data. + public bool GetTargetedSentiment(OnGetTargetedSentiment callback, string source, string targets, bool includeSourceText = false, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetTargetedSentiment."); + if (string.IsNullOrEmpty(targets)) + throw new WatsonException("Please provide a target for GetTargetedSentiment."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetTargetedSentimentRequest req = new GetTargetedSentimentRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + req.Forms["targets"] = new RESTConnector.Form(targets); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_TARGETED_SENTIMENT_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetTargetedSentiment Callback { get; set; } + service = SERVICE_GET_TARGETED_SENTIMENT_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetTargetedSentiment!"); + } + else + { + service = SERVICE_GET_TARGETED_SENTIMENT_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetTargetedSentimentResponse; + return connector.Send(req); + } - private void OnGetTargetedSentimentResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Get targeted sentiment request. + /// + public class GetTargetedSentimentRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetTargetedSentiment Callback { get; set; } + } + + private void OnGetTargetedSentimentResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TargetedSentimentData sentimentData = new TargetedSentimentData(); + if (resp.Success) + { + try { - TargetedSentimentData sentimentData = new TargetedSentimentData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = sentimentData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetTargetedSentimentResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetTargetedSentimentRequest)req).Callback != null) - ((GetTargetedSentimentRequest)req).Callback(resp.Success ? sentimentData : null, ((GetTargetedSentimentRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = sentimentData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetRankedTaxonomy - private const string SERVICE_GET_RANKED_TAXONOMY_HTML = "/html/HTMLGetRankedTaxonomy"; - private const string SERVICE_GET_RANKED_TAXONOMY_URL = "/url/URLGetRankedTaxonomy"; - private const string SERVICE_GET_RANKED_TAXONOMY_TEXT = "/text/TextGetRankedTaxonomy"; - - /// - /// On get ranked taxonomy delegate. - /// - public delegate void OnGetRankedTaxonomy(TaxonomyData taxonomyData, string data); - - /// - /// Extracts the ranked taxonomy from a source. - /// - /// true, if ranked taxonomy was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// If set to true include source text. - /// Custom data. - public bool GetRankedTaxonomy(OnGetRankedTaxonomy callback, string source, bool includeSourceText = false, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetRankedTaxonomy."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetRankedTaxomomyRequest req = new GetRankedTaxomomyRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_RANKED_TAXONOMY_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_RANKED_TAXONOMY_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetRankedTaxonomy!"); - } - else - { - service = SERVICE_GET_RANKED_TAXONOMY_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetRankedTaxonomyResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetTargetedSentimentResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get ranked taxomomy request. - /// - public class GetRankedTaxomomyRequest : RESTConnector.Request + if (((GetTargetedSentimentRequest)req).Callback != null) + ((GetTargetedSentimentRequest)req).Callback(resp.Success ? sentimentData : null, ((GetTargetedSentimentRequest)req).Data); + } + #endregion + + #region GetRankedTaxonomy + private const string SERVICE_GET_RANKED_TAXONOMY_HTML = "/html/HTMLGetRankedTaxonomy"; + private const string SERVICE_GET_RANKED_TAXONOMY_URL = "/url/URLGetRankedTaxonomy"; + private const string SERVICE_GET_RANKED_TAXONOMY_TEXT = "/text/TextGetRankedTaxonomy"; + + /// + /// On get ranked taxonomy delegate. + /// + public delegate void OnGetRankedTaxonomy(TaxonomyData taxonomyData, string data); + + /// + /// Extracts the ranked taxonomy from a source. + /// + /// true, if ranked taxonomy was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// If set to true include source text. + /// Custom data. + public bool GetRankedTaxonomy(OnGetRankedTaxonomy callback, string source, bool includeSourceText = false, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetRankedTaxonomy."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetRankedTaxomomyRequest req = new GetRankedTaxomomyRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_RANKED_TAXONOMY_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetRankedTaxonomy Callback { get; set; } + service = SERVICE_GET_RANKED_TAXONOMY_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetRankedTaxonomy!"); + } + else + { + service = SERVICE_GET_RANKED_TAXONOMY_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetRankedTaxonomyResponse; + return connector.Send(req); + } + + /// + /// Get ranked taxomomy request. + /// + public class GetRankedTaxomomyRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetRankedTaxonomy Callback { get; set; } + } - private void OnGetRankedTaxonomyResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetRankedTaxonomyResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TaxonomyData taxonomyData = new TaxonomyData(); + if (resp.Success) + { + try { - TaxonomyData taxonomyData = new TaxonomyData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = taxonomyData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetRankedTaxonomyResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetRankedTaxomomyRequest)req).Callback != null) - ((GetRankedTaxomomyRequest)req).Callback(resp.Success ? taxonomyData : null, ((GetRankedTaxomomyRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = taxonomyData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetText - private const string SERVICE_GET_TEXT_HTML = "/html/HTMLGetText"; - private const string SERVICE_GET_TEXT_URL = "/url/URLGetText"; - - /// - /// On get text delegate. - /// - public delegate void OnGetText(TextData textData, string data); - - /// - /// Extracts text from a source. - /// - /// true, if text was gotten, false otherwise. - /// Callback. - /// HTML or URL source. - /// If set to true extract links. - /// If set to true use metadata. - /// Custom data. - public bool GetText(OnGetText callback, string source, bool extractLinks = false, bool useMetadata = true, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetText."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetTextRequest req = new GetTextRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["extractLinks"] = Convert.ToInt32(extractLinks).ToString(); - req.Parameters["useMetadata"] = Convert.ToInt32(useMetadata).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service = ""; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_TEXT_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_TEXT_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetText!"); - } - else - { - Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetText!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetTextResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetRankedTaxonomyResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get text request. - /// - public class GetTextRequest : RESTConnector.Request + if (((GetRankedTaxomomyRequest)req).Callback != null) + ((GetRankedTaxomomyRequest)req).Callback(resp.Success ? taxonomyData : null, ((GetRankedTaxomomyRequest)req).Data); + } + #endregion + + #region GetText + private const string SERVICE_GET_TEXT_HTML = "/html/HTMLGetText"; + private const string SERVICE_GET_TEXT_URL = "/url/URLGetText"; + + /// + /// On get text delegate. + /// + public delegate void OnGetText(TextData textData, string data); + + /// + /// Extracts text from a source. + /// + /// true, if text was gotten, false otherwise. + /// Callback. + /// HTML or URL source. + /// If set to true extract links. + /// If set to true use metadata. + /// Custom data. + public bool GetText(OnGetText callback, string source, bool extractLinks = false, bool useMetadata = true, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetText."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetTextRequest req = new GetTextRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["extractLinks"] = Convert.ToInt32(extractLinks).ToString(); + req.Parameters["useMetadata"] = Convert.ToInt32(useMetadata).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service = ""; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_TEXT_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetText Callback { get; set; } + service = SERVICE_GET_TEXT_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetText!"); + } + else + { + Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetText!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetTextResponse; + return connector.Send(req); + } - private void OnGetTextResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Get text request. + /// + public class GetTextRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetText Callback { get; set; } + } + + private void OnGetTextResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TextData textData = new TextData(); + if (resp.Success) + { + try { - TextData textData = new TextData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = textData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetTextResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetTextRequest)req).Callback != null) - ((GetTextRequest)req).Callback(resp.Success ? textData : null, ((GetTextRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = textData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetRawText - private const string SERVICE_GET_RAW_TEXT_HTML = "/html/HTMLGetRawText"; - private const string SERVICE_GET_RAW_TEXT_URL = "/url/URLGetRawText"; - - /// - /// Gets raw text from a source. - /// - /// true, if raw text was gotten, false otherwise. - /// Callback. - /// HTML or URL source. - /// Custom data. - public bool GetRawText(OnGetText callback, string source, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetRawText."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetTextRequest req = new GetTextRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service = ""; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_TEXT_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_TEXT_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetRawText!"); - } - else - { - Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetRawText!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetTextResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetTextResponse Exception: {0}", e.ToString()); + resp.Success = false; } - #endregion - - #region GetTitle - private const string SERVICE_GET_TITLE_HTML = "/html/HTMLGetTitle"; - private const string SERVICE_GET_TITLE_URL = "/url/URLGetTitle"; - - /// - /// On get title delegate. - /// - public delegate void OnGetTitle(Title titleData, string data); - - /// - /// Extracts the title from a source. - /// - /// true, if title was gotten, false otherwise. - /// Callback. - /// HTML or URL source. - /// If set to true use metadata. - /// Custom data. - public bool GetTitle(OnGetTitle callback, string source, bool useMetadata = true, string customData = default(string)) + } + + if (((GetTextRequest)req).Callback != null) + ((GetTextRequest)req).Callback(resp.Success ? textData : null, ((GetTextRequest)req).Data); + } + #endregion + + #region GetRawText + private const string SERVICE_GET_RAW_TEXT_HTML = "/html/HTMLGetRawText"; + private const string SERVICE_GET_RAW_TEXT_URL = "/url/URLGetRawText"; + + /// + /// Gets raw text from a source. + /// + /// true, if raw text was gotten, false otherwise. + /// Callback. + /// HTML or URL source. + /// Custom data. + public bool GetRawText(OnGetText callback, string source, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetRawText."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetTextRequest req = new GetTextRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service = ""; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_TEXT_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetText."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetTitleRequest req = new GetTitleRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["useMetadata"] = Convert.ToInt32(useMetadata).ToString(); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service = ""; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_GET_TITLE_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_GET_TITLE_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetTitle!"); - } - else - { - Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetTitle!"); - return false; - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnGetTitleResponse; - return connector.Send(req); + service = SERVICE_GET_TEXT_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } - - /// - /// Get title request. - /// - public class GetTitleRequest : RESTConnector.Request + else + throw new WatsonException("An HTML source is needed for GetRawText!"); + } + else + { + Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetRawText!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetTextResponse; + return connector.Send(req); + } + #endregion + + #region GetTitle + private const string SERVICE_GET_TITLE_HTML = "/html/HTMLGetTitle"; + private const string SERVICE_GET_TITLE_URL = "/url/URLGetTitle"; + + /// + /// On get title delegate. + /// + public delegate void OnGetTitle(Title titleData, string data); + + /// + /// Extracts the title from a source. + /// + /// true, if title was gotten, false otherwise. + /// Callback. + /// HTML or URL source. + /// If set to true use metadata. + /// Custom data. + public bool GetTitle(OnGetTitle callback, string source, bool useMetadata = true, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetText."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetTitleRequest req = new GetTitleRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["useMetadata"] = Convert.ToInt32(useMetadata).ToString(); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service = ""; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_GET_TITLE_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetTitle Callback { get; set; } + service = SERVICE_GET_TITLE_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetTitle!"); + } + else + { + Log.Error("Alchemy Language", "Either a URL or a html page source is required for GetTitle!"); + return false; + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnGetTitleResponse; + return connector.Send(req); + } - private void OnGetTitleResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// Get title request. + /// + public class GetTitleRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetTitle Callback { get; set; } + } + + private void OnGetTitleResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Title titleData = new Title(); + if (resp.Success) + { + try { - Title titleData = new Title(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = titleData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnGetTitleResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetTitleRequest)req).Callback != null) - ((GetTitleRequest)req).Callback(resp.Success ? titleData : null, ((GetTitleRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = titleData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Combined Call - private const string SERVICE_COMBINED_CALL_HTML = "/html/HTMLGetCombinedData"; - private const string SERVICE_COMBINED_CALL_URL = "/url/URLGetCombinedData"; - private const string SERVICE_COMBINED_CALL_TEXT = "/text/TextGetCombinedData"; - - /// - /// On get combined data delegate. - /// - public delegate void OnGetCombinedData(CombinedCallData combinedData, string data); - - /// - /// Access multiple services in one call. - /// - /// true, if combined data was gotten, false otherwise. - /// Callback. - /// HTML, URL or Text source. - /// If set to true include source text. - /// If set to true extract authors. - /// If set to true extract concepts. - /// If set to true extract dates. - /// If set to true extract document emotion. - /// If set to true extract entities. - /// If set to true extract feeds. - /// If set to true extract keywords. - /// If set to true extract pub date. - /// If set to true extract relations. - /// If set to true extract document sentiment. - /// If set to true extract taxonomy. - /// If set to true extract title. - /// If set to true extract page image. - /// If set to true extract image keywords. - /// Custom data. - public bool GetCombinedData(OnGetCombinedData callback, string source, - bool includeSourceText = false, - bool extractAuthors = false, - bool extractConcepts = true, - bool extractDates = false, - bool extractDocEmotion = false, - bool extractEntities = true, - bool extractFeeds = false, - bool extractKeywords = true, - bool extractPubDate = false, - bool extractRelations = false, - bool extractDocSentiment = false, - bool extractTaxonomy = true, - bool extractTitle = false, - bool extractPageImage = false, - bool extractImageKeywords = false, - string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(source)) - throw new WatsonException("Please provide a source for GetCombinedData."); - if (!extractAuthors - && !extractConcepts - && !extractDates - && !extractDocEmotion - && !extractEntities - && !extractFeeds - && !extractKeywords - && !extractPubDate - && !extractRelations - && !extractDocSentiment - && !extractTaxonomy - && !extractTitle - && !extractPageImage - && !extractImageKeywords) - throw new WatsonException("GetCombinedCall - Please include one or more services."); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - CombinedCallRequest req = new CombinedCallRequest(); - req.Callback = callback; - req.Data = string.IsNullOrEmpty(customData) ? source : customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); - - List requestServices = new List(); - if (extractAuthors) - requestServices.Add("authors"); - if (extractConcepts) - requestServices.Add("concepts"); - if (extractDates) - requestServices.Add("dates"); - if (extractDocEmotion) - requestServices.Add("doc-emotion"); - if (extractEntities) - requestServices.Add("entities"); - if (extractFeeds) - requestServices.Add("feeds"); - if (extractKeywords) - requestServices.Add("keywords"); - if (extractPubDate) - requestServices.Add("pub-date"); - if (extractRelations) - requestServices.Add("relations"); - if (extractDocSentiment) - requestServices.Add("doc-sentiment"); - if (extractTaxonomy) - requestServices.Add("taxonomy"); - if (extractTitle) - requestServices.Add("title"); - if (extractPageImage) - requestServices.Add("page-image"); - if (extractImageKeywords) - requestServices.Add("image-kw"); - req.Parameters["extract"] = string.Join(",", requestServices.ToArray()); - - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Forms = new Dictionary(); - - string service; - string normalizedSource = source.Trim().ToLower(); - if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) - { - service = SERVICE_COMBINED_CALL_URL; - req.Forms["url"] = new RESTConnector.Form(source); - } - else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) - { - if (Path.GetExtension(normalizedSource).EndsWith(".html")) - { - service = SERVICE_COMBINED_CALL_HTML; - string htmlData = default(string); - htmlData = File.ReadAllText(source); - req.Forms["html"] = new RESTConnector.Form(htmlData); - } - else - throw new WatsonException("An HTML source is needed for GetCombinedData!"); - } - else - { - service = SERVICE_COMBINED_CALL_TEXT; - req.Forms["text"] = new RESTConnector.Form(source); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - req.OnResponse = OnCombinedCallResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnGetTitleResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Combined call request. - /// - public class CombinedCallRequest : RESTConnector.Request + if (((GetTitleRequest)req).Callback != null) + ((GetTitleRequest)req).Callback(resp.Success ? titleData : null, ((GetTitleRequest)req).Data); + } + #endregion + + #region Combined Call + private const string SERVICE_COMBINED_CALL_HTML = "/html/HTMLGetCombinedData"; + private const string SERVICE_COMBINED_CALL_URL = "/url/URLGetCombinedData"; + private const string SERVICE_COMBINED_CALL_TEXT = "/text/TextGetCombinedData"; + + /// + /// On get combined data delegate. + /// + public delegate void OnGetCombinedData(CombinedCallData combinedData, string data); + + /// + /// Access multiple services in one call. + /// + /// true, if combined data was gotten, false otherwise. + /// Callback. + /// HTML, URL or Text source. + /// If set to true include source text. + /// If set to true extract authors. + /// If set to true extract concepts. + /// If set to true extract dates. + /// If set to true extract document emotion. + /// If set to true extract entities. + /// If set to true extract feeds. + /// If set to true extract keywords. + /// If set to true extract pub date. + /// If set to true extract relations. + /// If set to true extract document sentiment. + /// If set to true extract taxonomy. + /// If set to true extract title. + /// If set to true extract page image. + /// If set to true extract image keywords. + /// Custom data. + public bool GetCombinedData(OnGetCombinedData callback, string source, + bool includeSourceText = false, + bool extractAuthors = false, + bool extractConcepts = true, + bool extractDates = false, + bool extractDocEmotion = false, + bool extractEntities = true, + bool extractFeeds = false, + bool extractKeywords = true, + bool extractPubDate = false, + bool extractRelations = false, + bool extractDocSentiment = false, + bool extractTaxonomy = true, + bool extractTitle = false, + bool extractPageImage = false, + bool extractImageKeywords = false, + string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new WatsonException("Please provide a source for GetCombinedData."); + if (!extractAuthors + && !extractConcepts + && !extractDates + && !extractDocEmotion + && !extractEntities + && !extractFeeds + && !extractKeywords + && !extractPubDate + && !extractRelations + && !extractDocSentiment + && !extractTaxonomy + && !extractTitle + && !extractPageImage + && !extractImageKeywords) + throw new WatsonException("GetCombinedCall - Please include one or more services."); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + CombinedCallRequest req = new CombinedCallRequest(); + req.Callback = callback; + req.Data = string.IsNullOrEmpty(customData) ? source : customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["showSourceText"] = Convert.ToInt32(includeSourceText).ToString(); + + List requestServices = new List(); + if (extractAuthors) + requestServices.Add("authors"); + if (extractConcepts) + requestServices.Add("concepts"); + if (extractDates) + requestServices.Add("dates"); + if (extractDocEmotion) + requestServices.Add("doc-emotion"); + if (extractEntities) + requestServices.Add("entities"); + if (extractFeeds) + requestServices.Add("feeds"); + if (extractKeywords) + requestServices.Add("keywords"); + if (extractPubDate) + requestServices.Add("pub-date"); + if (extractRelations) + requestServices.Add("relations"); + if (extractDocSentiment) + requestServices.Add("doc-sentiment"); + if (extractTaxonomy) + requestServices.Add("taxonomy"); + if (extractTitle) + requestServices.Add("title"); + if (extractPageImage) + requestServices.Add("page-image"); + if (extractImageKeywords) + requestServices.Add("image-kw"); + req.Parameters["extract"] = string.Join(",", requestServices.ToArray()); + + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Forms = new Dictionary(); + + string service; + string normalizedSource = source.Trim().ToLower(); + if (normalizedSource.StartsWith("http://") || normalizedSource.StartsWith("https://")) + { + service = SERVICE_COMBINED_CALL_URL; + req.Forms["url"] = new RESTConnector.Form(source); + } + else if (source.StartsWith(Application.dataPath) && !normalizedSource.StartsWith("http://") && !normalizedSource.StartsWith("https://")) + { + if (Path.GetExtension(normalizedSource).EndsWith(".html")) { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetCombinedData Callback { get; set; } + service = SERVICE_COMBINED_CALL_HTML; + string htmlData = default(string); + htmlData = File.ReadAllText(source); + req.Forms["html"] = new RESTConnector.Form(htmlData); } + else + throw new WatsonException("An HTML source is needed for GetCombinedData!"); + } + else + { + service = SERVICE_COMBINED_CALL_TEXT; + req.Forms["text"] = new RESTConnector.Form(source); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + req.OnResponse = OnCombinedCallResponse; + return connector.Send(req); + } + + /// + /// Combined call request. + /// + public class CombinedCallRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetCombinedData Callback { get; set; } + } - private void OnCombinedCallResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnCombinedCallResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + CombinedCallData combinedData = new CombinedCallData(); + if (resp.Success) + { + try { - CombinedCallData combinedData = new CombinedCallData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = combinedData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyLanguage", "OnCombinedCallResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((CombinedCallRequest)req).Callback != null) - ((CombinedCallRequest)req).Callback(resp.Success ? combinedData : null, ((CombinedCallRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = combinedData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetNews - private const string SERVICE_GET_NEWS = "/data/GetNews"; - - /// - /// On get news delegate. - /// - public delegate void OnGetNews(NewsResponse newsData, string data); - - /// - /// Gets news. - /// - /// true, if news was gotten, false otherwise. - /// Callback. - /// Fields returned. - /// Values for each field. - /// Date to start the query. - /// Date to end the query. - /// Maximum number of results. - /// the duration (in seconds) of each time slice. a human readable duration is also acceptable e.g. '1d', '4h', '1M', etc. - /// If set, this parameter causes the query engine to return a time series representing the count in each slice of time. If omitted, the query engine returns the total count over the time duration. - /// Custom data. - public bool GetNews(OnGetNews callback, - string[] returnFields = default(string[]), - Dictionary queryFields = null, - string startDate = "now-1d", - string endDate = "now", - int maxResults = 10, - string timeSlice = default(string), - string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(mp_ApiKey)) - SetCredentials(); - - GetNewsRequest req = new GetNewsRequest(); - req.Callback = callback; - req.Data = customData; - - req.Parameters["apikey"] = mp_ApiKey; - req.Parameters["outputMode"] = "json"; - req.Parameters["start"] = startDate; - req.Parameters["end"] = endDate; - req.Parameters["maxResults"] = maxResults; - if (timeSlice != default(string)) - req.Parameters["timeSlice"] = timeSlice; - if (returnFields != default(string[])) - req.Parameters["return"] = string.Join(",", returnFields); - if (queryFields != null) - foreach (KeyValuePair entry in queryFields) - req.Parameters[entry.Key] = "q." + entry.Value; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_NEWS); - if (connector == null) - return false; - - req.OnResponse = OnGetNewsResponse; - return connector.Send(req); + Log.Error("AlchemyLanguage", "OnCombinedCallResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get News request. - /// - public class GetNewsRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetNews Callback { get; set; } - } + if (((CombinedCallRequest)req).Callback != null) + ((CombinedCallRequest)req).Callback(resp.Success ? combinedData : null, ((CombinedCallRequest)req).Data); + } + #endregion + + #region GetNews + private const string SERVICE_GET_NEWS = "/data/GetNews"; + + /// + /// On get news delegate. + /// + public delegate void OnGetNews(NewsResponse newsData, string data); + + /// + /// Gets news. + /// + /// true, if news was gotten, false otherwise. + /// Callback. + /// Fields returned. + /// Values for each field. + /// Date to start the query. + /// Date to end the query. + /// Maximum number of results. + /// the duration (in seconds) of each time slice. a human readable duration is also acceptable e.g. '1d', '4h', '1M', etc. + /// If set, this parameter causes the query engine to return a time series representing the count in each slice of time. If omitted, the query engine returns the total count over the time duration. + /// Custom data. + public bool GetNews(OnGetNews callback, + string[] returnFields = default(string[]), + Dictionary queryFields = null, + string startDate = "now-1d", + string endDate = "now", + int maxResults = 10, + string timeSlice = default(string), + string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(mp_ApiKey)) + SetCredentials(); + + GetNewsRequest req = new GetNewsRequest(); + req.Callback = callback; + req.Data = customData; + + req.Parameters["apikey"] = mp_ApiKey; + req.Parameters["outputMode"] = "json"; + req.Parameters["start"] = startDate; + req.Parameters["end"] = endDate; + req.Parameters["maxResults"] = maxResults; + if (timeSlice != default(string)) + req.Parameters["timeSlice"] = timeSlice; + if (returnFields != default(string[])) + req.Parameters["return"] = string.Join(",", returnFields); + if (queryFields != null) + foreach (KeyValuePair entry in queryFields) + req.Parameters[entry.Key] = "q." + entry.Value; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_NEWS); + if (connector == null) + return false; + + req.OnResponse = OnGetNewsResponse; + return connector.Send(req); + } - private void OnGetNewsResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - NewsResponse newsData = new NewsResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = newsData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("AlchemyDataNews", "OnGetNewsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetNewsRequest)req).Callback != null) - ((GetNewsRequest)req).Callback(resp.Success ? newsData : null, ((GetNewsRequest)req).Data); - } - #endregion + /// + /// Get News request. + /// + public class GetNewsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetNews Callback { get; set; } + } - #region IWatsonService interface - /// - public string GetServiceID() + private void OnGetNewsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + NewsResponse newsData = new NewsResponse(); + if (resp.Success) + { + try { - return SERVICE_ID; + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = newsData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - /// - public void GetServiceStatus(ServiceStatus callback) + catch (Exception e) { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); + Log.Error("AlchemyDataNews", "OnGetNewsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - private class CheckServiceStatus - { - private AlchemyAPI m_Service = null; - private ServiceStatus m_Callback = null; + if (((GetNewsRequest)req).Callback != null) + ((GetNewsRequest)req).Callback(resp.Success ? newsData : null, ((GetNewsRequest)req).Data); + } + #endregion - public CheckServiceStatus(AlchemyAPI service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - if (!m_Service.ExtractEntities(OnGetEntityExtraction, "Test")) - m_Callback(SERVICE_ID, false); - } + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } - void OnGetEntityExtraction(EntityData entityExtractionData, string data) - { - if (m_Callback != null) - m_Callback(SERVICE_ID, entityExtractionData != null); - } + private class CheckServiceStatus + { + private AlchemyAPI m_Service = null; + private ServiceStatus m_Callback = null; - }; + public CheckServiceStatus(AlchemyAPI service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; - #endregion - } + if (!m_Service.ExtractEntities(OnGetEntityExtraction, "Test")) + m_Callback(SERVICE_ID, false); + } + + void OnGetEntityExtraction(EntityData entityExtractionData, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, entityExtractionData != null); + } + + }; + + #endregion + } } diff --git a/Scripts/Services/AlchemyAPI/DataModels.cs b/Scripts/Services/AlchemyAPI/DataModels.cs index 26de84276..90b1152c8 100755 --- a/Scripts/Services/AlchemyAPI/DataModels.cs +++ b/Scripts/Services/AlchemyAPI/DataModels.cs @@ -21,2895 +21,2895 @@ namespace IBM.Watson.DeveloperCloud.Services.AlchemyAPI.v1 { - #region Combined Call - /// - /// Combined call data. - /// - [fsObject] - public class CombinedCallData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the title. - /// - /// The title. - public string title { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the image. - /// - /// The image. - public string image { get; set; } - - /// - /// Gets or sets the image keywords. - /// - /// The image keywords. - public ImageKeyword[] imageKeywords { get; set; } - - /// - /// Gets or sets the publication date. - /// - /// The publication date. - public PublicationDate publicationDate { get; set; } - - /// - /// Gets or sets the authors. - /// - /// The authors. - public Authors authors { get; set; } - - /// - /// Gets or sets the document sentiment. - /// - /// The document sentiment. - public DocSentiment docSentiment { get; set; } - - /// - /// Gets or sets the feeds. - /// - /// The feeds. - public Feed[]feeds { get; set; } - - /// - /// Gets or sets the keywords. - /// - /// The keywords. - public Keyword[] keywords { get; set; } - - /// - /// Gets or sets the concepts. - /// - /// The concepts. - public Concept[] concepts { get; set; } - - /// - /// Gets or sets the entities. - /// - /// The entities. - public Entity[] entities { get; set; } - - /// - /// Gets or sets the relations. - /// - /// The relations. - public Relation[] relations { get; set; } - - /// - /// Gets or sets the taxonomy. - /// - /// The taxonomy. - public Taxonomy[] taxonomy { get; set; } - - /// - /// Gets or sets the dates. - /// - /// The dates. - public Date[] dates { get; set; } - - /// - /// Gets or sets the document emotions. - /// - /// The document emotions. - public DocEmotions[] docEmotions { get; set; } - - /// - /// Gets a value indicating whether this instance has data. - /// - /// true if this instance has data; otherwise, false. - public bool HasData - { - get - { - return EntityCombined != null && EntityCombined.Count > 0; - } - } + #region Combined Call + /// + /// Combined call data. + /// + [fsObject] + public class CombinedCallData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } - private List _EntityCombined = null; - /// - /// The entity combined. - /// - public List EntityCombined - { - get - { - if (_EntityCombined == null) - { - _EntityCombined = new List(); - - for (int i = 0; keywords != null && i < keywords.Length; i++) - { - if (!_EntityCombined.Contains(keywords[i].text)) - _EntityCombined.Add(keywords[i].text); - } - - for (int i = 0; entities != null && i < entities.Length; i++) - { - if (!_EntityCombined.Contains(entities[i].text)) - _EntityCombined.Add(entities[i].text); - } - } + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } - return _EntityCombined; - } - } + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } - /// - /// Gets the entity combined comma seperated. - /// - /// The entity combined comma seperated. - public string EntityCombinedCommaSeperated - { - get - { - if (EntityCombined.Count > 0) - return string.Join(",", EntityCombined.ToArray()); - return ""; - } - } + /// + /// Gets or sets the title. + /// + /// The title. + public string title { get; set; } - /// - /// Tos the long string. - /// - /// The long string. - public string ToLongString() - { - StringBuilder stringBuilder = new StringBuilder(string.Format("[CombinedCallData: status={0}, language={1}, text={2}", status, language, text)); + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } - stringBuilder.Append(EntityCombinedCommaSeperated); - for (int i = 0; dates != null && i < dates.Length; i++) - { - stringBuilder.Append(" Date: " + dates[i].DateValue.ToString()); - } + /// + /// Gets or sets the image. + /// + /// The image. + public string image { get; set; } - return stringBuilder.ToString(); - } + /// + /// Gets or sets the image keywords. + /// + /// The image keywords. + public ImageKeyword[] imageKeywords { get; set; } - }; + /// + /// Gets or sets the publication date. + /// + /// The publication date. + public PublicationDate publicationDate { get; set; } /// - /// Image keyword. + /// Gets or sets the authors. /// - [fsObject] - public class ImageKeyword - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the score. - /// - /// The score. - public string score { get; set; } - } - #endregion + /// The authors. + public Authors authors { get; set; } - #region GetAuthors /// - /// Authors data. + /// Gets or sets the document sentiment. /// - [fsObject] - public class AuthorsData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the authors. - /// - /// The authors. - public Authors authors { get; set; } - } + /// The document sentiment. + public DocSentiment docSentiment { get; set; } /// - /// Authors. + /// Gets or sets the feeds. /// - [fsObject] - public class Authors - { - /// - /// Gets or sets the confident. - /// - /// The confident. - public string confident { get; set; } - - /// - /// Gets or sets the names. - /// - /// The names. - public string[] names { get; set; } - } - #endregion + /// The feeds. + public Feed[] feeds { get; set; } - #region GetRankedConcepts /// - /// Concepts data. + /// Gets or sets the keywords. /// - [fsObject] - public class ConceptsData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the concepts. - /// - /// The concepts. - public Concept[] concepts { get; set; } - } + /// The keywords. + public Keyword[] keywords { get; set; } /// - /// Concept. + /// Gets or sets the concepts. /// - [fsObject] - public class Concept - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the relevance. - /// - /// The relevance. - public string relevance { get; set; } - - /// - /// Gets or sets the knowledge graph. - /// - /// The knowledge graph. - public KnowledgeGraph knowledgeGraph { get; set; } - - /// - /// Gets or sets the website. - /// - /// The website. - public string website { get; set; } - - /// - /// Gets or sets the geo. - /// - /// The geo. - public string geo { get; set; } - - /// - /// Gets or sets the dbpedia. - /// - /// The dbpedia. - public string dbpedia { get; set; } - - /// - /// Gets or sets the freebase. - /// - /// The freebase. - public string freebase { get; set; } - - /// - /// Gets or sets the yago. - /// - /// The yago. - public string yago { get; set; } - - /// - /// Gets or sets the opencyc. - /// - /// The opencyc. - public string opencyc { get; set; } - - /// - /// Gets or sets the cia factbook. - /// - /// The cia factbook. - public string ciaFactbook { get; set; } - - /// - /// Gets or sets the census. - /// - /// The census. - public string census { get; set; } - - /// - /// Gets or sets the geonames. - /// - /// The geonames. - public string geonames { get; set; } - - /// - /// Gets or sets the music brainz. - /// - /// The music brainz. - public string musicBrainz { get; set; } - - /// - /// Gets or sets the crunchbase. - /// - /// The crunchbase. - public string crunchbase { get; set; } - }; - #endregion - - #region ExtractDates - /// - /// Date data. - /// - [fsObject] - public class DateData + /// The concepts. + public Concept[] concepts { get; set; } + + /// + /// Gets or sets the entities. + /// + /// The entities. + public Entity[] entities { get; set; } + + /// + /// Gets or sets the relations. + /// + /// The relations. + public Relation[] relations { get; set; } + + /// + /// Gets or sets the taxonomy. + /// + /// The taxonomy. + public Taxonomy[] taxonomy { get; set; } + + /// + /// Gets or sets the dates. + /// + /// The dates. + public Date[] dates { get; set; } + + /// + /// Gets or sets the document emotions. + /// + /// The document emotions. + public DocEmotions[] docEmotions { get; set; } + + /// + /// Gets a value indicating whether this instance has data. + /// + /// true if this instance has data; otherwise, false. + public bool HasData { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the dates. - /// - /// The dates. - public Date[] dates { get; set; } + get + { + return EntityCombined != null && EntityCombined.Count > 0; + } } + private List _EntityCombined = null; /// - /// Date. + /// The entity combined. /// - [fsObject] - public class Date + public List EntityCombined { - /// - /// Gets or sets the date. - /// - /// The date. - public string date { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - private System.DateTime m_dateValue = default(System.DateTime); - - /// - /// Gets the date value. - /// - /// The date value. - public System.DateTime DateValue + get + { + if (_EntityCombined == null) { - get - { - if (m_dateValue == default(System.DateTime) && !string.IsNullOrEmpty(date) && date.Length > 8) - { - //19840101T000000 - System.DateTime.TryParseExact(date.Remove(8), - "yyyyddMM", - System.Globalization.CultureInfo.InvariantCulture, - System.Globalization.DateTimeStyles.None, - out m_dateValue); - - } - return m_dateValue; - } + _EntityCombined = new List(); + + for (int i = 0; keywords != null && i < keywords.Length; i++) + { + if (!_EntityCombined.Contains(keywords[i].text)) + _EntityCombined.Add(keywords[i].text); + } + + for (int i = 0; entities != null && i < entities.Length; i++) + { + if (!_EntityCombined.Contains(entities[i].text)) + _EntityCombined.Add(entities[i].text); + } } - }; - #endregion - #region GetEmotion + return _EntityCombined; + } + } + /// - /// Emotion data. + /// Gets the entity combined comma seperated. /// - [fsObject] - public class EmotionData + /// The entity combined comma seperated. + public string EntityCombinedCommaSeperated { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the document emotions. - /// - /// The document emotions. - public DocEmotions docEmotions { get; set; } + get + { + if (EntityCombined.Count > 0) + return string.Join(",", EntityCombined.ToArray()); + return ""; + } } /// - /// Document emotions. + /// Tos the long string. /// - [fsObject] - public class DocEmotions + /// The long string. + public string ToLongString() { - /// - /// Gets or sets the anger. - /// - /// The anger. - public string anger { get; set; } - - /// - /// Gets or sets the disgust. - /// - /// The disgust. - public string disgust { get; set; } - - /// - /// Gets or sets the fear. - /// - /// The fear. - public string fear { get; set; } - - /// - /// Gets or sets the joy. - /// - /// The joy. - public string joy { get; set; } - - /// - /// Gets or sets the sadness. - /// - /// The sadness. - public string sadness { get; set; } - }; - #endregion - - #region GetRankedNamedEntities - /// - /// Entity data. - /// - [fsObject] - public class EntityData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the entities. - /// - /// The entities. - public Entity[] entities { get; set; } - - /// - /// Gets a value indicating whether this instance has data. - /// - /// true if this instance has data; otherwise, false. - public bool HasData - { - get - { - return entities != null && entities.Length > 0; - } - } + StringBuilder stringBuilder = new StringBuilder(string.Format("[CombinedCallData: status={0}, language={1}, text={2}", status, language, text)); - /// - /// Gets a value indicating whether this instance has geographic information. - /// - /// true if this instance has geographic information; otherwise, false. - public bool HasGeographicInformation - { - get - { - string geoString = null; - for (int i = 0; entities != null && i < entities.Length; i++) - { - if (entities[i].disambiguated != null) - { - geoString = entities[i].disambiguated.geo; - if (!string.IsNullOrEmpty(geoString)) - break; - } - } - return !string.IsNullOrEmpty(geoString); - } - } + stringBuilder.Append(EntityCombinedCommaSeperated); + for (int i = 0; dates != null && i < dates.Length; i++) + { + stringBuilder.Append(" Date: " + dates[i].DateValue.ToString()); + } - private PositionOnMap m_GeoLocation = null; - /// - /// Gets the geo location. - /// - /// The geo location. - public PositionOnMap GeoLocation - { - get - { - if (m_GeoLocation == null) - { - string geoString = null; - for (int i = 0; entities != null && i < entities.Length; i++) - { - if (entities[i].disambiguated != null) - { - geoString = entities[i].disambiguated.geo; - if (!string.IsNullOrEmpty(geoString)) - { - string[] geoValues = geoString.Split(' '); - if (geoValues != null && geoValues.Length == 2) - { - double latitute = 0; - double longitutde = 0; - - if (double.TryParse(geoValues[0], out latitute) && double.TryParse(geoValues[1], out longitutde)) - { - m_GeoLocation = new PositionOnMap(latitute, longitutde, entities[i].disambiguated.name); - break; - } - } - } - } - } - } - return m_GeoLocation; - } - } + return stringBuilder.ToString(); + } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - StringBuilder stringBuilder = new StringBuilder(); - for (int indexEntity = 0; entities != null && indexEntity < entities.Length; indexEntity++) - { - stringBuilder.Append("\n\t"); - stringBuilder.Append(entities[indexEntity].ToString()); - } - return string.Format("[EntityExtractionData: status={0}, language={1}, url={2}, text={3}, entities={4}]", status, language, url, text, stringBuilder.ToString()); - } + }; - }; + /// + /// Image keyword. + /// + [fsObject] + public class ImageKeyword + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } /// - /// Entity. + /// Gets or sets the score. /// - [fsObject] - public class Entity - { - /// - /// Gets or sets the type. - /// - /// The type. - public string type { get; set; } - - /// - /// Gets or sets the relevance. - /// - /// The relevance. - public string relevance { get; set; } - - /// - /// Gets or sets the knowledge graph. - /// - /// The knowledge graph. - public KnowledgeGraph knowledgeGraph { get; set; } - - /// - /// Gets or sets the count. - /// - /// The count. - public string count { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the disambiguated. - /// - /// The disambiguated. - public Disambiguated disambiguated { get; set; } - - /// - /// Gets or sets the quotations. - /// - /// The quotations. - public Quotation[] quotations { get; set; } - - /// - /// Gets or sets the sentiment. - /// - /// The sentiment. - public DocSentiment sentiment { get; set; } - - private EntityPrimaryType _EntityType = EntityPrimaryType.NONE; - /// - /// The type of the entity. - /// - public EntityPrimaryType EntityType - { - get - { - if (_EntityType == EntityPrimaryType.NONE && !string.IsNullOrEmpty(type)) - { - for (int i = (int)EntityPrimaryType.NONE; i < (int)EntityPrimaryType.NAN; i++) - { - if (string.Compare(type, ((EntityPrimaryType)i).ToString()) == 0) - { - _EntityType = ((EntityPrimaryType)i); - break; - } - } - } - return _EntityType; - } - } + /// The score. + public string score { get; set; } + } + #endregion + + #region GetAuthors + /// + /// Authors data. + /// + [fsObject] + public class AuthorsData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - StringBuilder stringBuilder = new StringBuilder(); - for (int indexQuatation = 0; quotations != null && indexQuatation < quotations.Length; indexQuatation++) - { - stringBuilder.Append("\n\t"); - stringBuilder.Append(quotations[indexQuatation].ToString()); - } + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } - return string.Format("[Entity: type={0} - EntityType={8}, relevance={1}, knowledgeGraph={2}, count={3}, text={4}, disambiguated={5}, quotations={6}, sentiment={7}]", type, relevance, knowledgeGraph, count, text, disambiguated, stringBuilder.ToString(), sentiment, EntityType); - } + /// + /// Gets or sets the authors. + /// + /// The authors. + public Authors authors { get; set; } + } + + /// + /// Authors. + /// + [fsObject] + public class Authors + { + /// + /// Gets or sets the confident. + /// + /// The confident. + public string confident { get; set; } - /// - /// Gets a value indicating whether this instance has geographic information. - /// - /// true if this instance has geographic information; otherwise, false. - public bool HasGeographicInformation - { - get - { - string geoString = null; - if (disambiguated != null) - { - geoString = disambiguated.geo; - } - return !string.IsNullOrEmpty(geoString); - } - } + /// + /// Gets or sets the names. + /// + /// The names. + public string[] names { get; set; } + } + #endregion + + #region GetRankedConcepts + /// + /// Concepts data. + /// + [fsObject] + public class ConceptsData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } - private PositionOnMap _GeoLocation = null; - /// - /// Gets the geo location. - /// - /// The geo location. - public PositionOnMap GeoLocation - { - get - { - if (_GeoLocation == null) - { - string geoString = null; - if (disambiguated != null) - { - geoString = disambiguated.geo; - if (!string.IsNullOrEmpty(geoString)) - { - string[] geoValues = geoString.Split(' '); - if (geoValues != null && geoValues.Length == 2) - { - double latitute = 0; - double longitutde = 0; - - if (double.TryParse(geoValues[0], out latitute) && double.TryParse(geoValues[1], out longitutde)) - { - _GeoLocation = new PositionOnMap(latitute, longitutde, disambiguated.name); - } - } - } - } - } - return _GeoLocation; - } - } - }; + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } /// - /// Position on map. + /// Gets or sets the language. /// - public class PositionOnMap - { - /// - /// The name of the position. - /// - public string PositionName; - - /// - /// The latitude. - /// - public double Latitude; //Y : North - south - - /// - /// The longitude. - /// - public double Longitude; //X : West - East - - /// - /// Gets the x. - /// - /// The x. - public double X { get { return Longitude; } } - - /// - /// Gets the y. - /// - /// The y. - public double Y { get { return Latitude; } } - - /// - /// Initializes a new instance of the - /// class. - /// - /// Latitude. - /// Longitude. - public PositionOnMap(double latitude, double longitude) - { - this.Latitude = latitude; - this.Longitude = longitude; - } + /// The language. + public string language { get; set; } - /// - /// Initializes a new instance of the - /// class. - /// - /// Latitude. - /// Longitude. - /// Position name. - public PositionOnMap(double latitude, double longitude, string positionName) - { - this.Latitude = latitude; - this.Longitude = longitude; - this.PositionName = positionName; - } + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - return string.Format("[PositionOnMap: Name: {0}, Latitude:{1}, Longitude:{2}]", PositionName, Latitude.ToString(), Longitude.ToString()); - } - } - #endregion + /// + /// Gets or sets the concepts. + /// + /// The concepts. + public Concept[] concepts { get; set; } + } + + /// + /// Concept. + /// + [fsObject] + public class Concept + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } - #region EntityTypes /// - /// Entity primary type. + /// Gets or sets the relevance. /// - public enum EntityPrimaryType - { - NONE = -1, - Anatomy, - Anniversary, - Automobile, - City, - Company, - Continent, - Country, - Crime, - Degree, - Drug, - EntertainmentAward, - Facility, - FieldTerminology, - FinancialMarketIndex, - GeographicFeature, - HealthCondition, - Holiday, - JobTitle, - Movie, - MusicGroup, - NaturalDisaster, - OperatingSystem, - Organization, - Person, - PrintMedia, - Product, - ProfessionalDegree, - RadioProgram, - RadioStation, - Region, - Sport, - SportingEvent, - StateOrCounty, - Technology, - TelevisionShow, - TelevisionStation, - EmailAddress, - TwitterHandle, - Hashtag, - IPAddress, - Quantity, - Money, - NAN //At the end - } + /// The relevance. + public string relevance { get; set; } /// - /// Entity sub type. + /// Gets or sets the knowledge graph. /// - public enum EntitySubType - { - AdministrativeDivision, - AircraftManufacturer, - Airport, - AirportOperator, - AwardWinner, - BodyOfWater, - Broadcast, - Building, - ChineseAutonomousCounty, - CityTown, - CollegeUniversity, - Company, - Country, - Cuisine, - Dedicatee, - Disease, - DutchMunicipality, - EnglishCivilParish, - EnglishMetropolitanBorough, - Facility, - FictionalUniverse, - FilmScreeningVenue, - FootballTeam, - FrenchDepartment, - GeographicFeature, - GermanState, - GermanUrbanDistrict, - GovernmentalJurisdiction, - HumanLanguage, - IndianCity, - IndonesianCity, - Island, - ItalianComune, - JapaneseDesignatedCity, - JapanesePrefecture, - Kingdom, - Lake, - Location, - MilitaryConflict, - MilitaryPost, - Mountain, - Museum, - MusicalArtist, - Neighborhood, - OlympicBiddingCity, - OlympicHostCity, - Organization, - Person, - PlaceOfWorship, - PlaceWithNeighborhoods, - PoliticalDistrict, - RadioStation, - RecordProducer, - Region, - River, - School, - SchoolDistrict, - ScottishCouncilArea, - SoccerClub, - SportsTeam, - TouristAttraction, - USCounty, - USIndianReservation, - VietnameseProvincialCities, - Waterfall, - WineRegion, - Accommodation, - Airline, - AwardNominee, - AwardPresentingOrganization, - BasketballConference, - Brand, - Bridge, - BroadcastArtist, - BroadcastContent, - BroadcastDistributor, - Cemetery, - CompanyDivision, - CompanyFounder, - Composer, - ConductedEnsemble, - DrinkingEstablishment, - FashionDesigner, - FashionLabel, - Film, - FilmCinematographer, - FilmCompany, - FilmCostumerDesigner, - FilmDirector, - FilmDistributor, - FilmFestival, - FilmProducer, - HallOfFame, - HistoricPlace, - Hospital, - House, - Inventor, - Magazine, - MembershipOrganization, - MusicalAlbum, - MusicalGroup, - MusicalInstrumentCompany, - Newspaper, - OperaCompany, - Orchestra, - PeriodicalPublisher, - ProductionCompany, - PublicLibrary, - RadioNetwork, - RecordLabel, - RecurringEvent, - Road, - ShoppingCenter, - SportsFacility, - Stadium, - Station, - TelevisionShow, - TelevisionStation, - Theater, - TVChannel, - TVNetwork, - TVProducer, - TVWriter, - University, - VentureFundedCompany, - VideoGameDesigner, - VideoGameDeveloper, - VideoGameEngineDeveloper, - VideoGamePublisher, - Website, - WineProducer, - BoardMember, - Family, - FrenchRegion, - IslandGroup, - Monastery, - NobleTitle, - RoyalLine, - UKOverseasTerritory, - Award, - ArchitecturalContractor, - Lighthouse, - MountainPass, - OlympicVenue, - Park, - ProjectParticipant, - Skyscraper, - DiseaseCause, - Actor, - Book, - Celebrity, - Composition, - ConcertFilm, - FilmActor, - FilmEditor, - FilmSeries, - Play, - PublishedWork, - TVActor, - TVEpisode, - WorkOfFiction, - DisasterSurvivor, - DisasterVictim, - FilmMusicContributor, - Guitarist, - HallOfFameInductee, - MilitaryPerson, - MusicalGroupMember, - BuildingComplex, - CauseOfDeath, - DiseaseOrMedicalCondition, - InfectiousDisease, - MilitaryUnit, - PerformanceVenue, - Academic, - AcademicInstitution, - AircraftDesigner, - AmericanIndianGroup, - Appellation, - Appointer, - Architect, - ArchitectureFirm, - ArmedForce, - Astronaut, - Astronomer, - AstronomicalObservatory, - Athlete, - AutomobileCompany, - AutomobileModel, - AutomotiveDesigner, - AwardDiscipline, - AwardJudge, - BasketballPlayer, - Bassist, - Beer, - Beverage, - BicycleManufacturer, - Blog, - Blogger, - BoardMemberTitle, - Boxer, - CandyBarManufacturer, - CharacterOccupation, - CharacterSpecies, - Cheese, - ChemicalCompound, - ChivalricOrderMember, - Club, - Collector, - College, - Comedian, - ComicBookCreator, - ComicBookEditor, - ComicBookFictionalUniverse, - ComicBookPenciler, - ComicBookPublisher, - ComicBookSeries, - ComicBookWriter, - ComicStripArtist, - ComicStripSyndicate, - CompanyAdvisor, - CompanyShareholder, - CompetitiveSpace, - ComputerDesigner, - ComputerPeripheral, - ComputerScientist, - ComputingPlatform, - ConcertTour, - Conductor, - ConferenceSeries, - ConsumerProduct, - CricketAdministrativeBody, - CricketTeam, - Criminal, - CriminalOffense, - Dedicator, - DietFollower, - Dish, - Distillery, - Drummer, - EndorsedProduct, - Engine, - Engineer, - EngineeringFirm, - FictionalUniverseCreator, - FieldOfStudy, - FileFormat, - FilmArtDirector, - FilmCharacter, - FilmCrewmember, - FilmCritic, - FilmFestivalFocus, - FilmProductionDesigner, - FilmTheorist, - FilmWriter, - FootballLeague, - FootballOrganization, - FootballPlayer, - FoundingFigure, - Game, - GameDesigner, - GamePublisher, - Golfer, - GovernmentAgency, - GovernmentalBody, - GovernmentOfficeOrTitle, - Governor, - Guitar, - Hobbyist, - HockeyConference, - HockeyTeam, - HonoraryDegreeRecipient, - Illustrator, - Industry, - Invention, - ItalianRegion, - JobTitle, - Journal, - LandscapeProject, - LanguageCreator, - LanguageWritingSystem, - Lyricist, - ManufacturingPlant, - MartialArt, - MartialArtist, - MedicalSpecialty, - MedicalTreatment, - MemberOfParliament, - MeteorologicalService, - MilitaryCommander, - Monarch, - Mountaineer, - MountainRange, - MusicalGameSong, - MusicalPerformanceRole, - MusicalTrack, - MusicFestival, - NaturalOrCulturalPreservationAgency, - NoblePerson, - NonProfitOrganisation, //Non-ProfitOrganisation - OfficeHolder, - OlympicAthlete, - OlympicEvent, - OperaCharacter, - OperaHouse, - OperaSinger, - OperatingSystemDeveloper, - OrganizationSector, - PeriodicalEditor, - Philosopher, - Physician, - PoliticalAppointer, - PoliticalParty, - Politician, - President, - ProcessorManufacturer, - Profession, - ProfessionalSportsTeam, - ProgrammingLanguageDesigner, - ProgrammingLanguageDeveloper, - ProtectedArea, - Protocol, - ProtocolProvider, - Rank, - RecordingEngineer, - RecurringCompetition, - Religion, - ReligiousLeader, - ReligiousOrder, - ReligiousOrganization, - ReportIssuingInstitution, - RiskFactor, - RocketEngineDesigner, - RocketManufacturer, - Saint, - Satellite, - SchoolFounder, - SchoolNewspaper, - SchoolSportsTeam, - Scientist, - Senator, - ShipBuilder, - ShipDesigner, - SkiArea, - Software, - SoftwareDeveloper, - SoftwareLicense, - Songwriter, - Soundtrack, - SpaceAgency, - SpacecraftManufacturer, - Spaceport, - Sport, - SportsAssociation, - SportsLeagueAwardWinner, - StudentOrganization, - Supercouple, - Surgeon, - Symptom, - TheaterActor, - TheaterCharacter, - TheaterProduction, - TheatricalComposer, - TheatricalLyricist, - TopLevelDomainRegistry, - TradeUnion, - TransitLine, - TransportOperator, - TransportTerminus, - TVCharacter, - TVDirector, - TVPersonality, - USCongressperson, //U.S.Congressperson - USPresident, - USTerritory, - USVicePresident, - VideoGame, - VideoGameActor, - VideoGameEngine, - VideoGamePlatform, - VisualArtist, - Wrestler, - Writer, - Adherents, - Appointee, - ArchitectureFirmPartner, - BasketballCoach, - BritishRoyalty, - Cardinal, - Chancellor, - Chef, - ChivalricOrderFounder, - ChivalricOrderOfficer, - ChristianBishop, - CollegeCoach, - ComicBookInker, - ComicBookLetterer, - CreativeWork, - CricketBowler, - CricketCoach, - CricketPlayer, - CulinaryTool, - Cyclist, - Deity, - ElectionCampaign, - ElementDiscoverer, - FilmCastingDirector, - FilmSetDesigner, - FootballCoach, - FootballManager, - HockeyCoach, - HockeyPlayer, - Holiday, - Journalist, - Judge, - LandscapeArchitect, - Mayor, - Model, - MusicalRelease, - OperaDirector, - OrganismClassification, - ProfessionalField, - ProgrammingLanguage, - RugbyPlayer, - SchoolMascot, - SportsOfficial, - TennisPlayer, - TennisTournamentChampion, - TheaterChoreographer, - TheaterDesigner, - TheaterDirector, - TheaterProducer, - TVCrewmember, - TVThemeSong, - VaccineDeveloper, - RadioProgram, - USState - } - #endregion + /// The knowledge graph. + public KnowledgeGraph knowledgeGraph { get; set; } - #region GetFeedLinks /// - /// Feed data. + /// Gets or sets the website. /// - [fsObject] - public class FeedData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the feeds. - /// - /// The feeds. - public Feed[] feeds { get; set; } - } + /// The website. + public string website { get; set; } /// - /// Feed. + /// Gets or sets the geo. /// - [fsObject] - public class Feed - { - /// - /// Gets or sets the feed. - /// - /// The feed. - public string feed { get; set; } - } - #endregion + /// The geo. + public string geo { get; set; } - #region GetRankedKeyworkds /// - /// Keyword data. + /// Gets or sets the dbpedia. /// - [fsObject] - public class KeywordData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the keywords. - /// - /// The keywords. - public Keyword[] keywords { get; set; } - - /// - /// Gets a value indicating whether this instance has data. - /// - /// true if this instance has data; otherwise, false. - public bool HasData - { - get - { - return keywords != null && keywords.Length > 0; - } - } + /// The dbpedia. + public string dbpedia { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - StringBuilder stringBuilder = new StringBuilder(); - for (int indexKeyword = 0; keywords != null && indexKeyword < keywords.Length; indexKeyword++) - { - stringBuilder.Append("\n\t"); - stringBuilder.Append(keywords[indexKeyword].ToString()); - } - return string.Format("[KeywordExtractionData: status={0}, language={1}, url={2}, text={3}, keywords={4}]", status, language, url, text, stringBuilder.ToString()); - } - }; + /// + /// Gets or sets the freebase. + /// + /// The freebase. + public string freebase { get; set; } /// - /// Keyword. + /// Gets or sets the yago. /// - [fsObject] - public class Keyword - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the relevance. - /// - /// The relevance. - public string relevance { get; set; } - - /// - /// Gets or sets the knowledge graph. - /// - /// The knowledge graph. - public KnowledgeGraph knowledgeGraph { get; set; } - - /// - /// Gets or sets the sentiment. - /// - /// The sentiment. - public DocSentiment sentiment { get; set; } - }; - #endregion - - #region GetLanguage - /// - /// Language data. - /// - [fsObject] - public class LanguageData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the iso 639 1. - /// - /// The iso 639 1. - [fsProperty("iso-639-1")] - public string iso_639_1 { get; set; } - - /// - /// Gets or sets the iso 639 2. - /// - /// The iso 639 2. - [fsProperty("iso-639-2")] - public string iso_639_2 { get; set; } - - /// - /// Gets or sets the iso 639 3. - /// - /// The iso 639 3. - [fsProperty("iso-639-3")] - public string iso_639_3 { get; set; } - - /// - /// Gets or sets the ethnologue. - /// - /// The ethnologue. - public string ethnologue { get; set; } - - /// - /// Gets or sets the native speakers. - /// - /// The native speakers. - [fsProperty("native-speakers")] - public string native_speakers { get; set; } - - /// - /// Gets or sets the wikipedia. - /// - /// The wikipedia. - public string wikipedia { get; set; } - } - #endregion + /// The yago. + public string yago { get; set; } - #region GetMicroformatData /// - /// Microformat data. + /// Gets or sets the opencyc. /// - [fsObject] - public class MicroformatData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the microformats. - /// - /// The microformats. - public Microformat[] microformats { get; set; } - } + /// The opencyc. + public string opencyc { get; set; } /// - /// Microformat. + /// Gets or sets the cia factbook. /// - [fsObject] - public class Microformat - { - /// - /// Gets or sets the field. - /// - /// The field. - public string field { get; set; } - - /// - /// Gets or sets the data. - /// - /// The data. - public string data { get; set; } - } - #endregion + /// The cia factbook. + public string ciaFactbook { get; set; } - #region GetPublicationDate /// - /// Pub date data. + /// Gets or sets the census. /// - [fsObject] - public class PubDateData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the publication date. - /// - /// The publication date. - public PublicationDate publicationDate { get; set; } - } - #endregion + /// The census. + public string census { get; set; } - #region GetRelations /// - /// Relations data. + /// Gets or sets the geonames. /// - [fsObject] - public class RelationsData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the relations. - /// - /// The relations. - public Relation[] relations { get; set; } - } - #endregion + /// The geonames. + public string geonames { get; set; } - #region GetSentiment /// - /// Sentiment data. + /// Gets or sets the music brainz. /// - [fsObject] - public class SentimentData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the document sentiment. - /// - /// The document sentiment. - public DocSentiment docSentiment { get; set; } - } - #endregion + /// The music brainz. + public string musicBrainz { get; set; } - #region GetTargetedSentiment /// - /// Targeted sentiment data. + /// Gets or sets the crunchbase. /// - [fsObject] - public class TargetedSentimentData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the results. - /// - /// The results. - public TargetedSentiment[] results { get; set; } - } + /// The crunchbase. + public string crunchbase { get; set; } + }; + #endregion + + #region ExtractDates + /// + /// Date data. + /// + [fsObject] + public class DateData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } /// - /// Targeted sentiment. + /// Gets or sets the language. /// - [fsObject] - public class TargetedSentiment - { - /// - /// Gets or sets the sentiment. - /// - /// The sentiment. - public DocSentiment sentiment { get; set; } - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - } - #endregion + /// The language. + public string language { get; set; } - #region GetRankedTaxonomy /// - /// Taxonomy data. + /// Gets or sets the URL. /// - [fsObject] - public class TaxonomyData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the taxonomy. - /// - /// The taxonomy. - public Taxonomy[] taxonomy { get; set; } - } - #endregion + /// The URL. + public string url { get; set; } - #region GetRawText /// - /// Text data. + /// Gets or sets the text. /// - [fsObject] - public class TextData - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the language. - /// - /// The language. - public string language { get; set; } - } - #endregion + /// The text. + public string text { get; set; } - #region GetTitle /// - /// Title. + /// Gets or sets the dates. /// - [fsObject] - public class Title - { - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - - /// - /// Gets or sets the URL. - /// - /// The URL. - public string url { get; set; } - - /// - /// Gets or sets the title. - /// - /// The title. - public string title { get; set; } - } - #endregion + /// The dates. + public Date[] dates { get; set; } + } + + /// + /// Date. + /// + [fsObject] + public class Date + { + /// + /// Gets or sets the date. + /// + /// The date. + public string date { get; set; } - #region InlineModels /// - /// Knowledge graph. + /// Gets or sets the text. /// - [fsObject] - public class KnowledgeGraph - { - /// - /// Gets or sets the type hierarchy. - /// - /// The type hierarchy. - public string typeHierarchy { get; set; } - - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - return string.Format("[KnowledgeGraph: typeHierarchy={0}]", typeHierarchy); - } - } + /// The text. + public string text { get; set; } + + private System.DateTime m_dateValue = default(System.DateTime); /// - /// Disambiguated. + /// Gets the date value. /// - [fsObject] - public class Disambiguated + /// The date value. + public System.DateTime DateValue { - /// - /// Gets or sets the name. - /// - /// The name. - public string name { get; set; } - - /// - /// Gets or sets the type of the sub. - /// - /// The type of the sub. - public string subType { get; set; } - - /// - /// Gets or sets the website. - /// - /// The website. - public string website { get; set; } - - /// - /// Gets or sets the geo. - /// - /// The geo. - public string geo { get; set; } - - /// - /// Gets or sets the dbpedia. - /// - /// The dbpedia. - public string dbpedia { get; set; } - - /// - /// Gets or sets the yago. - /// - /// The yago. - public string yago { get; set; } - - /// - /// Gets or sets the opencyc. - /// - /// The opencyc. - public string opencyc { get; set; } - - /// - /// Gets or sets the umbel. - /// - /// The umbel. - public string umbel { get; set; } - - /// - /// Gets or sets the freebase. - /// - /// The freebase. - public string freebase { get; set; } - - /// - /// Gets or sets the cia factbook. - /// - /// The cia factbook. - public string ciaFactbook { get; set; } - - /// - /// Gets or sets the census. - /// - /// The census. - public string census { get; set; } - - /// - /// Gets or sets the geonames. - /// - /// The geonames. - public string geonames { get; set; } - - /// - /// Gets or sets the music brainz. - /// - /// The music brainz. - public string musicBrainz { get; set; } - - /// - /// Gets or sets the crunchbase. - /// - /// The crunchbase. - public string crunchbase { get; set; } - - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() + get + { + if (m_dateValue == default(System.DateTime) && !string.IsNullOrEmpty(date) && date.Length > 8) { - return string.Format("[Disambiguated: name={0}, subType={1}, website={2}, geo={3}, dbpedia={4}, yago={5}, opencyc={6}, umbel={7}, freebase={8}, ciaFactbook={9}, census={10}, geonames={11}, musicBrainz={12}, crunchbase={13}]", name, subType, website, geo, dbpedia, yago, opencyc, umbel, freebase, ciaFactbook, census, geonames, musicBrainz, crunchbase); + //19840101T000000 + System.DateTime.TryParseExact(date.Remove(8), + "yyyyddMM", + System.Globalization.CultureInfo.InvariantCulture, + System.Globalization.DateTimeStyles.None, + out m_dateValue); + } + return m_dateValue; + } } - + }; + #endregion + + #region GetEmotion + /// + /// Emotion data. + /// + [fsObject] + public class EmotionData + { /// - /// Quotation. + /// Gets or sets the status. /// - [fsObject] - public class Quotation - { - - /// - /// Gets or sets the quotation. - /// - /// The quotation. - public string quotation { get; set; } - - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - return string.Format("[Quotation: quotation={0}]", quotation); - } - } + /// The status. + public string status { get; set; } /// - /// Document sentiment. + /// Gets or sets the URL. /// - [fsObject] - public class DocSentiment - { - /// - /// Gets or sets the type. - /// - /// The type. - public string type { get; set; } - - /// - /// Gets or sets the score. - /// - /// The score. - public string score { get; set; } - - /// - /// Gets or sets the mixed. - /// - /// The mixed. - public string mixed { get; set; } - - private double m_Score = 0; - /// - /// Gets the score. - /// - /// The score. - public double Score - { - get - { - if (m_Score == 0) - { - if (!string.IsNullOrEmpty(score)) - { - double.TryParse(score, out m_Score); - } - } + /// The URL. + public string url { get; set; } - return m_Score; - } - } - - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - return string.Format("[Sentiment: type={0}, score={1}, mixed={2}]", type, score, mixed); - } - } + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } /// - /// Publication date. + /// Gets or sets the text. /// - [fsObject] - public class PublicationDate - { - /// - /// Gets or sets the date. - /// - /// The date. - public string date { get; set; } - /// - /// Gets or sets the confident. - /// - /// The confident. - public string confident { get; set; } - } + /// The text. + public string text { get; set; } /// - /// Relation. + /// Gets or sets the document emotions. /// - [fsObject] - public class Relation - { - /// - /// Gets or sets the sentence. - /// - /// The sentence. - public string sentence { get; set; } - - /// - /// Gets or sets the subject. - /// - /// The subject. - public Subject subject { get; set; } - - /// - /// Gets or sets the action. - /// - /// The action. - public Action action { get; set; } - - /// - /// Gets or sets the object. - /// - /// The object. - public ObjectData @object { get; set; } - - /// - /// Gets or sets the location. - /// - /// The location. - public Location location { get; set; } - - /// - /// Gets or sets the temporal. - /// - public Temporal temporal { get; set; } - } - + /// The document emotions. + public DocEmotions docEmotions { get; set; } + } + + /// + /// Document emotions. + /// + [fsObject] + public class DocEmotions + { /// - /// Subject. + /// Gets or sets the anger. /// - [fsObject] - public class Subject - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the sentiment. - /// - /// The sentiment. - public DocSentiment sentiment { get; set; } - - /// - /// Gets or sets the entities. - /// - /// The entities. - public Entity entities { get; set; } - - /// - /// Gets or sets the keywords. - /// - /// The keywords. - public Keyword keywords { get; set; } - } + /// The anger. + public string anger { get; set; } /// - /// Action. + /// Gets or sets the disgust. /// - [fsObject] - public class Action - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the lemmatized. - /// - /// The lemmatized. - public string lemmatized { get; set; } - - /// - /// Gets or sets the verb. - /// - /// The verb. - public Verb verb { get; set; } - } + /// The disgust. + public string disgust { get; set; } /// - /// Object data. + /// Gets or sets the fear. /// - [fsObject] - public class ObjectData - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the sentiment. - /// - /// The sentiment. - public DocSentiment sentiment { get; set; } - - /// - /// Gets or sets the sentiment from subject. - /// - /// The sentiment from subject. - public DocSentiment sentimentFromSubject { get; set; } - - /// - /// Gets or sets the entity. - /// - /// The entity. - public Entity entity { get; set; } - } + /// The fear. + public string fear { get; set; } /// - /// Verb. + /// Gets or sets the joy. /// - [fsObject] - public class Verb - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the tense. - /// - /// The tense. - public string tense { get; set; } - - /// - /// Gets or sets the negated. - /// - /// The negated. - public string negated { get; set; } - } + /// The joy. + public string joy { get; set; } /// - /// Taxonomy. + /// Gets or sets the sadness. /// - [fsObject] - public class Taxonomy - { - /// - /// Gets or sets the label. - /// - /// The label. - public string label { get; set; } - - /// - /// Gets or sets the score. - /// - /// The score. - public string score { get; set; } - - /// - /// Gets or sets the confident. - /// - /// The confident. - public string confident { get; set; } - }; - - /// - /// Location. - /// - [fsObject] - public class Location - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - - /// - /// Gets or sets the entities. - /// - /// The entities. - public Entity[] entities { get; set; } - } + /// The sadness. + public string sadness { get; set; } + }; + #endregion + + #region GetRankedNamedEntities + /// + /// Entity data. + /// + [fsObject] + public class EntityData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } /// - /// Temporal. + /// Gets or sets the URL. /// - [fsObject] - public class Temporal - { - /// - /// Gets or sets the text - /// - public string text { get; set; } - /// - /// Gets or sets the decoded values - /// - public Decoded decoded { get; set; } - } + /// The URL. + public string url { get; set; } /// - /// Decoded values. + /// Gets or sets the language. /// - [fsObject] - public class Decoded - { - /// - /// Gets or sets the type. - /// - public string type { get; set; } - /// - /// Gets or sets the value. - /// - public string value { get; set; } - /// - /// Gets or sets the start time. - /// - public string start { get; set; } - /// - /// Gets or sets the end time. - /// - public string end { get; set; } - } - #endregion + /// The language. + public string language { get; set; } - #region GetNews /// - /// The NewsResponse. + /// Gets or sets the text. /// - [fsObject] - public class NewsResponse - { - /// - /// THe status of the request. - /// - public string status { get; set; } - /// - /// The results. - /// - public Result result { get; set; } - } + /// The text. + public string text { get; set; } /// - /// The Result data. + /// Gets or sets the entities. /// - [fsObject] - public class Result - { - /// - /// The next string. - /// - public string next { get; set; } - /// - /// The request status. - /// - public string status { get; set; } - /// - /// The docs data. - /// - public Docs[] docs { get; set; } - } - #endregion + /// The entities. + public Entity[] entities { get; set; } - #region Docs /// - /// The Docs data. + /// Gets a value indicating whether this instance has data. /// - [fsObject] - public class Docs + /// true if this instance has data; otherwise, false. + public bool HasData { - /// - /// The request ID. - /// - public string id { get; set; } - /// - /// The source data. - /// - public Source source { get; set; } - /// - /// Timestamp of the request. - /// - public string timestamp { get; set; } + get + { + return entities != null && entities.Length > 0; + } } - #endregion - #region Source /// - /// The Source data. + /// Gets a value indicating whether this instance has geographic information. /// - [fsObject] - public class Source + /// true if this instance has geographic information; otherwise, false. + public bool HasGeographicInformation { - /// - /// Original data. - /// - public Original original { get; set; } - /// - /// The enriched data. - /// - /// The enriched. - public Enriched enriched { get; set; } + get + { + string geoString = null; + for (int i = 0; entities != null && i < entities.Length; i++) + { + if (entities[i].disambiguated != null) + { + geoString = entities[i].disambiguated.geo; + if (!string.IsNullOrEmpty(geoString)) + break; + } + } + return !string.IsNullOrEmpty(geoString); + } } - #endregion - #region Originial + private PositionOnMap m_GeoLocation = null; /// - /// The Original data. + /// Gets the geo location. /// - [fsObject] - public class Original + /// The geo location. + public PositionOnMap GeoLocation { - /// - /// The URL. - /// - public string url { get; set; } + get + { + if (m_GeoLocation == null) + { + string geoString = null; + for (int i = 0; entities != null && i < entities.Length; i++) + { + if (entities[i].disambiguated != null) + { + geoString = entities[i].disambiguated.geo; + if (!string.IsNullOrEmpty(geoString)) + { + string[] geoValues = geoString.Split(' '); + if (geoValues != null && geoValues.Length == 2) + { + double latitute = 0; + double longitutde = 0; + + if (double.TryParse(geoValues[0], out latitute) && double.TryParse(geoValues[1], out longitutde)) + { + m_GeoLocation = new PositionOnMap(latitute, longitutde, entities[i].disambiguated.name); + break; + } + } + } + } + } + } + return m_GeoLocation; + } } - #endregion - #region Enriched /// - /// The Enriched data. + /// Returns a that represents the current . /// - [fsObject] - public class Enriched + /// A that represents the current . + public override string ToString() { - /// - /// The URL. - /// - public URL url { get; set; } + StringBuilder stringBuilder = new StringBuilder(); + for (int indexEntity = 0; entities != null && indexEntity < entities.Length; indexEntity++) + { + stringBuilder.Append("\n\t"); + stringBuilder.Append(entities[indexEntity].ToString()); + } + return string.Format("[EntityExtractionData: status={0}, language={1}, url={2}, text={3}, entities={4}]", status, language, url, text, stringBuilder.ToString()); } - #endregion - #region URL + }; + + /// + /// Entity. + /// + [fsObject] + public class Entity + { /// - /// The URL data. + /// Gets or sets the type. /// - [fsObject] - public class URL - { - /// - /// The image data. - /// - public string image { get; set; } - /// - /// The image keywords. - /// - public ImageKeyword[] imageKeywords { get; set; } - /// - /// The RSS Feed data. - /// - public Feed[] feeds { get; set; } - /// - /// The URL. - /// - public string url { get; set; } - /// - /// The raw title. - /// - public string title { get; set; } - /// - /// The cleaned title. - /// - public string cleanedTitle { get; set; } - /// - /// Detected language. - /// - public string language { get; set; } - /// - /// The PublicationDate data. - /// - public PublicationDate publicationDate { get; set; } - /// - /// Text data. - /// - public string text { get; set; } - /// - /// /The Author data. - /// - public string author { get; set; } - /// - /// Keyword Extraction data. - /// - public Keyword[] keywords { get; set; } - /// - /// Entity extraction data. - /// - public Entity[] entities { get; set; } - /// - /// The concept data. - /// - public Concept[] concepts { get; set; } - /// - /// The relations data. - /// - public Relation relations { get; set; } - /// - /// The DocSentiment. - /// - public DocSentiment docSentiment { get; set; } - /// - /// The taxonomy data. - /// - public Taxonomy taxonomy { get; set; } - /// - /// The enriched title data. - /// - public EnrichedTitle[] enrichedTitle { get; set; } - } - #endregion + /// The type. + public string type { get; set; } - #region EnrichedTitle /// - /// The EnrichedTitle data. + /// Gets or sets the relevance. /// - [fsObject] - public class EnrichedTitle - { - /// - /// Keyword extraction data. - /// - public Keyword[] keywords { get; set; } - /// - /// Entity extraction data. - /// - public Entity[] entities { get; set; } - /// - /// The Concepts data. - /// - public Concept[] concepts { get; set; } - /// - /// Relations data. - /// - public Relation[] relations { get; set; } - /// - /// The DocSentiment. - /// - public DocSentiment docSentiment { get; set; } - /// - /// Taxonomy data. - /// - public Taxonomy[] taxonomy { get; set; } - } - #endregion + /// The relevance. + public string relevance { get; set; } - #region AlchemyData News Fields /// - /// All fields for querying and receiving data. + /// Gets or sets the knowledge graph. /// - public class Fields - { - public const string ORIGINAL_URL = "original.url"; - public const string ENRICHED_URL_IMAGE = "enriched.url.image"; - public const string ENRICHED_URL_IMAGEKEYWORDS = "enriched.url.imageKeywords"; - public const string ENRICHED_URL_IMAGEKEYWORDS_IMAGEKEYWORD_TEXT = "enriched.url.imageKeywords.imageKeyword.text"; - public const string ENRICHED_URL_IMAGEKEYWORDS_IMAGEKEYWORD_SCORE = "enriched.url.imageKeywords.imageKeyword.score"; - public const string ENRICHED_URL_FEEDS = "enriched.url.feeds"; - public const string ENRICHED_URL_FEEDS_FEED_FEED = "enriched.url.feeds.feed.feed"; - public const string ENRICHED_URL_URL = "enriched.url.url"; - public const string ENRICHED_URL_TITLE = "enriched.url.title"; - public const string ENRICHED_URL_CLEANEDTITLE = "enriched.url.cleanedTitle"; - public const string ENRICHED_URL_LANGUAGE = "enriched.url.language"; - public const string ENRICHED_URL_PUBLICATIONDATE_DATE = "enriched.url.publicationDate.date"; - public const string ENRICHED_URL_PUBLICATIONDATE_CONFIDENT = "enriched.url.publicationDate.confident"; - public const string ENRICHED_URL_TEXT = "enriched.url.text"; - public const string ENRICHED_URL_AUTHOR = "enriched.url.author"; - public const string ENRICHED_URL_KEYWORDS = "enriched.url.keywords"; - public const string ENRICHED_URL_KEYWORDS_KEYWORD_TEXT = "enriched.url.keywords.keyword.text"; - public const string ENRICHED_URL_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.keywords.keyword.relevance"; - public const string ENRICHED_URL_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENTITIES = "enriched.url.entities"; - public const string ENRICHED_URL_ENTITIES_ENTITY_TEXT = "enriched.url.entities.entity.text"; - public const string ENRICHED_URL_ENTITIES_ENTITY_TYPE = "enriched.url.entities.entity.type"; - public const string ENRICHED_URL_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENTITIES_ENTITY_COUNT = "enriched.url.entities.entity.count"; - public const string ENRICHED_URL_ENTITIES_ENTITY_RELEVANCE = "enriched.url.entities.entity.relevance"; - public const string ENRICHED_URL_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.entities.entity.sentiment.type"; - public const string ENRICHED_URL_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.entities.entity.sentiment.score"; - public const string ENRICHED_URL_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.entities.entity.quotations"; - public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_CONCEPTS = "enriched.url.concepts"; - public const string ENRICHED_URL_CONCEPTS_CONCEPT_TEXT = "enriched.url.concepts.concept.text"; - public const string ENRICHED_URL_CONCEPTS_CONCEPT_RELEVANCE = "enriched.url.concepts.concept.relevance"; - public const string ENRICHED_URL_CONCEPTS_CONCEPT_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.concepts.concept.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS = "enriched.url.relations"; - public const string ENRICHED_URL_RELATIONS_RELATION_SENTENCE = "enriched.url.relations.relation.sentence"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_TEXT = "enriched.url.relations.relation.subject.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES = "enriched.url.relations.relation.subject.entities"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.relations.relation.subject.entities.entity.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.relations.relation.subject.entities.entity.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.subject.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.relations.relation.subject.entities.entity.count"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.relations.relation.subject.entities.entity.relevance"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.relations.relation.subject.entities.entity.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.relations.relation.subject.entities.entity.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.relations.relation.subject.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.relations.relation.subject.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.relations.relation.subject.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.relations.relation.subject.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.relations.relation.subject.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.relations.relation.subject.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.relations.relation.subject.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.relations.relation.subject.entities.entity.quotations"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS = "enriched.url.relations.relation.subject.keywords"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.relations.relation.subject.keywords.keyword.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.relations.relation.subject.keywords.keyword.relevance"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.relations.relation.subject.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.relations.relation.subject.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.relations.relation.subject.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.subject.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_SENTIMENT_TYPE = "enriched.url.relations.relation.subject.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_SENTIMENT_SCORE = "enriched.url.relations.relation.subject.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_SENTIMENT_MIXED = "enriched.url.relations.relation.subject.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_TEXT = "enriched.url.relations.relation.action.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_LEMMATIZED = "enriched.url.relations.relation.action.lemmatized"; - public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_VERB_TEXT = "enriched.url.relations.relation.action.verb.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_VERB_TENSE = "enriched.url.relations.relation.action.verb.tense"; - public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_VERB_NEGATED = "enriched.url.relations.relation.action.verb.negated"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_TEXT = "enriched.url.relations.relation.object.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES = "enriched.url.relations.relation.object.entities"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.relations.relation.object.entities.entity.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.relations.relation.object.entities.entity.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.object.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.relations.relation.object.entities.entity.count"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.relations.relation.object.entities.entity.relevance"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.relations.relation.object.entities.entity.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.relations.relation.object.entities.entity.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.relations.relation.object.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.relations.relation.object.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.relations.relation.object.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.relations.relation.object.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.relations.relation.object.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.relations.relation.object.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.relations.relation.object.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.relations.relation.object.entities.entity.quotations"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS = "enriched.url.relations.relation.object.keywords"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.relations.relation.object.keywords.keyword.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.relations.relation.object.keywords.keyword.relevance"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.relations.relation.object.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.relations.relation.object.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.relations.relation.object.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.object.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENT_TYPE = "enriched.url.relations.relation.object.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENT_SCORE = "enriched.url.relations.relation.object.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENT_MIXED = "enriched.url.relations.relation.object.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_TYPE = "enriched.url.relations.relation.object.sentimentFromSubject.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_SCORE = "enriched.url.relations.relation.object.sentimentFromSubject.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_MIXED = "enriched.url.relations.relation.object.sentimentFromSubject.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_TEXT = "enriched.url.relations.relation.location.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_SENTIMENT_TYPE = "enriched.url.relations.relation.location.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_SENTIMENT_SCORE = "enriched.url.relations.relation.location.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_SENTIMENT_MIXED = "enriched.url.relations.relation.location.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES = "enriched.url.relations.relation.location.entities"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TEXT = "enriched.url.relations.relation.location.entities.entity.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TYPE = "enriched.url.relations.relation.location.entities.entity.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.location.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_COUNT = "enriched.url.relations.relation.location.entities.entity.count"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_RELEVANCE = "enriched.url.relations.relation.location.entities.entity.relevance"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.relations.relation.location.entities.entity.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.relations.relation.location.entities.entity.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.relations.relation.location.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.relations.relation.location.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.relations.relation.location.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.relations.relation.location.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.relations.relation.location.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.relations.relation.location.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.relations.relation.location.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.relations.relation.location.entities.entity.quotations"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS = "enriched.url.relations.relation.location.keywords"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_TEXT = "enriched.url.relations.relation.location.keywords.keyword.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.relations.relation.location.keywords.keyword.relevance"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.relations.relation.location.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.relations.relation.location.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.relations.relation.location.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.location.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_TEXT = "enriched.url.relations.relation.temporal.text"; - public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_TYPE = "enriched.url.relations.relation.temporal.decoded.type"; - public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_VALUE = "enriched.url.relations.relation.temporal.decoded.value"; - public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_START = "enriched.url.relations.relation.temporal.decoded.start"; - public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_END = "enriched.url.relations.relation.temporal.decoded.end"; - public const string ENRICHED_URL_DOCSENTIMENT_TYPE = "enriched.url.docSentiment.type"; - public const string ENRICHED_URL_DOCSENTIMENT_SCORE = "enriched.url.docSentiment.score"; - public const string ENRICHED_URL_DOCSENTIMENT_MIXED = "enriched.url.docSentiment.mixed"; - public const string ENRICHED_URL_TAXONOMY = "enriched.url.taxonomy"; - public const string ENRICHED_URL_TAXONOMY_TAXONOMY__LABEL = "enriched.url.taxonomy.taxonomy_.label"; - public const string ENRICHED_URL_TAXONOMY_TAXONOMY__SCORE = "enriched.url.taxonomy.taxonomy_.score"; - public const string ENRICHED_URL_TAXONOMY_TAXONOMY__CONFIDENT = "enriched.url.taxonomy.taxonomy_.confident"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS = "enriched.url.enrichedTitle.keywords"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.keywords.keyword.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.keywords.keyword.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES = "enriched.url.enrichedTitle.entities"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.entities.entity.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.entities.entity.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.entities.entity.count"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.entities.entity.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.entities.entity.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.entities.entity.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.entities.entity.quotations"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS = "enriched.url.enrichedTitle.concepts"; - public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS_CONCEPT_TEXT = "enriched.url.enrichedTitle.concepts.concept.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS_CONCEPT_RELEVANCE = "enriched.url.enrichedTitle.concepts.concept.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS_CONCEPT_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.concepts.concept.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS = "enriched.url.enrichedTitle.relations"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SENTENCE = "enriched.url.enrichedTitle.relations.relation.sentence"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_TEXT = "enriched.url.enrichedTitle.relations.relation.subject.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES = "enriched.url.enrichedTitle.relations.relation.subject.entities"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.count"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS = "enriched.url.enrichedTitle.relations.relation.subject.keywords"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_TEXT = "enriched.url.enrichedTitle.relations.relation.action.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_LEMMATIZED = "enriched.url.enrichedTitle.relations.relation.action.lemmatized"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_VERB_TEXT = "enriched.url.enrichedTitle.relations.relation.action.verb.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_VERB_TENSE = "enriched.url.enrichedTitle.relations.relation.action.verb.tense"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_VERB_NEGATED = "enriched.url.enrichedTitle.relations.relation.action.verb.negated"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_TEXT = "enriched.url.enrichedTitle.relations.relation.object.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES = "enriched.url.enrichedTitle.relations.relation.object.entities"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.count"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS = "enriched.url.enrichedTitle.relations.relation.object.keywords"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.sentimentFromSubject.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.sentimentFromSubject.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.sentimentFromSubject.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_TEXT = "enriched.url.enrichedTitle.relations.relation.location.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES = "enriched.url.enrichedTitle.relations.relation.location.entities"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.count"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.name"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.geo"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.dbpedia"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.website"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.subType"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.subType.subType_"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.quotation"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS = "enriched.url.enrichedTitle.relations.relation.location.keywords"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.relevance"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.sentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.sentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.sentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.knowledgeGraph.typeHierarchy"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_TEXT = "enriched.url.enrichedTitle.relations.relation.temporal.text"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_TYPE = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_VALUE = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.value"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_START = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.start"; - public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_END = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.end"; - public const string ENRICHED_URL_ENRICHEDTITLE_DOCSENTIMENT_TYPE = "enriched.url.enrichedTitle.docSentiment.type"; - public const string ENRICHED_URL_ENRICHEDTITLE_DOCSENTIMENT_SCORE = "enriched.url.enrichedTitle.docSentiment.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_DOCSENTIMENT_MIXED = "enriched.url.enrichedTitle.docSentiment.mixed"; - public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY = "enriched.url.enrichedTitle.taxonomy"; - public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY_TAXONOMY__LABEL = "enriched.url.enrichedTitle.taxonomy.taxonomy_.label"; - public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY_TAXONOMY__SCORE = "enriched.url.enrichedTitle.taxonomy.taxonomy_.score"; - public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY_TAXONOMY__CONFIDENT = "enriched.url.enrichedTitle.taxonomy.taxonomy_.confident"; - } - #endregion + /// The knowledge graph. + public KnowledgeGraph knowledgeGraph { get; set; } + + /// + /// Gets or sets the count. + /// + /// The count. + public string count { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the disambiguated. + /// + /// The disambiguated. + public Disambiguated disambiguated { get; set; } + + /// + /// Gets or sets the quotations. + /// + /// The quotations. + public Quotation[] quotations { get; set; } + + /// + /// Gets or sets the sentiment. + /// + /// The sentiment. + public DocSentiment sentiment { get; set; } + + private EntityPrimaryType _EntityType = EntityPrimaryType.NONE; + /// + /// The type of the entity. + /// + public EntityPrimaryType EntityType + { + get + { + if (_EntityType == EntityPrimaryType.NONE && !string.IsNullOrEmpty(type)) + { + for (int i = (int)EntityPrimaryType.NONE; i < (int)EntityPrimaryType.NAN; i++) + { + if (string.Compare(type, ((EntityPrimaryType)i).ToString()) == 0) + { + _EntityType = ((EntityPrimaryType)i); + break; + } + } + } + return _EntityType; + } + } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + for (int indexQuatation = 0; quotations != null && indexQuatation < quotations.Length; indexQuatation++) + { + stringBuilder.Append("\n\t"); + stringBuilder.Append(quotations[indexQuatation].ToString()); + } + + return string.Format("[Entity: type={0} - EntityType={8}, relevance={1}, knowledgeGraph={2}, count={3}, text={4}, disambiguated={5}, quotations={6}, sentiment={7}]", type, relevance, knowledgeGraph, count, text, disambiguated, stringBuilder.ToString(), sentiment, EntityType); + } + + /// + /// Gets a value indicating whether this instance has geographic information. + /// + /// true if this instance has geographic information; otherwise, false. + public bool HasGeographicInformation + { + get + { + string geoString = null; + if (disambiguated != null) + { + geoString = disambiguated.geo; + } + return !string.IsNullOrEmpty(geoString); + } + } + + private PositionOnMap _GeoLocation = null; + /// + /// Gets the geo location. + /// + /// The geo location. + public PositionOnMap GeoLocation + { + get + { + if (_GeoLocation == null) + { + string geoString = null; + if (disambiguated != null) + { + geoString = disambiguated.geo; + if (!string.IsNullOrEmpty(geoString)) + { + string[] geoValues = geoString.Split(' '); + if (geoValues != null && geoValues.Length == 2) + { + double latitute = 0; + double longitutde = 0; + + if (double.TryParse(geoValues[0], out latitute) && double.TryParse(geoValues[1], out longitutde)) + { + _GeoLocation = new PositionOnMap(latitute, longitutde, disambiguated.name); + } + } + } + } + } + return _GeoLocation; + } + } + }; + + /// + /// Position on map. + /// + public class PositionOnMap + { + /// + /// The name of the position. + /// + public string PositionName; + + /// + /// The latitude. + /// + public double Latitude; //Y : North - south + + /// + /// The longitude. + /// + public double Longitude; //X : West - East + + /// + /// Gets the x. + /// + /// The x. + public double X { get { return Longitude; } } + + /// + /// Gets the y. + /// + /// The y. + public double Y { get { return Latitude; } } + + /// + /// Initializes a new instance of the + /// class. + /// + /// Latitude. + /// Longitude. + public PositionOnMap(double latitude, double longitude) + { + this.Latitude = latitude; + this.Longitude = longitude; + } + + /// + /// Initializes a new instance of the + /// class. + /// + /// Latitude. + /// Longitude. + /// Position name. + public PositionOnMap(double latitude, double longitude, string positionName) + { + this.Latitude = latitude; + this.Longitude = longitude; + this.PositionName = positionName; + } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[PositionOnMap: Name: {0}, Latitude:{1}, Longitude:{2}]", PositionName, Latitude.ToString(), Longitude.ToString()); + } + } + #endregion + + #region EntityTypes + /// + /// Entity primary type. + /// + public enum EntityPrimaryType + { + NONE = -1, + Anatomy, + Anniversary, + Automobile, + City, + Company, + Continent, + Country, + Crime, + Degree, + Drug, + EntertainmentAward, + Facility, + FieldTerminology, + FinancialMarketIndex, + GeographicFeature, + HealthCondition, + Holiday, + JobTitle, + Movie, + MusicGroup, + NaturalDisaster, + OperatingSystem, + Organization, + Person, + PrintMedia, + Product, + ProfessionalDegree, + RadioProgram, + RadioStation, + Region, + Sport, + SportingEvent, + StateOrCounty, + Technology, + TelevisionShow, + TelevisionStation, + EmailAddress, + TwitterHandle, + Hashtag, + IPAddress, + Quantity, + Money, + NAN //At the end + } + + /// + /// Entity sub type. + /// + public enum EntitySubType + { + AdministrativeDivision, + AircraftManufacturer, + Airport, + AirportOperator, + AwardWinner, + BodyOfWater, + Broadcast, + Building, + ChineseAutonomousCounty, + CityTown, + CollegeUniversity, + Company, + Country, + Cuisine, + Dedicatee, + Disease, + DutchMunicipality, + EnglishCivilParish, + EnglishMetropolitanBorough, + Facility, + FictionalUniverse, + FilmScreeningVenue, + FootballTeam, + FrenchDepartment, + GeographicFeature, + GermanState, + GermanUrbanDistrict, + GovernmentalJurisdiction, + HumanLanguage, + IndianCity, + IndonesianCity, + Island, + ItalianComune, + JapaneseDesignatedCity, + JapanesePrefecture, + Kingdom, + Lake, + Location, + MilitaryConflict, + MilitaryPost, + Mountain, + Museum, + MusicalArtist, + Neighborhood, + OlympicBiddingCity, + OlympicHostCity, + Organization, + Person, + PlaceOfWorship, + PlaceWithNeighborhoods, + PoliticalDistrict, + RadioStation, + RecordProducer, + Region, + River, + School, + SchoolDistrict, + ScottishCouncilArea, + SoccerClub, + SportsTeam, + TouristAttraction, + USCounty, + USIndianReservation, + VietnameseProvincialCities, + Waterfall, + WineRegion, + Accommodation, + Airline, + AwardNominee, + AwardPresentingOrganization, + BasketballConference, + Brand, + Bridge, + BroadcastArtist, + BroadcastContent, + BroadcastDistributor, + Cemetery, + CompanyDivision, + CompanyFounder, + Composer, + ConductedEnsemble, + DrinkingEstablishment, + FashionDesigner, + FashionLabel, + Film, + FilmCinematographer, + FilmCompany, + FilmCostumerDesigner, + FilmDirector, + FilmDistributor, + FilmFestival, + FilmProducer, + HallOfFame, + HistoricPlace, + Hospital, + House, + Inventor, + Magazine, + MembershipOrganization, + MusicalAlbum, + MusicalGroup, + MusicalInstrumentCompany, + Newspaper, + OperaCompany, + Orchestra, + PeriodicalPublisher, + ProductionCompany, + PublicLibrary, + RadioNetwork, + RecordLabel, + RecurringEvent, + Road, + ShoppingCenter, + SportsFacility, + Stadium, + Station, + TelevisionShow, + TelevisionStation, + Theater, + TVChannel, + TVNetwork, + TVProducer, + TVWriter, + University, + VentureFundedCompany, + VideoGameDesigner, + VideoGameDeveloper, + VideoGameEngineDeveloper, + VideoGamePublisher, + Website, + WineProducer, + BoardMember, + Family, + FrenchRegion, + IslandGroup, + Monastery, + NobleTitle, + RoyalLine, + UKOverseasTerritory, + Award, + ArchitecturalContractor, + Lighthouse, + MountainPass, + OlympicVenue, + Park, + ProjectParticipant, + Skyscraper, + DiseaseCause, + Actor, + Book, + Celebrity, + Composition, + ConcertFilm, + FilmActor, + FilmEditor, + FilmSeries, + Play, + PublishedWork, + TVActor, + TVEpisode, + WorkOfFiction, + DisasterSurvivor, + DisasterVictim, + FilmMusicContributor, + Guitarist, + HallOfFameInductee, + MilitaryPerson, + MusicalGroupMember, + BuildingComplex, + CauseOfDeath, + DiseaseOrMedicalCondition, + InfectiousDisease, + MilitaryUnit, + PerformanceVenue, + Academic, + AcademicInstitution, + AircraftDesigner, + AmericanIndianGroup, + Appellation, + Appointer, + Architect, + ArchitectureFirm, + ArmedForce, + Astronaut, + Astronomer, + AstronomicalObservatory, + Athlete, + AutomobileCompany, + AutomobileModel, + AutomotiveDesigner, + AwardDiscipline, + AwardJudge, + BasketballPlayer, + Bassist, + Beer, + Beverage, + BicycleManufacturer, + Blog, + Blogger, + BoardMemberTitle, + Boxer, + CandyBarManufacturer, + CharacterOccupation, + CharacterSpecies, + Cheese, + ChemicalCompound, + ChivalricOrderMember, + Club, + Collector, + College, + Comedian, + ComicBookCreator, + ComicBookEditor, + ComicBookFictionalUniverse, + ComicBookPenciler, + ComicBookPublisher, + ComicBookSeries, + ComicBookWriter, + ComicStripArtist, + ComicStripSyndicate, + CompanyAdvisor, + CompanyShareholder, + CompetitiveSpace, + ComputerDesigner, + ComputerPeripheral, + ComputerScientist, + ComputingPlatform, + ConcertTour, + Conductor, + ConferenceSeries, + ConsumerProduct, + CricketAdministrativeBody, + CricketTeam, + Criminal, + CriminalOffense, + Dedicator, + DietFollower, + Dish, + Distillery, + Drummer, + EndorsedProduct, + Engine, + Engineer, + EngineeringFirm, + FictionalUniverseCreator, + FieldOfStudy, + FileFormat, + FilmArtDirector, + FilmCharacter, + FilmCrewmember, + FilmCritic, + FilmFestivalFocus, + FilmProductionDesigner, + FilmTheorist, + FilmWriter, + FootballLeague, + FootballOrganization, + FootballPlayer, + FoundingFigure, + Game, + GameDesigner, + GamePublisher, + Golfer, + GovernmentAgency, + GovernmentalBody, + GovernmentOfficeOrTitle, + Governor, + Guitar, + Hobbyist, + HockeyConference, + HockeyTeam, + HonoraryDegreeRecipient, + Illustrator, + Industry, + Invention, + ItalianRegion, + JobTitle, + Journal, + LandscapeProject, + LanguageCreator, + LanguageWritingSystem, + Lyricist, + ManufacturingPlant, + MartialArt, + MartialArtist, + MedicalSpecialty, + MedicalTreatment, + MemberOfParliament, + MeteorologicalService, + MilitaryCommander, + Monarch, + Mountaineer, + MountainRange, + MusicalGameSong, + MusicalPerformanceRole, + MusicalTrack, + MusicFestival, + NaturalOrCulturalPreservationAgency, + NoblePerson, + NonProfitOrganisation, //Non-ProfitOrganisation + OfficeHolder, + OlympicAthlete, + OlympicEvent, + OperaCharacter, + OperaHouse, + OperaSinger, + OperatingSystemDeveloper, + OrganizationSector, + PeriodicalEditor, + Philosopher, + Physician, + PoliticalAppointer, + PoliticalParty, + Politician, + President, + ProcessorManufacturer, + Profession, + ProfessionalSportsTeam, + ProgrammingLanguageDesigner, + ProgrammingLanguageDeveloper, + ProtectedArea, + Protocol, + ProtocolProvider, + Rank, + RecordingEngineer, + RecurringCompetition, + Religion, + ReligiousLeader, + ReligiousOrder, + ReligiousOrganization, + ReportIssuingInstitution, + RiskFactor, + RocketEngineDesigner, + RocketManufacturer, + Saint, + Satellite, + SchoolFounder, + SchoolNewspaper, + SchoolSportsTeam, + Scientist, + Senator, + ShipBuilder, + ShipDesigner, + SkiArea, + Software, + SoftwareDeveloper, + SoftwareLicense, + Songwriter, + Soundtrack, + SpaceAgency, + SpacecraftManufacturer, + Spaceport, + Sport, + SportsAssociation, + SportsLeagueAwardWinner, + StudentOrganization, + Supercouple, + Surgeon, + Symptom, + TheaterActor, + TheaterCharacter, + TheaterProduction, + TheatricalComposer, + TheatricalLyricist, + TopLevelDomainRegistry, + TradeUnion, + TransitLine, + TransportOperator, + TransportTerminus, + TVCharacter, + TVDirector, + TVPersonality, + USCongressperson, //U.S.Congressperson + USPresident, + USTerritory, + USVicePresident, + VideoGame, + VideoGameActor, + VideoGameEngine, + VideoGamePlatform, + VisualArtist, + Wrestler, + Writer, + Adherents, + Appointee, + ArchitectureFirmPartner, + BasketballCoach, + BritishRoyalty, + Cardinal, + Chancellor, + Chef, + ChivalricOrderFounder, + ChivalricOrderOfficer, + ChristianBishop, + CollegeCoach, + ComicBookInker, + ComicBookLetterer, + CreativeWork, + CricketBowler, + CricketCoach, + CricketPlayer, + CulinaryTool, + Cyclist, + Deity, + ElectionCampaign, + ElementDiscoverer, + FilmCastingDirector, + FilmSetDesigner, + FootballCoach, + FootballManager, + HockeyCoach, + HockeyPlayer, + Holiday, + Journalist, + Judge, + LandscapeArchitect, + Mayor, + Model, + MusicalRelease, + OperaDirector, + OrganismClassification, + ProfessionalField, + ProgrammingLanguage, + RugbyPlayer, + SchoolMascot, + SportsOfficial, + TennisPlayer, + TennisTournamentChampion, + TheaterChoreographer, + TheaterDesigner, + TheaterDirector, + TheaterProducer, + TVCrewmember, + TVThemeSong, + VaccineDeveloper, + RadioProgram, + USState + } + #endregion + + #region GetFeedLinks + /// + /// Feed data. + /// + [fsObject] + public class FeedData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the feeds. + /// + /// The feeds. + public Feed[] feeds { get; set; } + } + + /// + /// Feed. + /// + [fsObject] + public class Feed + { + /// + /// Gets or sets the feed. + /// + /// The feed. + public string feed { get; set; } + } + #endregion + + #region GetRankedKeyworkds + /// + /// Keyword data. + /// + [fsObject] + public class KeywordData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the keywords. + /// + /// The keywords. + public Keyword[] keywords { get; set; } + + /// + /// Gets a value indicating whether this instance has data. + /// + /// true if this instance has data; otherwise, false. + public bool HasData + { + get + { + return keywords != null && keywords.Length > 0; + } + } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + StringBuilder stringBuilder = new StringBuilder(); + for (int indexKeyword = 0; keywords != null && indexKeyword < keywords.Length; indexKeyword++) + { + stringBuilder.Append("\n\t"); + stringBuilder.Append(keywords[indexKeyword].ToString()); + } + return string.Format("[KeywordExtractionData: status={0}, language={1}, url={2}, text={3}, keywords={4}]", status, language, url, text, stringBuilder.ToString()); + } + }; + + /// + /// Keyword. + /// + [fsObject] + public class Keyword + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the relevance. + /// + /// The relevance. + public string relevance { get; set; } + + /// + /// Gets or sets the knowledge graph. + /// + /// The knowledge graph. + public KnowledgeGraph knowledgeGraph { get; set; } + + /// + /// Gets or sets the sentiment. + /// + /// The sentiment. + public DocSentiment sentiment { get; set; } + }; + #endregion + + #region GetLanguage + /// + /// Language data. + /// + [fsObject] + public class LanguageData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the iso 639 1. + /// + /// The iso 639 1. + [fsProperty("iso-639-1")] + public string iso_639_1 { get; set; } + + /// + /// Gets or sets the iso 639 2. + /// + /// The iso 639 2. + [fsProperty("iso-639-2")] + public string iso_639_2 { get; set; } + + /// + /// Gets or sets the iso 639 3. + /// + /// The iso 639 3. + [fsProperty("iso-639-3")] + public string iso_639_3 { get; set; } + + /// + /// Gets or sets the ethnologue. + /// + /// The ethnologue. + public string ethnologue { get; set; } + + /// + /// Gets or sets the native speakers. + /// + /// The native speakers. + [fsProperty("native-speakers")] + public string native_speakers { get; set; } + + /// + /// Gets or sets the wikipedia. + /// + /// The wikipedia. + public string wikipedia { get; set; } + } + #endregion + + #region GetMicroformatData + /// + /// Microformat data. + /// + [fsObject] + public class MicroformatData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the microformats. + /// + /// The microformats. + public Microformat[] microformats { get; set; } + } + + /// + /// Microformat. + /// + [fsObject] + public class Microformat + { + /// + /// Gets or sets the field. + /// + /// The field. + public string field { get; set; } + + /// + /// Gets or sets the data. + /// + /// The data. + public string data { get; set; } + } + #endregion + + #region GetPublicationDate + /// + /// Pub date data. + /// + [fsObject] + public class PubDateData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the publication date. + /// + /// The publication date. + public PublicationDate publicationDate { get; set; } + } + #endregion + + #region GetRelations + /// + /// Relations data. + /// + [fsObject] + public class RelationsData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the relations. + /// + /// The relations. + public Relation[] relations { get; set; } + } + #endregion + + #region GetSentiment + /// + /// Sentiment data. + /// + [fsObject] + public class SentimentData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the document sentiment. + /// + /// The document sentiment. + public DocSentiment docSentiment { get; set; } + } + #endregion + + #region GetTargetedSentiment + /// + /// Targeted sentiment data. + /// + [fsObject] + public class TargetedSentimentData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the results. + /// + /// The results. + public TargetedSentiment[] results { get; set; } + } + + /// + /// Targeted sentiment. + /// + [fsObject] + public class TargetedSentiment + { + /// + /// Gets or sets the sentiment. + /// + /// The sentiment. + public DocSentiment sentiment { get; set; } + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + } + #endregion + + #region GetRankedTaxonomy + /// + /// Taxonomy data. + /// + [fsObject] + public class TaxonomyData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the taxonomy. + /// + /// The taxonomy. + public Taxonomy[] taxonomy { get; set; } + } + #endregion + + #region GetRawText + /// + /// Text data. + /// + [fsObject] + public class TextData + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the language. + /// + /// The language. + public string language { get; set; } + } + #endregion + + #region GetTitle + /// + /// Title. + /// + [fsObject] + public class Title + { + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + + /// + /// Gets or sets the URL. + /// + /// The URL. + public string url { get; set; } + + /// + /// Gets or sets the title. + /// + /// The title. + public string title { get; set; } + } + #endregion + + #region InlineModels + /// + /// Knowledge graph. + /// + [fsObject] + public class KnowledgeGraph + { + /// + /// Gets or sets the type hierarchy. + /// + /// The type hierarchy. + public string typeHierarchy { get; set; } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[KnowledgeGraph: typeHierarchy={0}]", typeHierarchy); + } + } + + /// + /// Disambiguated. + /// + [fsObject] + public class Disambiguated + { + /// + /// Gets or sets the name. + /// + /// The name. + public string name { get; set; } + + /// + /// Gets or sets the type of the sub. + /// + /// The type of the sub. + public string subType { get; set; } + + /// + /// Gets or sets the website. + /// + /// The website. + public string website { get; set; } + + /// + /// Gets or sets the geo. + /// + /// The geo. + public string geo { get; set; } + + /// + /// Gets or sets the dbpedia. + /// + /// The dbpedia. + public string dbpedia { get; set; } + + /// + /// Gets or sets the yago. + /// + /// The yago. + public string yago { get; set; } + + /// + /// Gets or sets the opencyc. + /// + /// The opencyc. + public string opencyc { get; set; } + + /// + /// Gets or sets the umbel. + /// + /// The umbel. + public string umbel { get; set; } + + /// + /// Gets or sets the freebase. + /// + /// The freebase. + public string freebase { get; set; } + + /// + /// Gets or sets the cia factbook. + /// + /// The cia factbook. + public string ciaFactbook { get; set; } + + /// + /// Gets or sets the census. + /// + /// The census. + public string census { get; set; } + + /// + /// Gets or sets the geonames. + /// + /// The geonames. + public string geonames { get; set; } + + /// + /// Gets or sets the music brainz. + /// + /// The music brainz. + public string musicBrainz { get; set; } + + /// + /// Gets or sets the crunchbase. + /// + /// The crunchbase. + public string crunchbase { get; set; } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[Disambiguated: name={0}, subType={1}, website={2}, geo={3}, dbpedia={4}, yago={5}, opencyc={6}, umbel={7}, freebase={8}, ciaFactbook={9}, census={10}, geonames={11}, musicBrainz={12}, crunchbase={13}]", name, subType, website, geo, dbpedia, yago, opencyc, umbel, freebase, ciaFactbook, census, geonames, musicBrainz, crunchbase); + } + } + + /// + /// Quotation. + /// + [fsObject] + public class Quotation + { + + /// + /// Gets or sets the quotation. + /// + /// The quotation. + public string quotation { get; set; } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[Quotation: quotation={0}]", quotation); + } + } + + /// + /// Document sentiment. + /// + [fsObject] + public class DocSentiment + { + /// + /// Gets or sets the type. + /// + /// The type. + public string type { get; set; } + + /// + /// Gets or sets the score. + /// + /// The score. + public string score { get; set; } + + /// + /// Gets or sets the mixed. + /// + /// The mixed. + public string mixed { get; set; } + + private double m_Score = 0; + /// + /// Gets the score. + /// + /// The score. + public double Score + { + get + { + if (m_Score == 0) + { + if (!string.IsNullOrEmpty(score)) + { + double.TryParse(score, out m_Score); + } + } + + return m_Score; + } + } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[Sentiment: type={0}, score={1}, mixed={2}]", type, score, mixed); + } + } + + /// + /// Publication date. + /// + [fsObject] + public class PublicationDate + { + /// + /// Gets or sets the date. + /// + /// The date. + public string date { get; set; } + /// + /// Gets or sets the confident. + /// + /// The confident. + public string confident { get; set; } + } + + /// + /// Relation. + /// + [fsObject] + public class Relation + { + /// + /// Gets or sets the sentence. + /// + /// The sentence. + public string sentence { get; set; } + + /// + /// Gets or sets the subject. + /// + /// The subject. + public Subject subject { get; set; } + + /// + /// Gets or sets the action. + /// + /// The action. + public Action action { get; set; } + + /// + /// Gets or sets the object. + /// + /// The object. + public ObjectData @object { get; set; } + + /// + /// Gets or sets the location. + /// + /// The location. + public Location location { get; set; } + + /// + /// Gets or sets the temporal. + /// + public Temporal temporal { get; set; } + } + + /// + /// Subject. + /// + [fsObject] + public class Subject + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the sentiment. + /// + /// The sentiment. + public DocSentiment sentiment { get; set; } + + /// + /// Gets or sets the entities. + /// + /// The entities. + public Entity entities { get; set; } + + /// + /// Gets or sets the keywords. + /// + /// The keywords. + public Keyword keywords { get; set; } + } + + /// + /// Action. + /// + [fsObject] + public class Action + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the lemmatized. + /// + /// The lemmatized. + public string lemmatized { get; set; } + + /// + /// Gets or sets the verb. + /// + /// The verb. + public Verb verb { get; set; } + } + + /// + /// Object data. + /// + [fsObject] + public class ObjectData + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the sentiment. + /// + /// The sentiment. + public DocSentiment sentiment { get; set; } + + /// + /// Gets or sets the sentiment from subject. + /// + /// The sentiment from subject. + public DocSentiment sentimentFromSubject { get; set; } + + /// + /// Gets or sets the entity. + /// + /// The entity. + public Entity entity { get; set; } + } + + /// + /// Verb. + /// + [fsObject] + public class Verb + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the tense. + /// + /// The tense. + public string tense { get; set; } + + /// + /// Gets or sets the negated. + /// + /// The negated. + public string negated { get; set; } + } + + /// + /// Taxonomy. + /// + [fsObject] + public class Taxonomy + { + /// + /// Gets or sets the label. + /// + /// The label. + public string label { get; set; } + + /// + /// Gets or sets the score. + /// + /// The score. + public string score { get; set; } + + /// + /// Gets or sets the confident. + /// + /// The confident. + public string confident { get; set; } + }; + + /// + /// Location. + /// + [fsObject] + public class Location + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + + /// + /// Gets or sets the entities. + /// + /// The entities. + public Entity[] entities { get; set; } + } + + /// + /// Temporal. + /// + [fsObject] + public class Temporal + { + /// + /// Gets or sets the text + /// + public string text { get; set; } + /// + /// Gets or sets the decoded values + /// + public Decoded decoded { get; set; } + } + + /// + /// Decoded values. + /// + [fsObject] + public class Decoded + { + /// + /// Gets or sets the type. + /// + public string type { get; set; } + /// + /// Gets or sets the value. + /// + public string value { get; set; } + /// + /// Gets or sets the start time. + /// + public string start { get; set; } + /// + /// Gets or sets the end time. + /// + public string end { get; set; } + } + #endregion + + #region GetNews + /// + /// The NewsResponse. + /// + [fsObject] + public class NewsResponse + { + /// + /// THe status of the request. + /// + public string status { get; set; } + /// + /// The results. + /// + public Result result { get; set; } + } + + /// + /// The Result data. + /// + [fsObject] + public class Result + { + /// + /// The next string. + /// + public string next { get; set; } + /// + /// The request status. + /// + public string status { get; set; } + /// + /// The docs data. + /// + public Docs[] docs { get; set; } + } + #endregion + + #region Docs + /// + /// The Docs data. + /// + [fsObject] + public class Docs + { + /// + /// The request ID. + /// + public string id { get; set; } + /// + /// The source data. + /// + public Source source { get; set; } + /// + /// Timestamp of the request. + /// + public string timestamp { get; set; } + } + #endregion + + #region Source + /// + /// The Source data. + /// + [fsObject] + public class Source + { + /// + /// Original data. + /// + public Original original { get; set; } + /// + /// The enriched data. + /// + /// The enriched. + public Enriched enriched { get; set; } + } + #endregion + + #region Originial + /// + /// The Original data. + /// + [fsObject] + public class Original + { + /// + /// The URL. + /// + public string url { get; set; } + } + #endregion + + #region Enriched + /// + /// The Enriched data. + /// + [fsObject] + public class Enriched + { + /// + /// The URL. + /// + public URL url { get; set; } + } + #endregion + + #region URL + /// + /// The URL data. + /// + [fsObject] + public class URL + { + /// + /// The image data. + /// + public string image { get; set; } + /// + /// The image keywords. + /// + public ImageKeyword[] imageKeywords { get; set; } + /// + /// The RSS Feed data. + /// + public Feed[] feeds { get; set; } + /// + /// The URL. + /// + public string url { get; set; } + /// + /// The raw title. + /// + public string title { get; set; } + /// + /// The cleaned title. + /// + public string cleanedTitle { get; set; } + /// + /// Detected language. + /// + public string language { get; set; } + /// + /// The PublicationDate data. + /// + public PublicationDate publicationDate { get; set; } + /// + /// Text data. + /// + public string text { get; set; } + /// + /// /The Author data. + /// + public string author { get; set; } + /// + /// Keyword Extraction data. + /// + public Keyword[] keywords { get; set; } + /// + /// Entity extraction data. + /// + public Entity[] entities { get; set; } + /// + /// The concept data. + /// + public Concept[] concepts { get; set; } + /// + /// The relations data. + /// + public Relation relations { get; set; } + /// + /// The DocSentiment. + /// + public DocSentiment docSentiment { get; set; } + /// + /// The taxonomy data. + /// + public Taxonomy taxonomy { get; set; } + /// + /// The enriched title data. + /// + public EnrichedTitle[] enrichedTitle { get; set; } + } + #endregion + + #region EnrichedTitle + /// + /// The EnrichedTitle data. + /// + [fsObject] + public class EnrichedTitle + { + /// + /// Keyword extraction data. + /// + public Keyword[] keywords { get; set; } + /// + /// Entity extraction data. + /// + public Entity[] entities { get; set; } + /// + /// The Concepts data. + /// + public Concept[] concepts { get; set; } + /// + /// Relations data. + /// + public Relation[] relations { get; set; } + /// + /// The DocSentiment. + /// + public DocSentiment docSentiment { get; set; } + /// + /// Taxonomy data. + /// + public Taxonomy[] taxonomy { get; set; } + } + #endregion + + #region AlchemyData News Fields + /// + /// All fields for querying and receiving data. + /// + public class Fields + { + public const string ORIGINAL_URL = "original.url"; + public const string ENRICHED_URL_IMAGE = "enriched.url.image"; + public const string ENRICHED_URL_IMAGEKEYWORDS = "enriched.url.imageKeywords"; + public const string ENRICHED_URL_IMAGEKEYWORDS_IMAGEKEYWORD_TEXT = "enriched.url.imageKeywords.imageKeyword.text"; + public const string ENRICHED_URL_IMAGEKEYWORDS_IMAGEKEYWORD_SCORE = "enriched.url.imageKeywords.imageKeyword.score"; + public const string ENRICHED_URL_FEEDS = "enriched.url.feeds"; + public const string ENRICHED_URL_FEEDS_FEED_FEED = "enriched.url.feeds.feed.feed"; + public const string ENRICHED_URL_URL = "enriched.url.url"; + public const string ENRICHED_URL_TITLE = "enriched.url.title"; + public const string ENRICHED_URL_CLEANEDTITLE = "enriched.url.cleanedTitle"; + public const string ENRICHED_URL_LANGUAGE = "enriched.url.language"; + public const string ENRICHED_URL_PUBLICATIONDATE_DATE = "enriched.url.publicationDate.date"; + public const string ENRICHED_URL_PUBLICATIONDATE_CONFIDENT = "enriched.url.publicationDate.confident"; + public const string ENRICHED_URL_TEXT = "enriched.url.text"; + public const string ENRICHED_URL_AUTHOR = "enriched.url.author"; + public const string ENRICHED_URL_KEYWORDS = "enriched.url.keywords"; + public const string ENRICHED_URL_KEYWORDS_KEYWORD_TEXT = "enriched.url.keywords.keyword.text"; + public const string ENRICHED_URL_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.keywords.keyword.relevance"; + public const string ENRICHED_URL_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENTITIES = "enriched.url.entities"; + public const string ENRICHED_URL_ENTITIES_ENTITY_TEXT = "enriched.url.entities.entity.text"; + public const string ENRICHED_URL_ENTITIES_ENTITY_TYPE = "enriched.url.entities.entity.type"; + public const string ENRICHED_URL_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENTITIES_ENTITY_COUNT = "enriched.url.entities.entity.count"; + public const string ENRICHED_URL_ENTITIES_ENTITY_RELEVANCE = "enriched.url.entities.entity.relevance"; + public const string ENRICHED_URL_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.entities.entity.sentiment.type"; + public const string ENRICHED_URL_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.entities.entity.sentiment.score"; + public const string ENRICHED_URL_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.entities.entity.quotations"; + public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_CONCEPTS = "enriched.url.concepts"; + public const string ENRICHED_URL_CONCEPTS_CONCEPT_TEXT = "enriched.url.concepts.concept.text"; + public const string ENRICHED_URL_CONCEPTS_CONCEPT_RELEVANCE = "enriched.url.concepts.concept.relevance"; + public const string ENRICHED_URL_CONCEPTS_CONCEPT_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.concepts.concept.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS = "enriched.url.relations"; + public const string ENRICHED_URL_RELATIONS_RELATION_SENTENCE = "enriched.url.relations.relation.sentence"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_TEXT = "enriched.url.relations.relation.subject.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES = "enriched.url.relations.relation.subject.entities"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.relations.relation.subject.entities.entity.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.relations.relation.subject.entities.entity.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.subject.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.relations.relation.subject.entities.entity.count"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.relations.relation.subject.entities.entity.relevance"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.relations.relation.subject.entities.entity.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.relations.relation.subject.entities.entity.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.relations.relation.subject.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.relations.relation.subject.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.relations.relation.subject.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.relations.relation.subject.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.relations.relation.subject.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.relations.relation.subject.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.relations.relation.subject.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.relations.relation.subject.entities.entity.quotations"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS = "enriched.url.relations.relation.subject.keywords"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.relations.relation.subject.keywords.keyword.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.relations.relation.subject.keywords.keyword.relevance"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.relations.relation.subject.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.relations.relation.subject.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.relations.relation.subject.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.subject.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_SENTIMENT_TYPE = "enriched.url.relations.relation.subject.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_SENTIMENT_SCORE = "enriched.url.relations.relation.subject.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_SUBJECT_SENTIMENT_MIXED = "enriched.url.relations.relation.subject.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_TEXT = "enriched.url.relations.relation.action.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_LEMMATIZED = "enriched.url.relations.relation.action.lemmatized"; + public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_VERB_TEXT = "enriched.url.relations.relation.action.verb.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_VERB_TENSE = "enriched.url.relations.relation.action.verb.tense"; + public const string ENRICHED_URL_RELATIONS_RELATION_ACTION_VERB_NEGATED = "enriched.url.relations.relation.action.verb.negated"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_TEXT = "enriched.url.relations.relation.object.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES = "enriched.url.relations.relation.object.entities"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.relations.relation.object.entities.entity.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.relations.relation.object.entities.entity.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.object.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.relations.relation.object.entities.entity.count"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.relations.relation.object.entities.entity.relevance"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.relations.relation.object.entities.entity.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.relations.relation.object.entities.entity.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.relations.relation.object.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.relations.relation.object.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.relations.relation.object.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.relations.relation.object.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.relations.relation.object.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.relations.relation.object.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.relations.relation.object.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.relations.relation.object.entities.entity.quotations"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.relations.relation.object.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS = "enriched.url.relations.relation.object.keywords"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.relations.relation.object.keywords.keyword.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.relations.relation.object.keywords.keyword.relevance"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.relations.relation.object.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.relations.relation.object.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.relations.relation.object.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.object.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENT_TYPE = "enriched.url.relations.relation.object.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENT_SCORE = "enriched.url.relations.relation.object.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENT_MIXED = "enriched.url.relations.relation.object.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_TYPE = "enriched.url.relations.relation.object.sentimentFromSubject.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_SCORE = "enriched.url.relations.relation.object.sentimentFromSubject.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_MIXED = "enriched.url.relations.relation.object.sentimentFromSubject.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_TEXT = "enriched.url.relations.relation.location.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_SENTIMENT_TYPE = "enriched.url.relations.relation.location.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_SENTIMENT_SCORE = "enriched.url.relations.relation.location.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_SENTIMENT_MIXED = "enriched.url.relations.relation.location.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES = "enriched.url.relations.relation.location.entities"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TEXT = "enriched.url.relations.relation.location.entities.entity.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TYPE = "enriched.url.relations.relation.location.entities.entity.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.location.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_COUNT = "enriched.url.relations.relation.location.entities.entity.count"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_RELEVANCE = "enriched.url.relations.relation.location.entities.entity.relevance"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.relations.relation.location.entities.entity.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.relations.relation.location.entities.entity.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.relations.relation.location.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.relations.relation.location.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.relations.relation.location.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.relations.relation.location.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.relations.relation.location.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.relations.relation.location.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.relations.relation.location.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.relations.relation.location.entities.entity.quotations"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.relations.relation.location.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS = "enriched.url.relations.relation.location.keywords"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_TEXT = "enriched.url.relations.relation.location.keywords.keyword.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.relations.relation.location.keywords.keyword.relevance"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.relations.relation.location.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.relations.relation.location.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.relations.relation.location.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.relations.relation.location.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_TEXT = "enriched.url.relations.relation.temporal.text"; + public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_TYPE = "enriched.url.relations.relation.temporal.decoded.type"; + public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_VALUE = "enriched.url.relations.relation.temporal.decoded.value"; + public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_START = "enriched.url.relations.relation.temporal.decoded.start"; + public const string ENRICHED_URL_RELATIONS_RELATION_TEMPORAL_DECODED_END = "enriched.url.relations.relation.temporal.decoded.end"; + public const string ENRICHED_URL_DOCSENTIMENT_TYPE = "enriched.url.docSentiment.type"; + public const string ENRICHED_URL_DOCSENTIMENT_SCORE = "enriched.url.docSentiment.score"; + public const string ENRICHED_URL_DOCSENTIMENT_MIXED = "enriched.url.docSentiment.mixed"; + public const string ENRICHED_URL_TAXONOMY = "enriched.url.taxonomy"; + public const string ENRICHED_URL_TAXONOMY_TAXONOMY__LABEL = "enriched.url.taxonomy.taxonomy_.label"; + public const string ENRICHED_URL_TAXONOMY_TAXONOMY__SCORE = "enriched.url.taxonomy.taxonomy_.score"; + public const string ENRICHED_URL_TAXONOMY_TAXONOMY__CONFIDENT = "enriched.url.taxonomy.taxonomy_.confident"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS = "enriched.url.enrichedTitle.keywords"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.keywords.keyword.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.keywords.keyword.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES = "enriched.url.enrichedTitle.entities"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.entities.entity.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.entities.entity.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.entities.entity.count"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.entities.entity.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.entities.entity.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.entities.entity.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.entities.entity.quotations"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS = "enriched.url.enrichedTitle.concepts"; + public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS_CONCEPT_TEXT = "enriched.url.enrichedTitle.concepts.concept.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS_CONCEPT_RELEVANCE = "enriched.url.enrichedTitle.concepts.concept.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_CONCEPTS_CONCEPT_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.concepts.concept.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS = "enriched.url.enrichedTitle.relations"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SENTENCE = "enriched.url.enrichedTitle.relations.relation.sentence"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_TEXT = "enriched.url.enrichedTitle.relations.relation.subject.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES = "enriched.url.enrichedTitle.relations.relation.subject.entities"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.count"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS = "enriched.url.enrichedTitle.relations.relation.subject.keywords"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.subject.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.subject.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.subject.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_SUBJECT_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.subject.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_TEXT = "enriched.url.enrichedTitle.relations.relation.action.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_LEMMATIZED = "enriched.url.enrichedTitle.relations.relation.action.lemmatized"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_VERB_TEXT = "enriched.url.enrichedTitle.relations.relation.action.verb.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_VERB_TENSE = "enriched.url.enrichedTitle.relations.relation.action.verb.tense"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_ACTION_VERB_NEGATED = "enriched.url.enrichedTitle.relations.relation.action.verb.negated"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_TEXT = "enriched.url.enrichedTitle.relations.relation.object.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES = "enriched.url.enrichedTitle.relations.relation.object.entities"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.count"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS = "enriched.url.enrichedTitle.relations.relation.object.keywords"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.object.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_TYPE = "enriched.url.enrichedTitle.relations.relation.object.sentimentFromSubject.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_SCORE = "enriched.url.enrichedTitle.relations.relation.object.sentimentFromSubject.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_OBJECT_SENTIMENTFROMSUBJECT_MIXED = "enriched.url.enrichedTitle.relations.relation.object.sentimentFromSubject.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_TEXT = "enriched.url.enrichedTitle.relations.relation.location.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES = "enriched.url.enrichedTitle.relations.relation.location.entities"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TEXT = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_TYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_COUNT = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.count"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_NAME = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.name"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_GEO = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.geo"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_DBPEDIA = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.dbpedia"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_WEBSITE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.website"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.subType"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_DISAMBIGUATED_SUBTYPE_SUBTYPE_ = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.disambiguated.subType.subType_"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__QUOTATION = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.quotation"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_ENTITIES_ENTITY_QUOTATIONS_QUOTATION__SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.entities.entity.quotations.quotation_.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS = "enriched.url.enrichedTitle.relations.relation.location.keywords"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_TEXT = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_RELEVANCE = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.relevance"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_TYPE = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.sentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_SCORE = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.sentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_SENTIMENT_MIXED = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.sentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_LOCATION_KEYWORDS_KEYWORD_KNOWLEDGEGRAPH_TYPEHIERARCHY = "enriched.url.enrichedTitle.relations.relation.location.keywords.keyword.knowledgeGraph.typeHierarchy"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_TEXT = "enriched.url.enrichedTitle.relations.relation.temporal.text"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_TYPE = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_VALUE = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.value"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_START = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.start"; + public const string ENRICHED_URL_ENRICHEDTITLE_RELATIONS_RELATION_TEMPORAL_DECODED_END = "enriched.url.enrichedTitle.relations.relation.temporal.decoded.end"; + public const string ENRICHED_URL_ENRICHEDTITLE_DOCSENTIMENT_TYPE = "enriched.url.enrichedTitle.docSentiment.type"; + public const string ENRICHED_URL_ENRICHEDTITLE_DOCSENTIMENT_SCORE = "enriched.url.enrichedTitle.docSentiment.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_DOCSENTIMENT_MIXED = "enriched.url.enrichedTitle.docSentiment.mixed"; + public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY = "enriched.url.enrichedTitle.taxonomy"; + public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY_TAXONOMY__LABEL = "enriched.url.enrichedTitle.taxonomy.taxonomy_.label"; + public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY_TAXONOMY__SCORE = "enriched.url.enrichedTitle.taxonomy.taxonomy_.score"; + public const string ENRICHED_URL_ENRICHEDTITLE_TAXONOMY_TAXONOMY__CONFIDENT = "enriched.url.enrichedTitle.taxonomy.taxonomy_.confident"; + } + #endregion } diff --git a/Scripts/Services/Conversation-Experimental/Conversation-Experimental.cs b/Scripts/Services/Conversation-Experimental/Conversation-Experimental.cs index 603669e6f..139bca8d0 100755 --- a/Scripts/Services/Conversation-Experimental/Conversation-Experimental.cs +++ b/Scripts/Services/Conversation-Experimental/Conversation-Experimental.cs @@ -26,179 +26,179 @@ namespace IBM.Watson.DeveloperCloud.Services.ConversationExperimental.v1 { - /// - /// This class wraps the Watson Experimental Conversation service. - /// Experimental Conversation Service - /// - public class ConversationExperimental : IWatsonService - { - #region Public Types - /// - /// The callback for GetWorkspaces(). - /// - public delegate void OnGetWorkspaces(Workspaces workspaces); - /// - /// The callback for Message(). - /// - /// - public delegate void OnMessageCallback(bool success); - /// - /// The callback delegate for the Converse() function. - /// - /// The response object to a call to Converse(). - public delegate void OnMessage(MessageResponse resp); - - #endregion - - #region Public Properties - #endregion - - #region Private Data - private const string SERVICE_ID = "ConversationExperimentalV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Message - private const string SERVICE_MESSAGE = "/v1/workspaces"; - /// - /// Message the specified workspaceId, input and callback. - /// - /// Workspace identifier. - /// Input. - /// Callback. - public bool Message(string workspaceId, string input, OnMessage callback) - { - if(string.IsNullOrEmpty(workspaceId)) - throw new ArgumentNullException("workspaceId"); - if(string.IsNullOrEmpty(input)) - throw new ArgumentNullException("input"); - if(callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_MESSAGE); - if(connector == null) - return false; - - string reqJson = "{{\"input\": {{\"text\": \"{0}\"}}}}"; - string reqString = string.Format(reqJson, input); - - MessageReq req = new MessageReq(); - req.Callback = callback; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Parameters["version"] = Version.VERSION; - req.Function = "/" + workspaceId + "/message"; - req.Send = Encoding.UTF8.GetBytes(reqString); - req.OnResponse = MessageResp; - - return connector.Send(req); - } - - private class MessageReq : RESTConnector.Request - { - public OnMessage Callback { get; set; } - } - - private void MessageResp(RESTConnector.Request req, RESTConnector.Response resp) - { - MessageResponse response = new MessageResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Conversation", "MessageResp Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((MessageReq)req).Callback != null) - ((MessageReq)req).Callback(resp.Success ? response : null); - } - #endregion - - #region IWatsonService implementation - /// - public string GetServiceID() - { - return SERVICE_ID; - } - - /// - public void GetServiceStatus(ServiceStatus callback) - { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - { - if (callback != null && callback.Target != null) - { - callback(SERVICE_ID, false); - } - } - } - - private class CheckServiceStatus + /// + /// This class wraps the Watson Experimental Conversation service. + /// Experimental Conversation Service + /// + public class ConversationExperimental : IWatsonService + { + #region Public Types + /// + /// The callback for GetWorkspaces(). + /// + public delegate void OnGetWorkspaces(Workspaces workspaces); + /// + /// The callback for Message(). + /// + /// + public delegate void OnMessageCallback(bool success); + /// + /// The callback delegate for the Converse() function. + /// + /// The response object to a call to Converse(). + public delegate void OnMessage(MessageResponse resp); + + #endregion + + #region Public Properties + #endregion + + #region Private Data + private const string SERVICE_ID = "ConversationExperimentalV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Message + private const string SERVICE_MESSAGE = "/v1/workspaces"; + /// + /// Message the specified workspaceId, input and callback. + /// + /// Workspace identifier. + /// Input. + /// Callback. + public bool Message(string workspaceId, string input, OnMessage callback) + { + if (string.IsNullOrEmpty(workspaceId)) + throw new ArgumentNullException("workspaceId"); + if (string.IsNullOrEmpty(input)) + throw new ArgumentNullException("input"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_MESSAGE); + if (connector == null) + return false; + + string reqJson = "{{\"input\": {{\"text\": \"{0}\"}}}}"; + string reqString = string.Format(reqJson, input); + + MessageReq req = new MessageReq(); + req.Callback = callback; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Parameters["version"] = Version.VERSION; + req.Function = "/" + workspaceId + "/message"; + req.Send = Encoding.UTF8.GetBytes(reqString); + req.OnResponse = MessageResp; + + return connector.Send(req); + } + + private class MessageReq : RESTConnector.Request + { + public OnMessage Callback { get; set; } + } + + private void MessageResp(RESTConnector.Request req, RESTConnector.Response resp) + { + MessageResponse response = new MessageResponse(); + if (resp.Success) + { + try { - private ConversationExperimental m_Service = null; - private ServiceStatus m_Callback = null; - private int m_ConversationCount = 0; - - public CheckServiceStatus(ConversationExperimental service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - string customServiceID = Config.Instance.GetVariableValue(SERVICE_ID + "_ID"); - - //If custom classifierID is defined then we are using it to check the service health - if (!string.IsNullOrEmpty(customServiceID)) - { - - if (!m_Service.Message(customServiceID, "Ping", OnMessage)) - OnFailure("Failed to invoke Converse()."); - else - m_ConversationCount += 1; - } - else - { - OnFailure("Please define a workspace variable in config.json (" + SERVICE_ID + "_ID)"); - } - } - - private void OnMessage(MessageResponse resp) - { - if (m_ConversationCount > 0) - { - m_ConversationCount -= 1; - if (resp != null) - { - if (m_ConversationCount == 0 && m_Callback != null && m_Callback.Target != null) - m_Callback(SERVICE_ID, true); - } - else - OnFailure("ConverseResponse is null."); - } - } - - private void OnFailure(string msg) - { - Log.Error("Dialog", msg); - m_Callback(SERVICE_ID, false); - m_ConversationCount = 0; - } - }; - #endregion - } + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Conversation", "MessageResp Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((MessageReq)req).Callback != null) + ((MessageReq)req).Callback(resp.Success ? response : null); + } + #endregion + + #region IWatsonService implementation + /// + public string GetServiceID() + { + return SERVICE_ID; + } + + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + { + if (callback != null && callback.Target != null) + { + callback(SERVICE_ID, false); + } + } + } + + private class CheckServiceStatus + { + private ConversationExperimental m_Service = null; + private ServiceStatus m_Callback = null; + private int m_ConversationCount = 0; + + public CheckServiceStatus(ConversationExperimental service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + string customServiceID = Config.Instance.GetVariableValue(SERVICE_ID + "_ID"); + + //If custom classifierID is defined then we are using it to check the service health + if (!string.IsNullOrEmpty(customServiceID)) + { + + if (!m_Service.Message(customServiceID, "Ping", OnMessage)) + OnFailure("Failed to invoke Converse()."); + else + m_ConversationCount += 1; + } + else + { + OnFailure("Please define a workspace variable in config.json (" + SERVICE_ID + "_ID)"); + } + } + + private void OnMessage(MessageResponse resp) + { + if (m_ConversationCount > 0) + { + m_ConversationCount -= 1; + if (resp != null) + { + if (m_ConversationCount == 0 && m_Callback != null && m_Callback.Target != null) + m_Callback(SERVICE_ID, true); + } + else + OnFailure("ConverseResponse is null."); + } + } + + private void OnFailure(string msg) + { + Log.Error("Dialog", msg); + m_Callback(SERVICE_ID, false); + m_ConversationCount = 0; + } + }; + #endregion + } } diff --git a/Scripts/Services/Conversation-Experimental/DataModels.cs b/Scripts/Services/Conversation-Experimental/DataModels.cs index 01147f321..e13faab59 100755 --- a/Scripts/Services/Conversation-Experimental/DataModels.cs +++ b/Scripts/Services/Conversation-Experimental/DataModels.cs @@ -18,392 +18,392 @@ namespace IBM.Watson.DeveloperCloud.Services.ConversationExperimental.v1 { - #region Workspaces - /// - /// Workspaces. - /// - [fsObject] - public class Workspaces - { - /// - /// Gets or sets the workspaces. - /// - /// The workspaces. - public Workspace[] workspaces { get; set; } - } + #region Workspaces + /// + /// Workspaces. + /// + [fsObject] + public class Workspaces + { + /// + /// Gets or sets the workspaces. + /// + /// The workspaces. + public Workspace[] workspaces { get; set; } + } - /// - /// This data class is contained by Workspaces, it represents a single workspace. - /// - [fsObject] - public class Workspace - { - /// - /// Gets or sets the workspace identifier. - /// - /// The ID of the workspace. - public string workspace_id { get; set; } - /// - /// Gets or sets the date created - /// - /// The date created. - public string created { get; set; } - /// - /// Gets or sets the description of the workspace - /// - /// The description of the workspace. - public string description { get; set; } - /// - /// Gets or sets the name of the workspace. - /// - /// The name of the workspace. - public string name { get; set; } - /// - /// Gets or sets the language. - /// - /// The language of the workspace. - public string language { get; set; } - /// - /// Gets or sets the status. - /// - /// The status. - public string status { get; set; } - /// - /// Gets or sets the metadata. - /// - /// The metadata. - public object metadata { get; set; } - } - - #endregion + /// + /// This data class is contained by Workspaces, it represents a single workspace. + /// + [fsObject] + public class Workspace + { + /// + /// Gets or sets the workspace identifier. + /// + /// The ID of the workspace. + public string workspace_id { get; set; } + /// + /// Gets or sets the date created + /// + /// The date created. + public string created { get; set; } + /// + /// Gets or sets the description of the workspace + /// + /// The description of the workspace. + public string description { get; set; } + /// + /// Gets or sets the name of the workspace. + /// + /// The name of the workspace. + public string name { get; set; } + /// + /// Gets or sets the language. + /// + /// The language of the workspace. + public string language { get; set; } + /// + /// Gets or sets the status. + /// + /// The status. + public string status { get; set; } + /// + /// Gets or sets the metadata. + /// + /// The metadata. + public object metadata { get; set; } + } - #region Message - /// - /// Message response. - /// - [fsObject] - public class MessageResponse - { - /// - /// Gets or sets the intents. - /// - /// The intents. - public MessageIntent[] intents { get; set; } - /// - /// Gets or sets the entities. - /// - /// The entities. - public EntityExample[] entities { get; set; } - /// - /// Gets or sets the output. - /// - /// The output. - public Output output { get; set; } - /// - /// Gets or sets the context. - /// - /// The context. - public object context { get; set; } - } - #endregion + #endregion - #region Intent - /// - /// Intents. - /// - [fsObject] - public class Intents - { - /// - /// Gets or sets the intents. - /// - /// The intents. - public Intent[] intents { get; set; } - } + #region Message + /// + /// Message response. + /// + [fsObject] + public class MessageResponse + { + /// + /// Gets or sets the intents. + /// + /// The intents. + public MessageIntent[] intents { get; set; } + /// + /// Gets or sets the entities. + /// + /// The entities. + public EntityExample[] entities { get; set; } + /// + /// Gets or sets the output. + /// + /// The output. + public Output output { get; set; } + /// + /// Gets or sets the context. + /// + /// The context. + public object context { get; set; } + } + #endregion - /// - /// This data class is contained by Intents. It represents a single intent. - /// - [fsObject] - public class Intent - { - /// - /// Gets or sets the intent. - /// - /// The intent. - public string intent { get; set; } - /// - /// Gets or sets the created. - /// - /// The created. - public string created { get;set; } - /// - /// Gets or sets the description. - /// - /// The description. - public string description { get; set; } - } + #region Intent + /// + /// Intents. + /// + [fsObject] + public class Intents + { + /// + /// Gets or sets the intents. + /// + /// The intents. + public Intent[] intents { get; set; } + } - /// - /// Intent Examples. - /// - [fsObject] - public class Examples - { - /// - /// Gets or sets the examples. - /// - /// The examples. - public Example[] examples { get; set; } - } + /// + /// This data class is contained by Intents. It represents a single intent. + /// + [fsObject] + public class Intent + { + /// + /// Gets or sets the intent. + /// + /// The intent. + public string intent { get; set; } + /// + /// Gets or sets the created. + /// + /// The created. + public string created { get; set; } + /// + /// Gets or sets the description. + /// + /// The description. + public string description { get; set; } + } - /// - /// This class is contained by IntentExamples. It represents a single IntentExample. - /// - [fsObject] - public class Example - { - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set; } - /// - /// Gets or sets the entities. - /// - /// The entities. - public EntityExample entities { get; set; } - } + /// + /// Intent Examples. + /// + [fsObject] + public class Examples + { + /// + /// Gets or sets the examples. + /// + /// The examples. + public Example[] examples { get; set; } + } - /// - /// Entity example. - /// - [fsObject] - public class EntityExample - { - /// - /// Gets or sets the entity. - /// - /// The entity. - public string entity { get; set; } - /// - /// Gets or sets the value. - /// - /// The value. - public string value { get; set; } - /// - /// Gets or sets the location. - /// - /// The location. - public int[] location { get; set; } - } - #endregion + /// + /// This class is contained by IntentExamples. It represents a single IntentExample. + /// + [fsObject] + public class Example + { + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + /// + /// Gets or sets the entities. + /// + /// The entities. + public EntityExample entities { get; set; } + } - #region Entities - /// - /// Entities. - /// - [fsObject] - public class Entities - { - /// - /// Gets or sets the entities. - /// - /// The entities. - public Entity[] entities { get; set; } - } + /// + /// Entity example. + /// + [fsObject] + public class EntityExample + { + /// + /// Gets or sets the entity. + /// + /// The entity. + public string entity { get; set; } + /// + /// Gets or sets the value. + /// + /// The value. + public string value { get; set; } + /// + /// Gets or sets the location. + /// + /// The location. + public int[] location { get; set; } + } + #endregion - /// - /// This class is contained by Entities. It represents a single entity. - /// - [fsObject] - public class Entity - { - /// - /// Gets or sets the entity. - /// - /// The entity. - public string entity { get; set; } - /// - /// Gets or sets the description. - /// - /// The description. - public string description { get; set; } - /// - /// Gets or sets the created. - /// - /// The created. - public string created { get; set; } - /// - /// Gets or sets a value indicating whether this is an open list. - /// - /// true if open list; otherwise, false. - public bool open_list { get; set; } - /// - /// Gets or sets the tags. - /// - /// The tags. - public string[] tags { get; set; } - } + #region Entities + /// + /// Entities. + /// + [fsObject] + public class Entities + { + /// + /// Gets or sets the entities. + /// + /// The entities. + public Entity[] entities { get; set; } + } - /// - /// Entity Values. - /// - [fsObject] - public class Values - { - /// - /// Gets or sets the value. - /// - /// The value. - public string value { get; set; } - /// - /// Gets or sets the synonyms. - /// - /// The synonyms. - public string[] synonyms { get; set; } - /// - /// Gets or sets the metadata. - /// - /// The metadata. - public object metadata { get; set; } - } - #endregion + /// + /// This class is contained by Entities. It represents a single entity. + /// + [fsObject] + public class Entity + { + /// + /// Gets or sets the entity. + /// + /// The entity. + public string entity { get; set; } + /// + /// Gets or sets the description. + /// + /// The description. + public string description { get; set; } + /// + /// Gets or sets the created. + /// + /// The created. + public string created { get; set; } + /// + /// Gets or sets a value indicating whether this is an open list. + /// + /// true if open list; otherwise, false. + public bool open_list { get; set; } + /// + /// Gets or sets the tags. + /// + /// The tags. + public string[] tags { get; set; } + } - #region Dialog Nodes - /// - /// The Dialog nodes. - /// - [fsObject] - public class DialogNodes - { - /// - /// Gets or sets the dialog nodes. - /// - /// The dialog nodes. - public DialogNode[] dialog_nodes { get; set; } - } + /// + /// Entity Values. + /// + [fsObject] + public class Values + { + /// + /// Gets or sets the value. + /// + /// The value. + public string value { get; set; } + /// + /// Gets or sets the synonyms. + /// + /// The synonyms. + public string[] synonyms { get; set; } + /// + /// Gets or sets the metadata. + /// + /// The metadata. + public object metadata { get; set; } + } + #endregion - /// - /// This class is contained in DialogNodes. It represents a single DialogNode. - /// - [fsObject] - public class DialogNode - { - /// - /// Gets or sets the dialog node. - /// - /// The dialog node. - public string dialog_node { get; set; } - /// - /// Gets or sets the description. - /// - /// The description. - public string description { get; set; } - /// - /// Gets or sets the created. - /// - /// The created. - public string created { get; set; } - /// - /// Gets or sets the conditions. - /// - /// The conditions. - public string conditions { get; set; } - /// - /// Gets or sets the parent. - /// - /// The parent. - public string parent { get; set; } - /// - /// Gets or sets the previous sibling. - /// - /// The previous sibling. - public string previous_sibling { get; set; } - /// - /// Gets or sets the output. - /// - /// The output. - public Output output { get; set; } - /// - /// Gets or sets the context. - /// - /// The context. - public object context { get; set; } - /// - /// Gets or sets the go to. - /// - /// The go to. - public GoTo go_to { get; set; } - } - #endregion + #region Dialog Nodes + /// + /// The Dialog nodes. + /// + [fsObject] + public class DialogNodes + { + /// + /// Gets or sets the dialog nodes. + /// + /// The dialog nodes. + public DialogNode[] dialog_nodes { get; set; } + } - #region Common - /// - /// This class is contained by MessageIntents, it represents a single MessageIntent. - /// - [fsObject] - public class MessageIntent - { - /// - /// Gets or sets the intent. - /// - /// The intent. - public string intent { get; set; } - /// - /// Gets or sets the confidence. - /// - /// The confidence. - public double confidence { get; set; } - } + /// + /// This class is contained in DialogNodes. It represents a single DialogNode. + /// + [fsObject] + public class DialogNode + { + /// + /// Gets or sets the dialog node. + /// + /// The dialog node. + public string dialog_node { get; set; } + /// + /// Gets or sets the description. + /// + /// The description. + public string description { get; set; } + /// + /// Gets or sets the created. + /// + /// The created. + public string created { get; set; } + /// + /// Gets or sets the conditions. + /// + /// The conditions. + public string conditions { get; set; } + /// + /// Gets or sets the parent. + /// + /// The parent. + public string parent { get; set; } + /// + /// Gets or sets the previous sibling. + /// + /// The previous sibling. + public string previous_sibling { get; set; } + /// + /// Gets or sets the output. + /// + /// The output. + public Output output { get; set; } + /// + /// Gets or sets the context. + /// + /// The context. + public object context { get; set; } + /// + /// Gets or sets the go to. + /// + /// The go to. + public GoTo go_to { get; set; } + } + #endregion - /// - /// The output text of the conversation. - /// - [fsObject] - public class Output - { - /// - /// Gets or sets the text. - /// - /// The output text. - public string text { get; set; } - } + #region Common + /// + /// This class is contained by MessageIntents, it represents a single MessageIntent. + /// + [fsObject] + public class MessageIntent + { + /// + /// Gets or sets the intent. + /// + /// The intent. + public string intent { get; set; } + /// + /// Gets or sets the confidence. + /// + /// The confidence. + public double confidence { get; set; } + } - /// - /// Go to. - /// - [fsObject] - public class GoTo - { - /// - /// Gets or sets the dialog node. - /// - /// The dialog node. - public string dialog_node { get; set; } - /// - /// Gets or sets the selector. - /// - /// The selector. - public string selector { get; set; } - /// - /// Gets or sets a value indicating whether this returns. - /// - /// true if m return; otherwise, false. - public bool m_return { get; set; } - } - #endregion + /// + /// The output text of the conversation. + /// + [fsObject] + public class Output + { + /// + /// Gets or sets the text. + /// + /// The output text. + public string text { get; set; } + } - /// - /// The conversation service version. - /// - #region Version - public class Version - { - /// - /// The version. - /// - public const string VERSION = "2016-05-19"; - } - #endregion + /// + /// Go to. + /// + [fsObject] + public class GoTo + { + /// + /// Gets or sets the dialog node. + /// + /// The dialog node. + public string dialog_node { get; set; } + /// + /// Gets or sets the selector. + /// + /// The selector. + public string selector { get; set; } + /// + /// Gets or sets a value indicating whether this returns. + /// + /// true if m return; otherwise, false. + public bool m_return { get; set; } + } + #endregion + + /// + /// The conversation service version. + /// + #region Version + public class Version + { + /// + /// The version. + /// + public const string VERSION = "2016-05-19"; + } + #endregion } diff --git a/Scripts/Services/Conversation/Conversation.cs b/Scripts/Services/Conversation/Conversation.cs index 29dc833c0..c98afc9b7 100755 --- a/Scripts/Services/Conversation/Conversation.cs +++ b/Scripts/Services/Conversation/Conversation.cs @@ -26,223 +26,223 @@ namespace IBM.Watson.DeveloperCloud.Services.Conversation.v1 { - /// - /// This class wraps the Watson Conversation service. - /// Conversation Service - /// - public class Conversation : IWatsonService - { - #region Public Types - #endregion - - #region Public Properties - #endregion - - #region Private Data - private const string SERVICE_ID = "ConversationV1"; - private const string SERVICE_MESSAGE = "/v1/workspaces"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Message - /// - /// The callback delegate for the Message() function. - /// - /// The response object to a call to Message(). - public delegate void OnMessage(MessageResponse resp, string customData); - - /// - /// Message the specified workspaceId, input and callback. - /// - /// Workspace identifier. - /// Input. - /// Callback. - /// Custom data. - public bool Message(OnMessage callback, string workspaceID, string input, string customData = default(string)) - { - if(string.IsNullOrEmpty(workspaceID)) - throw new ArgumentNullException("workspaceId"); - if(string.IsNullOrEmpty(input)) - throw new ArgumentNullException("input"); - if(callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_MESSAGE); - if(connector == null) - return false; - - string reqJson = "{{\"input\": {{\"text\": \"{0}\"}}}}"; - string reqString = string.Format(reqJson, input); - - MessageReq req = new MessageReq(); - req.Callback = callback; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Parameters["version"] = Version.VERSION; - req.Function = "/" + workspaceID + "/message"; - req.Data = customData; - req.Send = Encoding.UTF8.GetBytes(reqString); - req.OnResponse = MessageResp; - - return connector.Send(req); - } - - /// - /// Message the specified workspaceId, input and callback. - /// - /// Callback. - /// Workspace identifier. - /// Message request object. - /// Custom data. - /// - public bool Message(OnMessage callback, string workspaceID, MessageRequest messageRequest, string customData = default(string)) + /// + /// This class wraps the Watson Conversation service. + /// Conversation Service + /// + public class Conversation : IWatsonService + { + #region Public Types + #endregion + + #region Public Properties + #endregion + + #region Private Data + private const string SERVICE_ID = "ConversationV1"; + private const string SERVICE_MESSAGE = "/v1/workspaces"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Message + /// + /// The callback delegate for the Message() function. + /// + /// The response object to a call to Message(). + public delegate void OnMessage(MessageResponse resp, string customData); + + /// + /// Message the specified workspaceId, input and callback. + /// + /// Workspace identifier. + /// Input. + /// Callback. + /// Custom data. + public bool Message(OnMessage callback, string workspaceID, string input, string customData = default(string)) + { + if (string.IsNullOrEmpty(workspaceID)) + throw new ArgumentNullException("workspaceId"); + if (string.IsNullOrEmpty(input)) + throw new ArgumentNullException("input"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_MESSAGE); + if (connector == null) + return false; + + string reqJson = "{{\"input\": {{\"text\": \"{0}\"}}}}"; + string reqString = string.Format(reqJson, input); + + MessageReq req = new MessageReq(); + req.Callback = callback; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Parameters["version"] = Version.VERSION; + req.Function = "/" + workspaceID + "/message"; + req.Data = customData; + req.Send = Encoding.UTF8.GetBytes(reqString); + req.OnResponse = MessageResp; + + return connector.Send(req); + } + + /// + /// Message the specified workspaceId, input and callback. + /// + /// Callback. + /// Workspace identifier. + /// Message request object. + /// Custom data. + /// + public bool Message(OnMessage callback, string workspaceID, MessageRequest messageRequest, string customData = default(string)) + { + if (string.IsNullOrEmpty(workspaceID)) + throw new ArgumentNullException("workspaceId"); + if (string.IsNullOrEmpty(messageRequest.input.text)) + throw new ArgumentNullException("messageRequest.input.text"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_MESSAGE); + if (connector == null) + return false; + + fsData data; + sm_Serializer.TrySerialize(messageRequest.GetType(), messageRequest, out data).AssertSuccessWithoutWarnings(); + string reqString = fsJsonPrinter.CompressedJson(data); + + MessageReq req = new MessageReq(); + req.Callback = callback; + req.MessageRequest = messageRequest; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Parameters["version"] = Version.VERSION; + req.Function = "/" + workspaceID + "/message"; + req.Data = customData; + req.Send = Encoding.UTF8.GetBytes(reqString); + req.OnResponse = MessageResp; + + return connector.Send(req); + } + + + private class MessageReq : RESTConnector.Request + { + public OnMessage Callback { get; set; } + public MessageRequest MessageRequest { get; set; } + public string Data { get; set; } + } + + private void MessageResp(RESTConnector.Request req, RESTConnector.Response resp) + { + MessageResponse response = new MessageResponse(); + if (resp.Success) + { + try { - if (string.IsNullOrEmpty(workspaceID)) - throw new ArgumentNullException("workspaceId"); - if(string.IsNullOrEmpty(messageRequest.input.text)) - throw new ArgumentNullException("messageRequest.input.text"); - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_MESSAGE); - if (connector == null) - return false; - - fsData data; - sm_Serializer.TrySerialize(messageRequest.GetType(), messageRequest, out data).AssertSuccessWithoutWarnings(); - string reqString = fsJsonPrinter.CompressedJson(data); - - MessageReq req = new MessageReq(); - req.Callback = callback; - req.MessageRequest = messageRequest; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Parameters["version"] = Version.VERSION; - req.Function = "/" + workspaceID + "/message"; - req.Data = customData; - req.Send = Encoding.UTF8.GetBytes(reqString); - req.OnResponse = MessageResp; - - return connector.Send(req); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } + catch (Exception e) + { + Log.Error("Conversation", "MessageResp Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((MessageReq)req).Callback != null) + ((MessageReq)req).Callback(resp.Success ? response : null, ((MessageReq)req).Data); + } + #endregion + + #region Intents + #endregion + + #region Entities + #endregion + + #region Dialog Nodes + #endregion + + #region IWatsonService implementation + /// + public string GetServiceID() + { + return SERVICE_ID; + } + + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + { + if (callback != null && callback.Target != null) + { + callback(SERVICE_ID, false); + } + } + } + private class CheckServiceStatus + { + private Conversation m_Service = null; + private ServiceStatus m_Callback = null; + private int m_ConversationCount = 0; - private class MessageReq : RESTConnector.Request - { - public OnMessage Callback { get; set; } - public MessageRequest MessageRequest { get; set; } - public string Data { get; set; } - } - - private void MessageResp(RESTConnector.Request req, RESTConnector.Response resp) - { - MessageResponse response = new MessageResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Conversation", "MessageResp Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((MessageReq)req).Callback != null) - ((MessageReq)req).Callback(resp.Success ? response : null, ((MessageReq)req).Data); - } - #endregion - - #region Intents - #endregion - - #region Entities - #endregion - - #region Dialog Nodes - #endregion - - #region IWatsonService implementation - /// - public string GetServiceID() - { - return SERVICE_ID; - } - - /// - public void GetServiceStatus(ServiceStatus callback) - { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - { - if (callback != null && callback.Target != null) - { - callback(SERVICE_ID, false); - } - } - } - - private class CheckServiceStatus + public CheckServiceStatus(Conversation service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + string customServiceID = Config.Instance.GetVariableValue(SERVICE_ID + "_ID"); + + //If custom classifierID is defined then we are using it to check the service health + if (!string.IsNullOrEmpty(customServiceID)) { - private Conversation m_Service = null; - private ServiceStatus m_Callback = null; - private int m_ConversationCount = 0; - - public CheckServiceStatus(Conversation service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - string customServiceID = Config.Instance.GetVariableValue(SERVICE_ID + "_ID"); - - //If custom classifierID is defined then we are using it to check the service health - if (!string.IsNullOrEmpty(customServiceID)) - { - - if (!m_Service.Message(OnMessage, customServiceID, "Ping", "Ping")) - OnFailure("Failed to invoke Converse()."); - else - m_ConversationCount += 1; - } - else - { - OnFailure("Please define a workspace variable in config.json (" + SERVICE_ID + "_ID)"); - } - } - - private void OnMessage(MessageResponse resp, string customData) - { - if (m_ConversationCount > 0) - { - m_ConversationCount -= 1; - if (resp != null) - { - if (m_ConversationCount == 0 && m_Callback != null && m_Callback.Target != null) - m_Callback(SERVICE_ID, true); - } - else - OnFailure("ConverseResponse is null."); - } - } - - private void OnFailure(string msg) - { - Log.Error("Dialog", msg); - m_Callback(SERVICE_ID, false); - m_ConversationCount = 0; - } - }; - #endregion - } + + if (!m_Service.Message(OnMessage, customServiceID, "Ping", "Ping")) + OnFailure("Failed to invoke Converse()."); + else + m_ConversationCount += 1; + } + else + { + OnFailure("Please define a workspace variable in config.json (" + SERVICE_ID + "_ID)"); + } + } + + private void OnMessage(MessageResponse resp, string customData) + { + if (m_ConversationCount > 0) + { + m_ConversationCount -= 1; + if (resp != null) + { + if (m_ConversationCount == 0 && m_Callback != null && m_Callback.Target != null) + m_Callback(SERVICE_ID, true); + } + else + OnFailure("ConverseResponse is null."); + } + } + + private void OnFailure(string msg) + { + Log.Error("Dialog", msg); + m_Callback(SERVICE_ID, false); + m_ConversationCount = 0; + } + }; + #endregion + } } diff --git a/Scripts/Services/Conversation/DataModels.cs b/Scripts/Services/Conversation/DataModels.cs index 3124de7be..a9ac5e39d 100755 --- a/Scripts/Services/Conversation/DataModels.cs +++ b/Scripts/Services/Conversation/DataModels.cs @@ -18,291 +18,292 @@ namespace IBM.Watson.DeveloperCloud.Services.Conversation.v1 { + /// + /// The mesage response. + /// + #region MessageResponse + [fsObject] + public class MessageResponse + { /// - /// The mesage response. + /// The input text. /// - #region MessageResponse - [fsObject] - public class MessageResponse - { - /// - /// The input text. - /// - public InputData input { get; set; } - /// - /// The context objext. - /// - public Context context { get; set; } - /// - /// Terms from the request that are identified as entities. - /// - public EntityResponse[] entities { get; set; } - /// - /// Terms from the request that are identified as intents. - /// - public Intent[] intents { get; set; } - /// - /// Output logs. - /// - public OutputData output { get; set; } - } - + public InputData input { get; set; } /// - /// The entity object. + /// The context objext. /// - [fsObject] - public class EntityResponse - { - /// - /// The entity name. - /// - public string entity { get; set; } - /// - /// The entity location. - /// - public int[] location { get; set; } - /// - /// The entity value. - /// - public string value { get; set; } - } + public Context context { get; set; } + /// + /// Terms from the request that are identified as entities. + /// + public EntityResponse[] entities { get; set; } + /// + /// Terms from the request that are identified as intents. + /// + public Intent[] intents { get; set; } + /// + /// Output logs. + /// + public OutputData output { get; set; } + } + /// + /// The entity object. + /// + [fsObject] + public class EntityResponse + { /// - /// The resultant intent. + /// The entity name. /// - [fsObject] - public class Intent - { - /// - /// The intent. - /// - public string intent { get; set; } - /// - /// The confidence. - /// - public float confidence { get; set; } - } + public string entity { get; set; } + /// + /// The entity location. + /// + public int[] location { get; set; } + /// + /// The entity value. + /// + public string value { get; set; } + } + /// + /// The resultant intent. + /// + [fsObject] + public class Intent + { /// - /// The Output data. + /// The intent. /// - [fsObject] - public class OutputData - { - /// - /// Log messages. - /// - public LogMessageResponse[] log_messages { get; set; } - /// - /// Output text. - /// - public string[] text { get; set; } - /// - /// The nodes that were visited. - /// - public string[] nodes_visited { get; set; } - } + public string intent { get; set; } + /// + /// The confidence. + /// + public float confidence { get; set; } + } + /// + /// The Output data. + /// + [fsObject] + public class OutputData + { /// - /// The log message object. + /// Log messages. /// - [fsObject] - public class LogMessageResponse - { - /// - /// The log level. - /// - public string level { get; set; } - /// - /// The log message. - /// - public string msg { get; set; } - } - #endregion + public LogMessageResponse[] log_messages { get; set; } + /// + /// Output text. + /// + public string[] text { get; set; } + /// + /// The nodes that were visited. + /// + public string[] nodes_visited { get; set; } + } - #region Message Request + /// + /// The log message object. + /// + [fsObject] + public class LogMessageResponse + { /// - /// The user's input, with optional intents, entities, and other properties from the response. + /// The log level. /// - [fsObject] - public class MessageRequest - { - ///// - ///// Default constructor. - ///// - //public MessageRequest() - //{ - // input = new InputData(); - // context = new Context(); - //} + public string level { get; set; } + /// + /// The log message. + /// + public string msg { get; set; } + } + #endregion - /// - /// The input text. - /// - public InputData input { get; set; } - /// - /// Whether to return more than one intent. Set to true to return all matching intents. - /// - public bool alternate_intents { get; set; } - /// - /// State information about the conversation. - /// - public Context context { get; set; } + #region Message Request + /// + /// The user's input, with optional intents, entities, and other properties from the response. + /// + [fsObject] + public class MessageRequest + { + ///// + ///// Default constructor. + ///// + //public MessageRequest() + //{ + // input = new InputData(); + // context = new Context(); + //} - /// - /// Creates the input object and sets the InputText. - /// - public string InputText - { - get { - if (input == null) - { - input = new InputData(); - return ""; - } - else - { - return input.text; - } - } - set - { - if (input == null) - input = new InputData(); + /// + /// The input text. + /// + public InputData input { get; set; } + /// + /// Whether to return more than one intent. Set to true to return all matching intents. + /// + public bool alternate_intents { get; set; } + /// + /// State information about the conversation. + /// + public Context context { get; set; } - input.text = value; - } + /// + /// Creates the input object and sets the InputText. + /// + public string InputText + { + get + { + if (input == null) + { + input = new InputData(); + return ""; } - - /// - /// Gets and sets the input value and creates the InputData object if it hasn't been created. - /// - public InputData InputData - { - get { return input != null ? input : input = new InputData(); } - set - { - if (input == null) - input = new InputData(); - - input = value; - } - } - - /// - /// Creates the Context object and sets the conversation_id. - /// - public string conversationID + else { - get { return context != null ? context.conversation_id : null; } - set - { - if (context == null) - context = new Context(); - - context.conversation_id = value; - } + return input.text; } + } + set + { + if (input == null) + input = new InputData(); - /// - /// Gets and sets the context value and creates the Context object if it hasn't been created. - /// - public Context ContextData - { - get { return context != null ? context : context = new Context(); } - set - { - if (context == null) - context = new Context(); - - context = value; - } - } + input.text = value; + } } - #endregion - #region common /// - /// The input text. + /// Gets and sets the input value and creates the InputData object if it hasn't been created. /// - [fsObject] - public class InputData + public InputData InputData { - /// - /// The user's input. - /// - public string text { get; set; } + get { return input != null ? input : input = new InputData(); } + set + { + if (input == null) + input = new InputData(); + + input = value; + } } /// - /// Information about the conversation. + /// Creates the Context object and sets the conversation_id. /// - [fsObject] - public class Context + public string conversationID { - ///// - ///// Default constructor. - ///// - //public Context() - //{ - // system = new SystemResponse(); - //} - /// - /// The unique identifier of the conversation. - /// - public string conversation_id { get; set; } - /// - /// Information about the dialog - /// - public SystemResponse system { get; set; } - - /// - /// Creates the SystemResponse object and sets it. - /// - public SystemResponse SystemResponse - { - get { return system != null ? system : system = new SystemResponse(); } - set - { - if (system == null) - system = new SystemResponse(); + get { return context != null ? context.conversation_id : null; } + set + { + if (context == null) + context = new Context(); - system = value; - } - } - } + context.conversation_id = value; + } + } /// - /// Dialog information. + /// Gets and sets the context value and creates the Context object if it hasn't been created. /// - [fsObject] - public class SystemResponse + public Context ContextData { - /// - /// An array of dialog node IDs that are in focus in the conversation. - /// - public string[] dialog_stack { get; set; } - /// - /// The number of cycles of user input and response in this conversation. - /// - public int dialog_turn_counter { get; set; } - /// - /// The number of inputs in this conversation. This counter might be higher than the dialog_turn_counter counter when multiple inputs are needed before a response can be returned. - /// - public int dialog_request_counter { get; set; } + get { return context != null ? context : context = new Context(); } + set + { + if (context == null) + context = new Context(); + + context = value; + } } - #endregion + } + #endregion - #region Version + #region common + /// + /// The input text. + /// + [fsObject] + public class InputData + { /// - /// The conversation service version. + /// The user's input. /// - public class Version + public string text { get; set; } + } + + /// + /// Information about the conversation. + /// + [fsObject] + public class Context + { + ///// + ///// Default constructor. + ///// + //public Context() + //{ + // system = new SystemResponse(); + //} + /// + /// The unique identifier of the conversation. + /// + public string conversation_id { get; set; } + /// + /// Information about the dialog + /// + public SystemResponse system { get; set; } + + /// + /// Creates the SystemResponse object and sets it. + /// + public SystemResponse SystemResponse { - /// - /// The version. - /// - public const string VERSION = "2016-07-11"; + get { return system != null ? system : system = new SystemResponse(); } + set + { + if (system == null) + system = new SystemResponse(); + + system = value; + } } - #endregion + } + + /// + /// Dialog information. + /// + [fsObject] + public class SystemResponse + { + /// + /// An array of dialog node IDs that are in focus in the conversation. + /// + public string[] dialog_stack { get; set; } + /// + /// The number of cycles of user input and response in this conversation. + /// + public int dialog_turn_counter { get; set; } + /// + /// The number of inputs in this conversation. This counter might be higher than the dialog_turn_counter counter when multiple inputs are needed before a response can be returned. + /// + public int dialog_request_counter { get; set; } + } + #endregion + + #region Version + /// + /// The conversation service version. + /// + public class Version + { + /// + /// The version. + /// + public const string VERSION = "2016-07-11"; + } + #endregion } diff --git a/Scripts/Services/DeepQA/DataModels.cs b/Scripts/Services/DeepQA/DataModels.cs old mode 100644 new mode 100755 index 551b114c1..541e37376 --- a/Scripts/Services/DeepQA/DataModels.cs +++ b/Scripts/Services/DeepQA/DataModels.cs @@ -20,551 +20,551 @@ namespace IBM.Watson.DeveloperCloud.Services.DeepQA.v1 { - /// - /// The returned value. - /// - [fsObject] - public class Value - { - /// - /// The value. - /// - public string value { get; set; } - }; + /// + /// The returned value. + /// + [fsObject] + public class Value + { + /// + /// The value. + /// + public string value { get; set; } + }; - /// - /// The metadata of the answer. - /// - [fsObject] - public class MetaDataMap - { - /// - /// The original file. - /// - public string originalFile { get; set; } - /// - /// The title. - /// - public string title { get; set; } - /// - /// The corpus name. - /// - public string corpusName { get; set; } - /// - /// The file name. - /// - public string fileName { get; set; } - /// - /// The document number. - /// - public string DOCNO { get; set; } - /// - /// The corpus and document number. - /// - public string CorpusPlusDocno { get; set; } - }; + /// + /// The metadata of the answer. + /// + [fsObject] + public class MetaDataMap + { + /// + /// The original file. + /// + public string originalFile { get; set; } + /// + /// The title. + /// + public string title { get; set; } + /// + /// The corpus name. + /// + public string corpusName { get; set; } + /// + /// The file name. + /// + public string fileName { get; set; } + /// + /// The document number. + /// + public string DOCNO { get; set; } + /// + /// The corpus and document number. + /// + public string CorpusPlusDocno { get; set; } + }; - /// - /// The evidence of the answer. - /// - [fsObject] - public class Evidence - { - /// - /// The value. - /// - public string value { get; set; } - /// - /// The text. - /// - public string text { get; set; } - /// - /// The identifier. - /// - public string id { get; set; } - /// - /// The title. - /// - public string title { get; set; } - /// - /// The document. - /// - public string document { get; set; } - /// - /// The copyright. - /// - public string copyright { get; set; } - /// - /// The terms of use. - /// - public string termsOfUse { get; set; } - /// - /// The metadata map. - /// - public MetaDataMap metadataMap { get; set; } - }; + /// + /// The evidence of the answer. + /// + [fsObject] + public class Evidence + { + /// + /// The value. + /// + public string value { get; set; } + /// + /// The text. + /// + public string text { get; set; } + /// + /// The identifier. + /// + public string id { get; set; } + /// + /// The title. + /// + public string title { get; set; } + /// + /// The document. + /// + public string document { get; set; } + /// + /// The copyright. + /// + public string copyright { get; set; } + /// + /// The terms of use. + /// + public string termsOfUse { get; set; } + /// + /// The metadata map. + /// + public MetaDataMap metadataMap { get; set; } + }; - /// - /// Synonym of an answer. - /// - [fsObject] - public class Synonym + /// + /// Synonym of an answer. + /// + [fsObject] + public class Synonym + { + /// + /// Is the synonym chosen? + /// + public bool isChosen { get; set; } + /// + /// The synonym value. + /// + public string value { get; set; } + /// + /// The synonym weight. + /// + public double weight { get; set; } + }; + + /// + /// Synonym set. + /// + [fsObject] + public class SynSet + { + /// + /// The synset name. + /// + public string name { get; set; } + /// + /// The synonyms. + /// + public Synonym[] synSet { get; set; } + }; + + /// + /// Synonym list. + /// + [fsObject] + public class SynonymList + { + /// + /// The part of speech. + /// + public string partOfSpeech { get; set; } + /// + /// The valuse. + /// + public string value { get; set; } + /// + /// The lemma. + /// + public string lemma { get; set; } + /// + /// The synsets. + /// + public SynSet[] synSet { get; set; } + }; + + /// + /// The evidence request. + /// + [fsObject] + public class EvidenceRequest + { + /// + /// The items. + /// + public long items { get; set; } + /// + /// The profile. + /// + public string profile { get; set; } + }; + + /// + /// The answer. + /// + [fsObject] + public class Answer + { + /// + /// The answer identifier. + /// + public long id { get; set; } + /// + /// The answer text. + /// + public string text { get; set; } + /// + /// The pipeline. + /// + public string pipeline { get; set; } + /// + /// The formatted text. + /// + public string formattedText { get; set; } + /// + /// The confidence. + /// + public double confidence { get; set; } + /// + /// The evidence. + /// + public Evidence[] evidence { get; set; } + /// + /// The entity types. + /// + public string[] entityTypes { get; set; } + + private static string CleanInnerText(string text) { - /// - /// Is the synonym chosen? - /// - public bool isChosen { get; set; } - /// - /// The synonym value. - /// - public string value { get; set; } - /// - /// The synonym weight. - /// - public double weight { get; set; } - }; + text = text.Replace(" ", " "); + text = text.Replace("\\n", "\n"); + text = text.Replace("\\r", "\r"); + text = text.Replace("\\t", "\t"); + return text.Trim(new char[] { '\n', '\r', '\t', ' ' }); + } - /// - /// Synonym set. - /// + /// + /// Answer cell. + /// [fsObject] - public class SynSet + public class Cell { - /// - /// The synset name. - /// - public string name { get; set; } - /// - /// The synonyms. - /// - public Synonym[] synSet { get; set; } + /// + /// The cell value. + /// + public string Value { get; set; } + /// + /// The column span. + /// + public int ColSpan { get; set; } + /// + /// Is this cell highlighted? + /// + public bool Highlighted { get; set; } }; - /// - /// Synonym list. - /// + /// + /// Answer row. + /// [fsObject] - public class SynonymList + public class Row { - /// - /// The part of speech. - /// - public string partOfSpeech { get; set; } - /// - /// The valuse. - /// - public string value { get; set; } - /// - /// The lemma. - /// - public string lemma { get; set; } - /// - /// The synsets. - /// - public SynSet[] synSet { get; set; } + /// + /// The row columns. + /// + public Cell[] columns { get; set; } }; - /// - /// The evidence request. - /// + /// + /// Answer table. + /// [fsObject] - public class EvidenceRequest + public class Table { - /// - /// The items. - /// - public long items { get; set; } - /// - /// The profile. - /// - public string profile { get; set; } + /// + /// The table rows. + /// + public Row[] rows { get; set; } }; - /// - /// The answer. - /// - [fsObject] - public class Answer + /// + /// Helper function to extract all tables from the formatted answer + /// + /// An array of all tables found. + public Table[] ExtractTables(string answer) { - /// - /// The answer identifier. - /// - public long id { get; set; } - /// - /// The answer text. - /// - public string text { get; set; } - /// - /// The pipeline. - /// - public string pipeline { get; set; } - /// - /// The formatted text. - /// - public string formattedText { get; set; } - /// - /// The confidence. - /// - public double confidence { get; set; } - /// - /// The evidence. - /// - public Evidence[] evidence { get; set; } - /// - /// The entity types. - /// - public string[] entityTypes { get; set; } + if (!string.IsNullOrEmpty(formattedText)) + { + HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); + doc.LoadHtml(formattedText); - private static string CleanInnerText(string text) - { - text = text.Replace(" ", " "); - text = text.Replace("\\n", "\n"); - text = text.Replace("\\r", "\r"); - text = text.Replace("\\t", "\t"); - return text.Trim(new char[] { '\n', '\r', '\t', ' ' }); - } + if (doc.DocumentNode == null) + return null; + var table_nodes = doc.DocumentNode.SelectNodes("//table"); + if (table_nodes == null) + return null; - /// - /// Answer cell. - /// - [fsObject] - public class Cell + List tables = new List
(); + foreach (var table in table_nodes) { - /// - /// The cell value. - /// - public string Value { get; set; } - /// - /// The column span. - /// - public int ColSpan { get; set; } - /// - /// Is this cell highlighted? - /// - public bool Highlighted { get; set; } - }; + var row_nodes = table.SelectNodes("*/tr"); + if (row_nodes == null) + continue; - /// - /// Answer row. - /// - [fsObject] - public class Row - { - /// - /// The row columns. - /// - public Cell[] columns { get; set; } - }; + List rows = new List(); + foreach (var row in row_nodes) + { + var cell_nodes = row.SelectNodes("*/th|td"); + if (cell_nodes == null) + continue; - /// - /// Answer table. - /// - [fsObject] - public class Table - { - /// - /// The table rows. - /// - public Row[] rows { get; set; } - }; - - /// - /// Helper function to extract all tables from the formatted answer - /// - /// An array of all tables found. - public Table[] ExtractTables(string answer) - { - if (!string.IsNullOrEmpty(formattedText)) + List cells = new List(); + foreach (var cell in cell_nodes) { - HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); - doc.LoadHtml(formattedText); - - if (doc.DocumentNode == null) - return null; - var table_nodes = doc.DocumentNode.SelectNodes("//table"); - if (table_nodes == null) - return null; - - List
tables = new List
(); - foreach (var table in table_nodes) - { - var row_nodes = table.SelectNodes("*/tr"); - if (row_nodes == null) - continue; + string text = CleanInnerText(cell.InnerText); - List rows = new List(); - foreach (var row in row_nodes) - { - var cell_nodes = row.SelectNodes("*/th|td"); - if (cell_nodes == null) - continue; + int colspan = 1; + if (cell.Attributes.Contains("colspan")) + colspan = int.Parse(cell.Attributes["colspan"].Value); + bool bHighlighted = false; + if (text == answer) + bHighlighted = true; - List cells = new List(); - foreach (var cell in cell_nodes) - { - string text = CleanInnerText(cell.InnerText); - - int colspan = 1; - if (cell.Attributes.Contains("colspan")) - colspan = int.Parse(cell.Attributes["colspan"].Value); - bool bHighlighted = false; - if (text == answer) - bHighlighted = true; - - cells.Add(new Cell() { Value = text, ColSpan = colspan, Highlighted = bHighlighted }); - for (int i = 1; i < colspan; ++i) - cells.Add(null); // add empty cells for the spans - } + cells.Add(new Cell() { Value = text, ColSpan = colspan, Highlighted = bHighlighted }); + for (int i = 1; i < colspan; ++i) + cells.Add(null); // add empty cells for the spans + } - rows.Add(new Row() { columns = cells.ToArray() }); - } + rows.Add(new Row() { columns = cells.ToArray() }); + } - tables.Add(new Table() { rows = rows.ToArray() }); - } + tables.Add(new Table() { rows = rows.ToArray() }); + } - return tables.ToArray(); - } + return tables.ToArray(); + } - return null; - } - }; + return null; + } + }; - /// - /// The word slots. - /// - [fsObject] - public class Slots - { - /// - /// The pred. - /// - public string pred { get; set; } - /// - /// The subj. - /// - public string subj { get; set; } - /// - /// The objprep. - /// - public string objprep { get; set; } - /// - /// The psubj. - /// - public string psubj { get; set; } - }; + /// + /// The word slots. + /// + [fsObject] + public class Slots + { + /// + /// The pred. + /// + public string pred { get; set; } + /// + /// The subj. + /// + public string subj { get; set; } + /// + /// The objprep. + /// + public string objprep { get; set; } + /// + /// The psubj. + /// + public string psubj { get; set; } + }; - /// - /// The word. - /// - [fsObject] - public class Word - { - /// - /// The slots. - /// - public Slots compSlotParseNodes { get; set; } - /// - /// The slot name. - /// - public string slotname { get; set; } - /// - /// The word text. - /// - public string wordtext { get; set; } - /// - /// The slot name options. - /// - public string slotnameoptions { get; set; } - /// - /// The word sense. - /// - public string wordsense { get; set; } - /// - /// The numeric sense. - /// - public string numericsense { get; set; } - /// - /// The seqno. - /// - public string seqno { get; set; } - /// - /// The word begin. - /// - public string wordbegin { get; set; } - /// - /// The frame begin. - /// - public string framebegin { get; set; } - /// - /// The frame end. - /// - public string frameend { get; set; } - /// - /// The word end. - /// - public string wordend { get; set; } - /// - /// The features. - /// - public string features { get; set; } - /// - /// The lMods. - /// - public Word[] lmods { get; set; } - /// - /// The rMods. - /// - public Word[] rmods { get; set; } - }; + /// + /// The word. + /// + [fsObject] + public class Word + { + /// + /// The slots. + /// + public Slots compSlotParseNodes { get; set; } + /// + /// The slot name. + /// + public string slotname { get; set; } + /// + /// The word text. + /// + public string wordtext { get; set; } + /// + /// The slot name options. + /// + public string slotnameoptions { get; set; } + /// + /// The word sense. + /// + public string wordsense { get; set; } + /// + /// The numeric sense. + /// + public string numericsense { get; set; } + /// + /// The seqno. + /// + public string seqno { get; set; } + /// + /// The word begin. + /// + public string wordbegin { get; set; } + /// + /// The frame begin. + /// + public string framebegin { get; set; } + /// + /// The frame end. + /// + public string frameend { get; set; } + /// + /// The word end. + /// + public string wordend { get; set; } + /// + /// The features. + /// + public string features { get; set; } + /// + /// The lMods. + /// + public Word[] lmods { get; set; } + /// + /// The rMods. + /// + public Word[] rmods { get; set; } + }; - /// - /// The parse tree. - /// - [fsObject] - public class ParseTree : Word - { - /// - /// The parse score. - /// - public string parseScore { get; set; } - }; + /// + /// The parse tree. + /// + [fsObject] + public class ParseTree : Word + { + /// + /// The parse score. + /// + public string parseScore { get; set; } + }; - /// - /// The question. - /// - [fsObject] - public class Question - { - /// - /// The qClassList. - /// - public Value[] qclasslist { get; set; } - /// - /// The focus list. - /// - public Value[] focuslist { get; set; } - /// - /// The lat list. - /// - public Value[] latlist { get; set; } - /// - /// The evidence list. - /// - public Evidence[] evidencelist { get; set; } - /// - /// The synonyms list. - /// - public SynonymList[] synonymList { get; set; } - /// - /// The disambiguated entities. - /// - public string[] disambiguatedEntities { get; set; } - /// - /// The xsgtopparses. - /// - public ParseTree[] xsgtopparses { get; set; } - /// - /// The cas XML. - /// - public string casXml { get; set; } - /// - /// The pipeline id. - /// - public string pipelineid { get; set; } - /// - /// The formatted answer. - /// - public bool formattedAnswer { get; set; } - /// - /// The selected processing components. - /// - public string selectedProcessingComponents { get; set; } - /// - /// The category. - /// - public string category { get; set; } - /// - /// The items. - /// - public long items { get; set; } - /// - /// The status. - /// - public string status { get; set; } - /// - /// The identifier. - /// - public string id { get; set; } - /// - /// The question text. - /// - public string questionText { get; set; } - /// - /// The evidence request. - /// - public EvidenceRequest evidenceRequest { get; set; } - /// - /// The answers. - /// - public Answer[] answers { get; set; } - /// - /// The error notifications. - /// - public string[] errorNotifications { get; set; } - /// - /// The passthru. - /// - public string passthru { get; set; } - /// - /// The question identifier. - /// - public string questionId { get; set; } // local cache ID - }; + /// + /// The question. + /// + [fsObject] + public class Question + { + /// + /// The qClassList. + /// + public Value[] qclasslist { get; set; } + /// + /// The focus list. + /// + public Value[] focuslist { get; set; } + /// + /// The lat list. + /// + public Value[] latlist { get; set; } + /// + /// The evidence list. + /// + public Evidence[] evidencelist { get; set; } + /// + /// The synonyms list. + /// + public SynonymList[] synonymList { get; set; } + /// + /// The disambiguated entities. + /// + public string[] disambiguatedEntities { get; set; } + /// + /// The xsgtopparses. + /// + public ParseTree[] xsgtopparses { get; set; } + /// + /// The cas XML. + /// + public string casXml { get; set; } + /// + /// The pipeline id. + /// + public string pipelineid { get; set; } + /// + /// The formatted answer. + /// + public bool formattedAnswer { get; set; } + /// + /// The selected processing components. + /// + public string selectedProcessingComponents { get; set; } + /// + /// The category. + /// + public string category { get; set; } + /// + /// The items. + /// + public long items { get; set; } + /// + /// The status. + /// + public string status { get; set; } + /// + /// The identifier. + /// + public string id { get; set; } + /// + /// The question text. + /// + public string questionText { get; set; } + /// + /// The evidence request. + /// + public EvidenceRequest evidenceRequest { get; set; } + /// + /// The answers. + /// + public Answer[] answers { get; set; } + /// + /// The error notifications. + /// + public string[] errorNotifications { get; set; } + /// + /// The passthru. + /// + public string passthru { get; set; } + /// + /// The question identifier. + /// + public string questionId { get; set; } // local cache ID + }; - /// - /// The question class. - /// - [fsObject] - public class QuestionClass - { - /// - /// Out of domain. - /// - public string out_of_domain { get; set; } - /// - /// The question. - /// - public string question { get; set; } - /// - /// The domain. - /// - public string domain { get; set; } - }; + /// + /// The question class. + /// + [fsObject] + public class QuestionClass + { /// - /// The response object for QA.AskQuestion(). + /// Out of domain. /// - [fsObject] - public class Response - { - /// - /// The questions. - /// - public Question question { get; set; } - /// - /// The question classes. - /// - public QuestionClass[] questionClasses { get; set; } - }; + public string out_of_domain { get; set; } + /// + /// The question. + /// + public string question { get; set; } + /// + /// The domain. + /// + public string domain { get; set; } + }; + /// + /// The response object for QA.AskQuestion(). + /// + [fsObject] + public class Response + { + /// + /// The questions. + /// + public Question question { get; set; } + /// + /// The question classes. + /// + public QuestionClass[] questionClasses { get; set; } + }; + /// + /// A list of responses. + /// + [fsObject] + public class ResponseList + { /// - /// A list of responses. + /// The responses. /// - [fsObject] - public class ResponseList - { - /// - /// The responses. - /// - public Response[] responses { get; set; } - }; + public Response[] responses { get; set; } + }; } diff --git a/Scripts/Services/DeepQA/DeepQA.cs b/Scripts/Services/DeepQA/DeepQA.cs old mode 100644 new mode 100755 index a6ce99296..6c472e284 --- a/Scripts/Services/DeepQA/DeepQA.cs +++ b/Scripts/Services/DeepQA/DeepQA.cs @@ -26,106 +26,106 @@ namespace IBM.Watson.DeveloperCloud.Services.DeepQA.v1 { + /// + /// The DeepQA provides an abstraction for the DeepQA services of Watson. + /// + public class DeepQA : IWatsonService + { + #region Public Types + /// + public delegate void OnQuestion(Question response); + #endregion + + #region Public Properties /// - /// The DeepQA provides an abstraction for the DeepQA services of Watson. + /// True to disable the question cache. /// - public class DeepQA : IWatsonService + public bool DisableCache { get; set; } + #endregion + + #region Private Data + private string m_ServiceId = null; + private DataCache m_QuestionCache = null; + + private static fsSerializer sm_Serializer = new fsSerializer(); + private const string ASK_QUESTION = "/v1/question"; + #endregion + + /// + /// Public constructor. + /// + /// The ID of the pipeline for caching purposes. + public DeepQA(string serviceId) { - #region Public Types - /// - public delegate void OnQuestion(Question response); - #endregion - - #region Public Properties - /// - /// True to disable the question cache. - /// - public bool DisableCache { get; set; } - #endregion - - #region Private Data - private string m_ServiceId = null; - private DataCache m_QuestionCache = null; - - private static fsSerializer sm_Serializer = new fsSerializer(); - private const string ASK_QUESTION = "/v1/question"; - #endregion - - /// - /// Public constructor. - /// - /// The ID of the pipeline for caching purposes. - public DeepQA(string serviceId) - { - m_ServiceId = serviceId; - } + m_ServiceId = serviceId; + } - #region AskQuestion - /// - /// This function flushes all data from the answer cache. - /// - public void FlushAnswerCache() - { - if (m_QuestionCache == null) - m_QuestionCache = new DataCache(m_ServiceId); + #region AskQuestion + /// + /// This function flushes all data from the answer cache. + /// + public void FlushAnswerCache() + { + if (m_QuestionCache == null) + m_QuestionCache = new DataCache(m_ServiceId); - m_QuestionCache.Flush(); - } + m_QuestionCache.Flush(); + } - /// - /// Find a question in the question cache. - /// - /// - /// - public Question FindQuestion(string questionId) + /// + /// Find a question in the question cache. + /// + /// + /// + public Question FindQuestion(string questionId) + { + if (m_QuestionCache == null) + m_QuestionCache = new DataCache(m_ServiceId); + + byte[] cachedQuestion = m_QuestionCache.Find(questionId); + if (cachedQuestion != null) + { + Response response = ProcessAskResp(cachedQuestion); + if (response != null) { - if (m_QuestionCache == null) - m_QuestionCache = new DataCache(m_ServiceId); - - byte[] cachedQuestion = m_QuestionCache.Find(questionId); - if (cachedQuestion != null) - { - Response response = ProcessAskResp(cachedQuestion); - if (response != null) - { - response.question.questionId = questionId; - return response.question; - } - } - - return null; + response.question.questionId = questionId; + return response.question; } + } - /// - /// Ask a question using the given pipeline. - /// - /// The text of the question. - /// The callback to receive the response. - /// Returns true if the request was submitted. - public bool AskQuestion(string question, OnQuestion callback, int evidenceItems = 1, bool useCache = true) + return null; + } + + /// + /// Ask a question using the given pipeline. + /// + /// The text of the question. + /// The callback to receive the response. + /// Returns true if the request was submitted. + public bool AskQuestion(string question, OnQuestion callback, int evidenceItems = 1, bool useCache = true) + { + if (string.IsNullOrEmpty(question)) + throw new ArgumentNullException("question"); + if (callback == null) + throw new ArgumentNullException("callback"); + + string questionId = Utility.GetMD5(question); + if (!DisableCache && useCache) + { + Question q = FindQuestion(questionId); + if (q != null) { - if (string.IsNullOrEmpty(question)) - throw new ArgumentNullException("question"); - if (callback == null) - throw new ArgumentNullException("callback"); - - string questionId = Utility.GetMD5(question); - if (!DisableCache && useCache) - { - Question q = FindQuestion(questionId); - if (q != null) - { - callback(q); - return true; - } - } - - RESTConnector connector = RESTConnector.GetConnector(m_ServiceId, ASK_QUESTION); - if (connector == null) - return false; - - Dictionary questionJson = new Dictionary(); - questionJson["question"] = new Dictionary() { + callback(q); + return true; + } + } + + RESTConnector connector = RESTConnector.GetConnector(m_ServiceId, ASK_QUESTION); + if (connector == null) + return false; + + Dictionary questionJson = new Dictionary(); + questionJson["question"] = new Dictionary() { { "questionText", question }, { "formattedAnswer", "true" }, { "evidenceRequest", new Dictionary() { @@ -133,107 +133,107 @@ public bool AskQuestion(string question, OnQuestion callback, int evidenceItems { "profile", "NO" } } } }; - string json = MiniJSON.Json.Serialize(questionJson); + string json = MiniJSON.Json.Serialize(questionJson); - AskQuestionReq req = new AskQuestionReq(); - req.QuestionID = questionId; - req.Callback = callback; - req.Headers["Content-Type"] = "application/json"; - req.Headers["X-Synctimeout"] = "-1"; - req.Send = Encoding.UTF8.GetBytes(json); - req.OnResponse = OnAskQuestionResp; + AskQuestionReq req = new AskQuestionReq(); + req.QuestionID = questionId; + req.Callback = callback; + req.Headers["Content-Type"] = "application/json"; + req.Headers["X-Synctimeout"] = "-1"; + req.Send = Encoding.UTF8.GetBytes(json); + req.OnResponse = OnAskQuestionResp; - return connector.Send(req); - } - private class AskQuestionReq : RESTConnector.Request + return connector.Send(req); + } + private class AskQuestionReq : RESTConnector.Request + { + public string QuestionID { get; set; } + public OnQuestion Callback { get; set; } + }; + private void OnAskQuestionResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Response response = null; + if (resp.Success) + { + try { - public string QuestionID { get; set; } - public OnQuestion Callback { get; set; } - }; - private void OnAskQuestionResp(RESTConnector.Request req, RESTConnector.Response resp) + response = ProcessAskResp(resp.Data); + if (m_QuestionCache != null && response != null) + m_QuestionCache.Save(((AskQuestionReq)req).QuestionID, resp.Data); + } + catch (Exception e) { - Response response = null; - if (resp.Success) - { - try - { - response = ProcessAskResp(resp.Data); - if (m_QuestionCache != null && response != null) - m_QuestionCache.Save(((AskQuestionReq)req).QuestionID, resp.Data); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((AskQuestionReq)req).Callback != null) - { - if (resp.Success && response != null) - { - response.question.questionId = ((AskQuestionReq)req).QuestionID; - ((AskQuestionReq)req).Callback(response.question); - } - else - ((AskQuestionReq)req).Callback(null); - } + Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); + resp.Success = false; } + } - private Response ProcessAskResp(byte[] json_data) + if (((AskQuestionReq)req).Callback != null) + { + if (resp.Success && response != null) { - Response response = new Response(); + response.question.questionId = ((AskQuestionReq)req).QuestionID; + ((AskQuestionReq)req).Callback(response.question); + } + else + ((AskQuestionReq)req).Callback(null); + } + } - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(json_data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); + private Response ProcessAskResp(byte[] json_data) + { + Response response = new Response(); - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(json_data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); - return response; - } + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); - #endregion + return response; + } - #region IWatsonService interface - /// - public string GetServiceID() - { - return m_ServiceId; - } + #endregion - /// - public void GetServiceStatus(ServiceStatus callback) - { - if (Config.Instance.FindCredentials(m_ServiceId) != null) - new CheckServiceStatus(this, callback); - else - callback(m_ServiceId, false); - } + #region IWatsonService interface + /// + public string GetServiceID() + { + return m_ServiceId; + } - private class CheckServiceStatus - { - private DeepQA m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(DeepQA service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - if (!m_Service.AskQuestion("What is the best treatment for an African American male in heart failure?", OnQuestion, 1, false)) - m_Callback(m_Service.GetServiceID(), false); - } - - private void OnQuestion(Question question) - { - m_Callback(m_Service.GetServiceID(), question != null); - } - }; - #endregion + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(m_ServiceId) != null) + new CheckServiceStatus(this, callback); + else + callback(m_ServiceId, false); } + + private class CheckServiceStatus + { + private DeepQA m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(DeepQA service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.AskQuestion("What is the best treatment for an African American male in heart failure?", OnQuestion, 1, false)) + m_Callback(m_Service.GetServiceID(), false); + } + + private void OnQuestion(Question question) + { + m_Callback(m_Service.GetServiceID(), question != null); + } + }; + #endregion + } } diff --git a/Scripts/Services/DocumentConversion/DataModels.cs b/Scripts/Services/DocumentConversion/DataModels.cs index b4e920194..352a95daa 100755 --- a/Scripts/Services/DocumentConversion/DataModels.cs +++ b/Scripts/Services/DocumentConversion/DataModels.cs @@ -21,153 +21,153 @@ namespace IBM.Watson.DeveloperCloud.Services.DocumentConversion.v1 { + /// + /// Document Conversion response. + /// + [fsObject] + public class ConvertedDocument + { /// - /// Document Conversion response. - /// - [fsObject] - public class ConvertedDocument - { - /// - /// The source document ID. - /// - public string source_document_id { get; set; } - /// - /// The timestamp. - /// - public string timestamp { get; set; } - /// - /// The detected media type. - /// - public string media_type_detected { get; set; } - /// - /// Array of document metadata. - /// - public Metadata[] metadata { get; set; } - /// - /// Answer Units. - /// - public AnswerUnit[] answer_units { get; set; } - /// - /// Warnings. - /// - public Warning[] warnings { get; set; } - /// - /// Container for text response from ConversionTarget.NORMALIZED_TEXT - /// - public string textContent { get; set; } - /// - /// Container for HTML response from ConversionTarget.NORMALIZED_HTML - /// - public string htmlContent { get; set; } - } + /// The source document ID. + /// + public string source_document_id { get; set; } + /// + /// The timestamp. + /// + public string timestamp { get; set; } + /// + /// The detected media type. + /// + public string media_type_detected { get; set; } + /// + /// Array of document metadata. + /// + public Metadata[] metadata { get; set; } + /// + /// Answer Units. + /// + public AnswerUnit[] answer_units { get; set; } + /// + /// Warnings. + /// + public Warning[] warnings { get; set; } + /// + /// Container for text response from ConversionTarget.NORMALIZED_TEXT + /// + public string textContent { get; set; } + /// + /// Container for HTML response from ConversionTarget.NORMALIZED_HTML + /// + public string htmlContent { get; set; } + } + /// + /// Metadata for the doucment conversion. + /// + [fsObject] + public class Metadata + { + /// + /// Metadata name. + /// + public string name { get; set; } /// - /// Metadata for the doucment conversion. - /// - [fsObject] - public class Metadata - { - /// - /// Metadata name. - /// - public string name { get; set; } - /// - /// Metadata content. - /// - public string content { get; set; } - } + /// Metadata content. + /// + public string content { get; set; } + } + /// + /// The units of the broken down document. + /// + [fsObject] + public class AnswerUnit + { /// - /// The units of the broken down document. - /// - [fsObject] - public class AnswerUnit - { - /// - /// The AnswerUnit ID. - /// - public string id { get; set; } - /// - /// The AnswerUnit type. - /// - public string type { get; set; } - /// - /// The AnswerUnit parent ID. - /// - public string parent_id { get; set; } - /// - /// The AnswerUnit title. - /// - public string title { get; set; } - /// - /// The AnswerUnit direction. - /// - public string direction { get; set; } - /// - /// The AnswerUnit content. - /// - public Content[] content { get; set; } - } + /// The AnswerUnit ID. + /// + public string id { get; set; } + /// + /// The AnswerUnit type. + /// + public string type { get; set; } + /// + /// The AnswerUnit parent ID. + /// + public string parent_id { get; set; } + /// + /// The AnswerUnit title. + /// + public string title { get; set; } + /// + /// The AnswerUnit direction. + /// + public string direction { get; set; } + /// + /// The AnswerUnit content. + /// + public Content[] content { get; set; } + } - /// - /// Document content. - /// - [fsObject] - public class Content - { - /// - /// The content media type. - /// - public string media_type { get; set; } - /// - /// The content text. - /// - public string text { get; set; } - } + /// + /// Document content. + /// + [fsObject] + public class Content + { + /// + /// The content media type. + /// + public string media_type { get; set; } + /// + /// The content text. + /// + public string text { get; set; } + } + /// + /// The error response. + /// + [fsObject] + public class Warning + { /// - /// The error response. - /// - [fsObject] - public class Warning - { - /// - /// The warning code. - /// - public string code { get; set; } - /// - /// The warning error text. - /// - public string error { get; set; } - } + /// The warning code. + /// + public string code { get; set; } + /// + /// The warning error text. + /// + public string error { get; set; } + } + /// + /// Targets for document conversion. + /// + public class ConversionTarget + { /// - /// Targets for document conversion. - /// - public class ConversionTarget - { - /// - /// Answer units conversion target. - /// - public const string ANSWER_UNITS = "{\"conversion_target\": \"answer_units\"}"; - /// - /// Normalized html conversion target. - /// - public const string NORMALIZED_HTML = "{\"conversion_target\": \"normalized_html\"}"; - /// - /// Normalized text conversion target. - /// - public const string NORMALIZED_TEXT = "{\"conversion_target\": \"normalized_text\"}"; - } + /// Answer units conversion target. + /// + public const string ANSWER_UNITS = "{\"conversion_target\": \"answer_units\"}"; + /// + /// Normalized html conversion target. + /// + public const string NORMALIZED_HTML = "{\"conversion_target\": \"normalized_html\"}"; + /// + /// Normalized text conversion target. + /// + public const string NORMALIZED_TEXT = "{\"conversion_target\": \"normalized_text\"}"; + } + /// + /// The Document Conversion service version. + /// + public class Version + { /// - /// The Document Conversion service version. + /// The version. /// - public class Version - { - /// - /// The version. - /// - public const string DOCUMENT_CONVERSION = "2015-12-15"; - } + public const string DOCUMENT_CONVERSION = "2015-12-15"; + } } diff --git a/Scripts/Services/DocumentConversion/DocumentConversion.cs b/Scripts/Services/DocumentConversion/DocumentConversion.cs index f69c36540..3b36bd5dc 100755 --- a/Scripts/Services/DocumentConversion/DocumentConversion.cs +++ b/Scripts/Services/DocumentConversion/DocumentConversion.cs @@ -28,182 +28,182 @@ namespace IBM.Watson.DeveloperCloud.Services.DocumentConversion.v1 { - /// - /// This class wraps the Document Conversion service. - /// Document Conversion Service - /// - public class DocumentConversion : IWatsonService + /// + /// This class wraps the Document Conversion service. + /// Document Conversion Service + /// + public class DocumentConversion : IWatsonService + { + #region Private Data + private const string SERVICE_ID = "DocumentConversionV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region ConvertDocument + private const string FUNCTION_CONVERT_DOCUMENT = "/v1/convert_document"; + /// + /// The OnConvertDocument callback. + /// + /// + /// + public delegate void OnConvertDocument(ConvertedDocument resp, string data); + + /// + /// The delegate for loading a file, used by TrainClassifier(). + /// + /// The filename to load. + /// Should return a byte array of the file contents or null of failure. + public delegate byte[] LoadFileDelegate(string filename); + + /// + /// Set this property to overload the internal file loading of this class. + /// + public LoadFileDelegate LoadFile { get; set; } + + /// + /// Convert document to use in other Watson services. + /// + /// + /// + /// + /// + /// + public bool ConvertDocument(OnConvertDocument callback, string documentPath, string conversionTarget = ConversionTarget.ANSWER_UNITS, string data = null) { - #region Private Data - private const string SERVICE_ID = "DocumentConversionV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region ConvertDocument - private const string FUNCTION_CONVERT_DOCUMENT = "/v1/convert_document"; - /// - /// The OnConvertDocument callback. - /// - /// - /// - public delegate void OnConvertDocument(ConvertedDocument resp, string data); - - /// - /// The delegate for loading a file, used by TrainClassifier(). - /// - /// The filename to load. - /// Should return a byte array of the file contents or null of failure. - public delegate byte[] LoadFileDelegate(string filename); - - /// - /// Set this property to overload the internal file loading of this class. - /// - public LoadFileDelegate LoadFile { get; set; } - - /// - /// Convert document to use in other Watson services. - /// - /// - /// - /// - /// - /// - public bool ConvertDocument(OnConvertDocument callback, string documentPath, string conversionTarget = ConversionTarget.ANSWER_UNITS, string data = null) + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(documentPath)) + throw new ArgumentNullException("A document path is needed to convert document."); + if (string.IsNullOrEmpty(conversionTarget)) + throw new ArgumentNullException("A conversion target is needed to convert document."); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_CONVERT_DOCUMENT); + if (connector == null) + return false; + + ConvertDocumentRequest req = new ConvertDocumentRequest(); + req.Callback = callback; + req.OnResponse = ConvertDocumentResponse; + req.Data = data; + req.ConversionTarget = conversionTarget; + req.Parameters["version"] = Version.DOCUMENT_CONVERSION; + + byte[] documentData = null; + if (documentPath != default(string)) + { + if (LoadFile != null) + { + documentData = LoadFile(documentPath); + } + else { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(documentPath)) - throw new ArgumentNullException("A document path is needed to convert document."); - if (string.IsNullOrEmpty(conversionTarget)) - throw new ArgumentNullException("A conversion target is needed to convert document."); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_CONVERT_DOCUMENT); - if (connector == null) - return false; - - ConvertDocumentRequest req = new ConvertDocumentRequest(); - req.Callback = callback; - req.OnResponse = ConvertDocumentResponse; - req.Data = data; - req.ConversionTarget = conversionTarget; - req.Parameters["version"] = Version.DOCUMENT_CONVERSION; - - byte[] documentData = null; - if (documentPath != default(string)) - { - if (LoadFile != null) - { - documentData = LoadFile(documentPath); - } - else - { #if !UNITY_WEBPLAYER - documentData = File.ReadAllBytes(documentPath); + documentData = File.ReadAllBytes(documentPath); #endif - } - - if (documentData == null) - Log.Error("DocumentConversion", "Failed to upload {0}!", documentPath); - } - - if (documentData != null) - { - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - - req.Forms = new Dictionary(); - req.Forms["file"] = new RESTConnector.Form(documentData); - req.Forms["config"] = new RESTConnector.Form(conversionTarget.ToString()); - } - - return connector.Send(req); } - private class ConvertDocumentRequest : RESTConnector.Request - { - public string Data { get; set; } - public string ConversionTarget { get; set; } - public OnConvertDocument Callback { get; set; } - }; + if (documentData == null) + Log.Error("DocumentConversion", "Failed to upload {0}!", documentPath); + } + + if (documentData != null) + { + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + + req.Forms = new Dictionary(); + req.Forms["file"] = new RESTConnector.Form(documentData); + req.Forms["config"] = new RESTConnector.Form(conversionTarget.ToString()); + } + + return connector.Send(req); + } + + private class ConvertDocumentRequest : RESTConnector.Request + { + public string Data { get; set; } + public string ConversionTarget { get; set; } + public OnConvertDocument Callback { get; set; } + }; - private void ConvertDocumentResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void ConvertDocumentResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + ConvertedDocument response = new ConvertedDocument(); + + if (resp.Success) + { + if ((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.ANSWER_UNITS) { - ConvertedDocument response = new ConvertedDocument(); - - if (resp.Success) - { - if((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.ANSWER_UNITS) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("DocumentConversion", "ConvertDocumentResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - else if((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.NORMALIZED_HTML) - { - response.htmlContent = System.Text.Encoding.Default.GetString(resp.Data); - } - else if((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.NORMALIZED_TEXT) - { - response.textContent = System.Text.Encoding.Default.GetString(resp.Data); - } - - } - - if (((ConvertDocumentRequest)req).Callback != null) - ((ConvertDocumentRequest)req).Callback(resp.Success ? response : null, ((ConvertDocumentRequest)req).Data); + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("DocumentConversion", "ConvertDocumentResponse Exception: {0}", e.ToString()); + resp.Success = false; + } } - #endregion - - #region IWatsonService interface - /// - public string GetServiceID() + else if ((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.NORMALIZED_HTML) { - return SERVICE_ID; + response.htmlContent = System.Text.Encoding.Default.GetString(resp.Data); } - - /// - public void GetServiceStatus(ServiceStatus callback) + else if ((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.NORMALIZED_TEXT) { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); + response.textContent = System.Text.Encoding.Default.GetString(resp.Data); } - private class CheckServiceStatus - { - private DocumentConversion m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(DocumentConversion service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - string examplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; - if (!m_Service.ConvertDocument(OnConvertDocument, examplePath)) - m_Callback(SERVICE_ID, false); - } - - void OnConvertDocument(ConvertedDocument documentConversionData, string data) - { - if (m_Callback != null) - m_Callback(SERVICE_ID, documentConversionData != null); - } - - }; - #endregion + } + + if (((ConvertDocumentRequest)req).Callback != null) + ((ConvertDocumentRequest)req).Callback(resp.Success ? response : null, ((ConvertDocumentRequest)req).Data); + } + #endregion + + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; } + + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + private class CheckServiceStatus + { + private DocumentConversion m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(DocumentConversion service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + string examplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; + if (!m_Service.ConvertDocument(OnConvertDocument, examplePath)) + m_Callback(SERVICE_ID, false); + } + + void OnConvertDocument(ConvertedDocument documentConversionData, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, documentConversionData != null); + } + + }; + #endregion + } } \ No newline at end of file diff --git a/Scripts/Services/IWatsonService.cs b/Scripts/Services/IWatsonService.cs old mode 100644 new mode 100755 index ec78e761a..3ca262aa5 --- a/Scripts/Services/IWatsonService.cs +++ b/Scripts/Services/IWatsonService.cs @@ -23,59 +23,59 @@ namespace IBM.Watson.DeveloperCloud.Services { + /// + /// Callback for the GetServiceStatus() function. + /// + /// The ID of the service. + /// The status of the service, true is up, false is down. + public delegate void ServiceStatus(string serviceID, bool active); + + /// + /// This interface defines common interface for all watson services. + /// + public interface IWatsonService + { /// - /// Callback for the GetServiceStatus() function. + /// Returns the service ID. /// - /// The ID of the service. - /// The status of the service, true is up, false is down. - public delegate void ServiceStatus(string serviceID, bool active); - + /// A string containing the service ID. + string GetServiceID(); /// - /// This interface defines common interface for all watson services. + /// This should check if the service is up or down, and invoke the callback with the current + /// state of the service once determined. /// - public interface IWatsonService - { - /// - /// Returns the service ID. - /// - /// A string containing the service ID. - string GetServiceID(); - /// - /// This should check if the service is up or down, and invoke the callback with the current - /// state of the service once determined. - /// - /// The callback to invoke. - void GetServiceStatus(ServiceStatus callback); - } + /// The callback to invoke. + void GetServiceStatus(ServiceStatus callback); + } + /// + /// Service helper class. + /// + public static class ServiceHelper + { /// - /// Service helper class. + /// This returns a instance of all services. /// - public static class ServiceHelper + /// An array of IWatsonService instances. + public static IWatsonService[] GetAllServices(bool reqCredentials = false) { - /// - /// This returns a instance of all services. - /// - /// An array of IWatsonService instances. - public static IWatsonService[] GetAllServices(bool reqCredentials = false) - { - List services = new List(); - - Type[] types = Utilities.Utility.FindAllDerivedTypes(typeof(IWatsonService)); - foreach (var type in types) - { - try - { - IWatsonService serviceObject = Activator.CreateInstance(type) as IWatsonService; - if (reqCredentials && Config.Instance.FindCredentials(serviceObject.GetServiceID()) == null) - continue; // skip services that don't have credential data.. - services.Add(serviceObject as IWatsonService); - } - catch (Exception) - { } - } + List services = new List(); - return services.ToArray(); + Type[] types = Utilities.Utility.FindAllDerivedTypes(typeof(IWatsonService)); + foreach (var type in types) + { + try + { + IWatsonService serviceObject = Activator.CreateInstance(type) as IWatsonService; + if (reqCredentials && Config.Instance.FindCredentials(serviceObject.GetServiceID()) == null) + continue; // skip services that don't have credential data.. + services.Add(serviceObject as IWatsonService); } + catch (Exception) + { } + } + + return services.ToArray(); } + } } diff --git a/Scripts/Services/LanguageTranslation/DataModels.cs b/Scripts/Services/LanguageTranslation/DataModels.cs old mode 100644 new mode 100755 index a7027fade..33d5fb605 --- a/Scripts/Services/LanguageTranslation/DataModels.cs +++ b/Scripts/Services/LanguageTranslation/DataModels.cs @@ -20,118 +20,118 @@ namespace IBM.Watson.DeveloperCloud.Services.LanguageTranslation.v1 { + /// + /// Language data class. + /// + [fsObject] + public class Language + { /// - /// Language data class. - /// - [fsObject] - public class Language - { - /// - /// String that contains the country code. - /// - public string language { get; set; } - /// - /// The language name. - /// - public string name { get; set; } - } - /// - /// Languages data class. - /// - [fsObject] - public class Languages - { - /// - /// Array of language objects. - /// - public Language[] languages { get; set; } - } - /// - /// Translation data class. - /// - [fsObject] - public class Translation - { - /// - /// Translation text. - /// - public string translation { get; set; } - }; - /// - /// Translate data class returned by the TranslateCallback. - /// - [fsObject] - public class Translations - { - /// - /// Number of words in the translation. - /// - public long word_count { get; set; } - /// - /// Number of characters in the translation. - /// - public long character_count { get; set; } - /// - /// A array of translations. - /// - public Translation[] translations { get; set; } - } - /// - /// Language model data class. - /// - [fsObject] - public class TranslationModel - { - /// - /// The language model ID. - /// - public string model_id { get; set; } - /// - /// The name of the language model. - /// - public string name { get; set; } - /// - /// The source language ID. - /// - public string source { get; set; } - /// - /// The target language ID. - /// - public string target { get; set; } - /// - /// The model of which this model was based. - /// - public string base_model_id { get; set; } - /// - /// The domain of the language model. - /// - public string domain { get; set; } - /// - /// Is this model customizable? - /// - public bool customizable { get; set; } - /// - /// Is this model default. - /// - public bool @default { get; set; } - /// - /// Who is the owner of this model. - /// - public string owner { get; set; } - /// - /// What is the status of this model. - /// - public string status { get; set; } - } - /// - /// Models data class. - /// - [fsObject] - public class TranslationModels - { - /// - /// The array of TranslationModel objects. - /// - public TranslationModel[] models { get; set; } - } + /// String that contains the country code. + /// + public string language { get; set; } + /// + /// The language name. + /// + public string name { get; set; } + } + /// + /// Languages data class. + /// + [fsObject] + public class Languages + { + /// + /// Array of language objects. + /// + public Language[] languages { get; set; } + } + /// + /// Translation data class. + /// + [fsObject] + public class Translation + { + /// + /// Translation text. + /// + public string translation { get; set; } + }; + /// + /// Translate data class returned by the TranslateCallback. + /// + [fsObject] + public class Translations + { + /// + /// Number of words in the translation. + /// + public long word_count { get; set; } + /// + /// Number of characters in the translation. + /// + public long character_count { get; set; } + /// + /// A array of translations. + /// + public Translation[] translations { get; set; } + } + /// + /// Language model data class. + /// + [fsObject] + public class TranslationModel + { + /// + /// The language model ID. + /// + public string model_id { get; set; } + /// + /// The name of the language model. + /// + public string name { get; set; } + /// + /// The source language ID. + /// + public string source { get; set; } + /// + /// The target language ID. + /// + public string target { get; set; } + /// + /// The model of which this model was based. + /// + public string base_model_id { get; set; } + /// + /// The domain of the language model. + /// + public string domain { get; set; } + /// + /// Is this model customizable? + /// + public bool customizable { get; set; } + /// + /// Is this model default. + /// + public bool @default { get; set; } + /// + /// Who is the owner of this model. + /// + public string owner { get; set; } + /// + /// What is the status of this model. + /// + public string status { get; set; } + } + /// + /// Models data class. + /// + [fsObject] + public class TranslationModels + { + /// + /// The array of TranslationModel objects. + /// + public TranslationModel[] models { get; set; } + } } diff --git a/Scripts/Services/LanguageTranslation/LanguageTranslation.cs b/Scripts/Services/LanguageTranslation/LanguageTranslation.cs index 80e48f653..de16a6f0b 100755 --- a/Scripts/Services/LanguageTranslation/LanguageTranslation.cs +++ b/Scripts/Services/LanguageTranslation/LanguageTranslation.cs @@ -27,434 +27,434 @@ namespace IBM.Watson.DeveloperCloud.Services.LanguageTranslation.v1 { - /// - /// This class wraps the Language Translation service. - /// Language Translation Service - /// - public class LanguageTranslation : IWatsonService + /// + /// This class wraps the Language Translation service. + /// Language Translation Service + /// + public class LanguageTranslation : IWatsonService + { + #region Public Types + /// + /// Callback for GetModels() method. + /// + /// + public delegate void GetModelsCallback(TranslationModels models); + /// + /// Callback for GetModel() method. + /// + /// + public delegate void GetModelCallback(TranslationModel model); + /// + /// Callback for GetLanguages() method. + /// + /// + public delegate void GetLanguagesCallback(Languages languages); + /// + /// Callback for Identify() method. + /// + /// + public delegate void IdentifyCallback(string languages); + /// + /// Callback for Translate() method. + /// + /// + public delegate void TranslateCallback(Translations translation); + #endregion + + #region Private Data + private const string SERVICE_ID = "LanguageTranslationV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region GetTranslation Functions + /// + /// Translate the provided text using the specified model. + /// + /// The text to translate. + /// The ID of the model to use. + /// The callback to receive the translated text. + /// Returns true on success. + public bool GetTranslation(string text, string model_id, TranslateCallback callback) { - #region Public Types - /// - /// Callback for GetModels() method. - /// - /// - public delegate void GetModelsCallback(TranslationModels models); - /// - /// Callback for GetModel() method. - /// - /// - public delegate void GetModelCallback(TranslationModel model); - /// - /// Callback for GetLanguages() method. - /// - /// - public delegate void GetLanguagesCallback(Languages languages); - /// - /// Callback for Identify() method. - /// - /// - public delegate void IdentifyCallback(string languages); - /// - /// Callback for Translate() method. - /// - /// - public delegate void TranslateCallback(Translations translation); - #endregion - - #region Private Data - private const string SERVICE_ID = "LanguageTranslationV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region GetTranslation Functions - /// - /// Translate the provided text using the specified model. - /// - /// The text to translate. - /// The ID of the model to use. - /// The callback to receive the translated text. - /// Returns true on success. - public bool GetTranslation(string text, string model_id, TranslateCallback callback) - { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (string.IsNullOrEmpty(model_id)) - throw new ArgumentNullException("model_id"); + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (string.IsNullOrEmpty(model_id)) + throw new ArgumentNullException("model_id"); - Dictionary parameters = new Dictionary(); - parameters["model_id"] = model_id; - parameters["text"] = new string[] { text }; + Dictionary parameters = new Dictionary(); + parameters["model_id"] = model_id; + parameters["text"] = new string[] { text }; - return GetTranslation(Json.Serialize(parameters), callback); - } - /// - /// Translate the provided text using the specified source and target. - /// - /// The text to translate. - /// The ID of the source language. - /// The ID of the target language. - /// The callback to receive the translated text. - /// Returns true on success. - public bool GetTranslation(string text, string source, string target, TranslateCallback callback) - { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (string.IsNullOrEmpty(source)) - throw new ArgumentNullException("source"); - if (string.IsNullOrEmpty(target)) - throw new ArgumentNullException("target"); - - Dictionary parameters = new Dictionary(); - parameters["source"] = source; - parameters["target"] = target; - parameters["text"] = new string[] { text }; - - return GetTranslation(Json.Serialize(parameters), callback); - } - private bool GetTranslation(string json, TranslateCallback callback) - { - if (callback == null) - throw new ArgumentNullException("callback"); + return GetTranslation(Json.Serialize(parameters), callback); + } + /// + /// Translate the provided text using the specified source and target. + /// + /// The text to translate. + /// The ID of the source language. + /// The ID of the target language. + /// The callback to receive the translated text. + /// Returns true on success. + public bool GetTranslation(string text, string source, string target, TranslateCallback callback) + { + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (string.IsNullOrEmpty(source)) + throw new ArgumentNullException("source"); + if (string.IsNullOrEmpty(target)) + throw new ArgumentNullException("target"); + + Dictionary parameters = new Dictionary(); + parameters["source"] = source; + parameters["target"] = target; + parameters["text"] = new string[] { text }; + + return GetTranslation(Json.Serialize(parameters), callback); + } + private bool GetTranslation(string json, TranslateCallback callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/translate"); - if (connector == null) - return false; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/translate"); + if (connector == null) + return false; - TranslateReq req = new TranslateReq(); - req.Callback = callback; - req.OnResponse = TranslateResponse; - req.Send = Encoding.UTF8.GetBytes(json); - req.Headers["accept"] = "application/json"; - req.Headers["Content-Type"] = "application/json"; + TranslateReq req = new TranslateReq(); + req.Callback = callback; + req.OnResponse = TranslateResponse; + req.Send = Encoding.UTF8.GetBytes(json); + req.Headers["accept"] = "application/json"; + req.Headers["Content-Type"] = "application/json"; - return connector.Send(req); - } + return connector.Send(req); + } - private class TranslateReq : RESTConnector.Request - { - public TranslateCallback Callback { get; set; } - }; - private void TranslateResponse(RESTConnector.Request req, RESTConnector.Response resp) + private class TranslateReq : RESTConnector.Request + { + public TranslateCallback Callback { get; set; } + }; + private void TranslateResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Translations translations = new Translations(); + if (resp.Success) + { + try { - Translations translations = new Translations(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = translations; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetTranslation Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((TranslateReq)req).Callback != null) - ((TranslateReq)req).Callback(resp.Success ? translations : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = translations; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Models Functions - /// - /// This determines the types of models to return with GetModels. - /// - public enum TypeFilter + catch (Exception e) { - /// - /// Default types - /// - DEFAULT, - /// - /// Non-Default types - /// - NON_DEFAULT, - /// - /// All types are returned. - /// - ALL + Log.Error("Natural Language Classifier", "GetTranslation Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Retrieve the translation models with optional filters. - /// - /// The callback to invoke with the array of models. - /// Optional source language filter. - /// Optional target language filter. - /// Controls if we get default, non-default, or all models. - /// Returns a true on success, false if it failed to submit the request. - public bool GetModels(GetModelsCallback callback, - string sourceFilter = null, - string targetFilter = null, - TypeFilter defaults = TypeFilter.ALL) - { - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models"); - if (connector == null) - return false; - - GetModelsReq req = new GetModelsReq(); - req.Callback = callback; - req.OnResponse = GetModelsResponse; - - if (!string.IsNullOrEmpty(sourceFilter)) - req.Parameters["source"] = sourceFilter; - if (!string.IsNullOrEmpty(targetFilter)) - req.Parameters["target"] = targetFilter; - if (defaults == TypeFilter.DEFAULT) - req.Parameters["default"] = "true"; - else if (defaults == TypeFilter.NON_DEFAULT) - req.Parameters["default"] = "false"; - - return connector.Send(req); - } + if (((TranslateReq)req).Callback != null) + ((TranslateReq)req).Callback(resp.Success ? translations : null); + } + #endregion - private class GetModelsReq : RESTConnector.Request + #region Models Functions + /// + /// This determines the types of models to return with GetModels. + /// + public enum TypeFilter + { + /// + /// Default types + /// + DEFAULT, + /// + /// Non-Default types + /// + NON_DEFAULT, + /// + /// All types are returned. + /// + ALL + } + + /// + /// Retrieve the translation models with optional filters. + /// + /// The callback to invoke with the array of models. + /// Optional source language filter. + /// Optional target language filter. + /// Controls if we get default, non-default, or all models. + /// Returns a true on success, false if it failed to submit the request. + public bool GetModels(GetModelsCallback callback, + string sourceFilter = null, + string targetFilter = null, + TypeFilter defaults = TypeFilter.ALL) + { + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models"); + if (connector == null) + return false; + + GetModelsReq req = new GetModelsReq(); + req.Callback = callback; + req.OnResponse = GetModelsResponse; + + if (!string.IsNullOrEmpty(sourceFilter)) + req.Parameters["source"] = sourceFilter; + if (!string.IsNullOrEmpty(targetFilter)) + req.Parameters["target"] = targetFilter; + if (defaults == TypeFilter.DEFAULT) + req.Parameters["default"] = "true"; + else if (defaults == TypeFilter.NON_DEFAULT) + req.Parameters["default"] = "false"; + + return connector.Send(req); + } + + private class GetModelsReq : RESTConnector.Request + { + public GetModelsCallback Callback { get; set; } + } + + private void GetModelsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TranslationModels models = new TranslationModels(); + if (resp.Success) + { + try { - public GetModelsCallback Callback { get; set; } + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = models; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - private void GetModelsResponse(RESTConnector.Request req, RESTConnector.Response resp) + catch (Exception e) { - TranslationModels models = new TranslationModels(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = models; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetModels Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetModelsReq)req).Callback != null) - ((GetModelsReq)req).Callback(resp.Success ? models : null); + Log.Error("Natural Language Classifier", "GetModels Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get a specific model by it's ID. - /// - /// - /// - /// - public bool GetModel(string model_id, GetModelCallback callback) - { - if (string.IsNullOrEmpty(model_id)) - throw new ArgumentNullException("model_id"); - if (callback == null) - throw new ArgumentNullException("callback"); + if (((GetModelsReq)req).Callback != null) + ((GetModelsReq)req).Callback(resp.Success ? models : null); + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models/"); - if (connector == null) - return false; + /// + /// Get a specific model by it's ID. + /// + /// + /// + /// + public bool GetModel(string model_id, GetModelCallback callback) + { + if (string.IsNullOrEmpty(model_id)) + throw new ArgumentNullException("model_id"); + if (callback == null) + throw new ArgumentNullException("callback"); - GetModelReq req = new GetModelReq(); - req.Callback = callback; - req.Function = WWW.EscapeURL(model_id); - req.OnResponse = GetModelResponse; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models/"); + if (connector == null) + return false; - return connector.Send(req); - } + GetModelReq req = new GetModelReq(); + req.Callback = callback; + req.Function = WWW.EscapeURL(model_id); + req.OnResponse = GetModelResponse; - private class GetModelReq : RESTConnector.Request - { - public GetModelCallback Callback { get; set; } - } + return connector.Send(req); + } - private void GetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) + private class GetModelReq : RESTConnector.Request + { + public GetModelCallback Callback { get; set; } + } + + private void GetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TranslationModel model = new TranslationModel(); + if (resp.Success) + { + try { - TranslationModel model = new TranslationModel(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = model; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetModel Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetModelReq)req).Callback != null) - ((GetModelReq)req).Callback(resp.Success ? model : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = model; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetLanguages Functions - /// - /// This function returns a list to the callback of all identifiable languages. - /// - /// The callback to invoke with a Language array, null on error. - /// Returns true if the request was submitted. - public bool GetLanguages(GetLanguagesCallback callback) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); + Log.Error("Natural Language Classifier", "GetModel Exception: {0}", e.ToString()); + resp.Success = false; + } + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identifiable_languages"); - if (connector == null) - return false; + if (((GetModelReq)req).Callback != null) + ((GetModelReq)req).Callback(resp.Success ? model : null); + } + #endregion + + #region GetLanguages Functions + /// + /// This function returns a list to the callback of all identifiable languages. + /// + /// The callback to invoke with a Language array, null on error. + /// Returns true if the request was submitted. + public bool GetLanguages(GetLanguagesCallback callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); - GetLanguagesReq req = new GetLanguagesReq(); - req.Callback = callback; - req.OnResponse = GetLanguagesResponse; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identifiable_languages"); + if (connector == null) + return false; - return connector.Send(req); - } + GetLanguagesReq req = new GetLanguagesReq(); + req.Callback = callback; + req.OnResponse = GetLanguagesResponse; - private class GetLanguagesReq : RESTConnector.Request - { - public GetLanguagesCallback Callback { get; set; } - } + return connector.Send(req); + } - private void GetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + private class GetLanguagesReq : RESTConnector.Request + { + public GetLanguagesCallback Callback { get; set; } + } + + private void GetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Languages langs = new Languages(); + if (resp.Success) + { + try { - Languages langs = new Languages(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = langs; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetLanguages Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetLanguagesReq)req).Callback != null) - ((GetLanguagesReq)req).Callback(resp.Success ? langs : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = langs; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Identify Functions - /// - /// Identifies a language from the given text. - /// - /// The text sample to ID. - /// The callback to receive the results. - /// - public bool Identify(string text, IdentifyCallback callback) + catch (Exception e) { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identify"); - if (connector == null) - return false; - - IdentifyReq req = new IdentifyReq(); - req.Callback = callback; - req.Send = Encoding.UTF8.GetBytes(text); - req.Headers["Content-Type"] = "text/plain"; - req.OnResponse = OnIdentifyResponse; - - return connector.Send(req); + Log.Error("Natural Language Classifier", "GetLanguages Exception: {0}", e.ToString()); + resp.Success = false; } + } - private class IdentifyReq : RESTConnector.Request - { - public IdentifyCallback Callback { get; set; } - }; + if (((GetLanguagesReq)req).Callback != null) + ((GetLanguagesReq)req).Callback(resp.Success ? langs : null); + } + #endregion + + #region Identify Functions + /// + /// Identifies a language from the given text. + /// + /// The text sample to ID. + /// The callback to receive the results. + /// + public bool Identify(string text, IdentifyCallback callback) + { + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identify"); + if (connector == null) + return false; + + IdentifyReq req = new IdentifyReq(); + req.Callback = callback; + req.Send = Encoding.UTF8.GetBytes(text); + req.Headers["Content-Type"] = "text/plain"; + req.OnResponse = OnIdentifyResponse; + + return connector.Send(req); + } - private void OnIdentifyResponse(RESTConnector.Request r, RESTConnector.Response resp) - { - IdentifyReq req = r as IdentifyReq; - if (req == null) - throw new WatsonException("Unexpected Request type."); - - if (resp.Success) - { - if (req.Callback != null) - req.Callback(Encoding.UTF8.GetString(resp.Data)); - } - else - { - Log.Error("Translate", "Identify() failed: {0}", resp.Error); - if (req.Callback != null) - req.Callback(null); - } - } - #endregion + private class IdentifyReq : RESTConnector.Request + { + public IdentifyCallback Callback { get; set; } + }; - #region IWatsonService interface - /// - public string GetServiceID() - { - return SERVICE_ID; - } + private void OnIdentifyResponse(RESTConnector.Request r, RESTConnector.Response resp) + { + IdentifyReq req = r as IdentifyReq; + if (req == null) + throw new WatsonException("Unexpected Request type."); + + if (resp.Success) + { + if (req.Callback != null) + req.Callback(Encoding.UTF8.GetString(resp.Data)); + } + else + { + Log.Error("Translate", "Identify() failed: {0}", resp.Error); + if (req.Callback != null) + req.Callback(null); + } + } + #endregion - /// - public void GetServiceStatus(ServiceStatus callback) - { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); - } + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - private class CheckServiceStatus - { - private LanguageTranslation m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(LanguageTranslation service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - if (!m_Service.GetLanguages(OnCheckService)) - m_Callback(SERVICE_ID, false); - } - - private void OnCheckService(Languages langs) - { - if (m_Callback != null) - m_Callback(SERVICE_ID, langs != null); - } - }; - #endregion + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); } + + private class CheckServiceStatus + { + private LanguageTranslation m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(LanguageTranslation service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.GetLanguages(OnCheckService)) + m_Callback(SERVICE_ID, false); + } + + private void OnCheckService(Languages langs) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, langs != null); + } + }; + #endregion + } } diff --git a/Scripts/Services/LanguageTranslator/DataModels.cs b/Scripts/Services/LanguageTranslator/DataModels.cs old mode 100644 new mode 100755 index 07161304d..7cb3dbe8a --- a/Scripts/Services/LanguageTranslator/DataModels.cs +++ b/Scripts/Services/LanguageTranslator/DataModels.cs @@ -20,118 +20,118 @@ namespace IBM.Watson.DeveloperCloud.Services.LanguageTranslator.v1 { + /// + /// Language data class. + /// + [fsObject] + public class Language + { /// - /// Language data class. - /// - [fsObject] - public class Language - { - /// - /// String that contains the country code. - /// - public string language { get; set; } - /// - /// The language name. - /// - public string name { get; set; } - } - /// - /// Languages data class. - /// - [fsObject] - public class Languages - { - /// - /// Array of language objects. - /// - public Language[] languages { get; set; } - } - /// - /// Translation data class. - /// - [fsObject] - public class Translation - { - /// - /// Translation text. - /// - public string translation { get; set; } - }; - /// - /// Translate data class returned by the TranslateCallback. - /// - [fsObject] - public class Translations - { - /// - /// Number of words in the translation. - /// - public long word_count { get; set; } - /// - /// Number of characters in the translation. - /// - public long character_count { get; set; } - /// - /// A array of translations. - /// - public Translation[] translations { get; set; } - } - /// - /// Language model data class. - /// - [fsObject] - public class TranslationModel - { - /// - /// The language model ID. - /// - public string model_id { get; set; } - /// - /// The name of the language model. - /// - public string name { get; set; } - /// - /// The source language ID. - /// - public string source { get; set; } - /// - /// The target language ID. - /// - public string target { get; set; } - /// - /// The model of which this model was based. - /// - public string base_model_id { get; set; } - /// - /// The domain of the language model. - /// - public string domain { get; set; } - /// - /// Is this model customizable? - /// - public bool customizable { get; set; } - /// - /// Is this model default. - /// - public bool @default { get; set; } - /// - /// Who is the owner of this model. - /// - public string owner { get; set; } - /// - /// What is the status of this model. - /// - public string status { get; set; } - } - /// - /// Models data class. - /// - [fsObject] - public class TranslationModels - { - /// - /// The array of TranslationModel objects. - /// - public TranslationModel[] models { get; set; } - } + /// String that contains the country code. + /// + public string language { get; set; } + /// + /// The language name. + /// + public string name { get; set; } + } + /// + /// Languages data class. + /// + [fsObject] + public class Languages + { + /// + /// Array of language objects. + /// + public Language[] languages { get; set; } + } + /// + /// Translation data class. + /// + [fsObject] + public class Translation + { + /// + /// Translation text. + /// + public string translation { get; set; } + }; + /// + /// Translate data class returned by the TranslateCallback. + /// + [fsObject] + public class Translations + { + /// + /// Number of words in the translation. + /// + public long word_count { get; set; } + /// + /// Number of characters in the translation. + /// + public long character_count { get; set; } + /// + /// A array of translations. + /// + public Translation[] translations { get; set; } + } + /// + /// Language model data class. + /// + [fsObject] + public class TranslationModel + { + /// + /// The language model ID. + /// + public string model_id { get; set; } + /// + /// The name of the language model. + /// + public string name { get; set; } + /// + /// The source language ID. + /// + public string source { get; set; } + /// + /// The target language ID. + /// + public string target { get; set; } + /// + /// The model of which this model was based. + /// + public string base_model_id { get; set; } + /// + /// The domain of the language model. + /// + public string domain { get; set; } + /// + /// Is this model customizable? + /// + public bool customizable { get; set; } + /// + /// Is this model default. + /// + public bool @default { get; set; } + /// + /// Who is the owner of this model. + /// + public string owner { get; set; } + /// + /// What is the status of this model. + /// + public string status { get; set; } + } + /// + /// Models data class. + /// + [fsObject] + public class TranslationModels + { + /// + /// The array of TranslationModel objects. + /// + public TranslationModel[] models { get; set; } + } } diff --git a/Scripts/Services/LanguageTranslator/LanguageTranslator.cs b/Scripts/Services/LanguageTranslator/LanguageTranslator.cs old mode 100644 new mode 100755 index 81911520b..21362c002 --- a/Scripts/Services/LanguageTranslator/LanguageTranslator.cs +++ b/Scripts/Services/LanguageTranslator/LanguageTranslator.cs @@ -27,434 +27,434 @@ namespace IBM.Watson.DeveloperCloud.Services.LanguageTranslator.v1 { - /// - /// This class wraps the Language Translator service. - /// Language Translator Service - /// - public class LanguageTranslator : IWatsonService + /// + /// This class wraps the Language Translator service. + /// Language Translator Service + /// + public class LanguageTranslator : IWatsonService + { + #region Public Types + /// + /// Callback for GetModels() method. + /// + /// + public delegate void GetModelsCallback(TranslationModels models); + /// + /// Callback for GetModel() method. + /// + /// + public delegate void GetModelCallback(TranslationModel model); + /// + /// Callback for GetLanguages() method. + /// + /// + public delegate void GetLanguagesCallback(Languages languages); + /// + /// Callback for Identify() method. + /// + /// + public delegate void IdentifyCallback(string languages); + /// + /// Callback for Translate() method. + /// + /// + public delegate void TranslateCallback(Translations translation); + #endregion + + #region Private Data + private const string SERVICE_ID = "LanguageTranslatorV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region GetTranslation Functions + /// + /// Translate the provided text using the specified model. + /// + /// The text to translate. + /// The ID of the model to use. + /// The callback to receive the translated text. + /// Returns true on success. + public bool GetTranslation(string text, string model_id, TranslateCallback callback) { - #region Public Types - /// - /// Callback for GetModels() method. - /// - /// - public delegate void GetModelsCallback(TranslationModels models); - /// - /// Callback for GetModel() method. - /// - /// - public delegate void GetModelCallback(TranslationModel model); - /// - /// Callback for GetLanguages() method. - /// - /// - public delegate void GetLanguagesCallback(Languages languages); - /// - /// Callback for Identify() method. - /// - /// - public delegate void IdentifyCallback(string languages); - /// - /// Callback for Translate() method. - /// - /// - public delegate void TranslateCallback(Translations translation); - #endregion - - #region Private Data - private const string SERVICE_ID = "LanguageTranslatorV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region GetTranslation Functions - /// - /// Translate the provided text using the specified model. - /// - /// The text to translate. - /// The ID of the model to use. - /// The callback to receive the translated text. - /// Returns true on success. - public bool GetTranslation(string text, string model_id, TranslateCallback callback) - { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (string.IsNullOrEmpty(model_id)) - throw new ArgumentNullException("model_id"); + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (string.IsNullOrEmpty(model_id)) + throw new ArgumentNullException("model_id"); - Dictionary parameters = new Dictionary(); - parameters["model_id"] = model_id; - parameters["text"] = new string[] { text }; + Dictionary parameters = new Dictionary(); + parameters["model_id"] = model_id; + parameters["text"] = new string[] { text }; - return GetTranslation(Json.Serialize(parameters), callback); - } - /// - /// Translate the provided text using the specified source and target. - /// - /// The text to translate. - /// The ID of the source language. - /// The ID of the target language. - /// The callback to receive the translated text. - /// Returns true on success. - public bool GetTranslation(string text, string source, string target, TranslateCallback callback) - { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (string.IsNullOrEmpty(source)) - throw new ArgumentNullException("source"); - if (string.IsNullOrEmpty(target)) - throw new ArgumentNullException("target"); - - Dictionary parameters = new Dictionary(); - parameters["source"] = source; - parameters["target"] = target; - parameters["text"] = new string[] { text }; - - return GetTranslation(Json.Serialize(parameters), callback); - } - private bool GetTranslation(string json, TranslateCallback callback) - { - if (callback == null) - throw new ArgumentNullException("callback"); + return GetTranslation(Json.Serialize(parameters), callback); + } + /// + /// Translate the provided text using the specified source and target. + /// + /// The text to translate. + /// The ID of the source language. + /// The ID of the target language. + /// The callback to receive the translated text. + /// Returns true on success. + public bool GetTranslation(string text, string source, string target, TranslateCallback callback) + { + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (string.IsNullOrEmpty(source)) + throw new ArgumentNullException("source"); + if (string.IsNullOrEmpty(target)) + throw new ArgumentNullException("target"); + + Dictionary parameters = new Dictionary(); + parameters["source"] = source; + parameters["target"] = target; + parameters["text"] = new string[] { text }; + + return GetTranslation(Json.Serialize(parameters), callback); + } + private bool GetTranslation(string json, TranslateCallback callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/translate"); - if (connector == null) - return false; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/translate"); + if (connector == null) + return false; - TranslateReq req = new TranslateReq(); - req.Callback = callback; - req.OnResponse = TranslateResponse; - req.Send = Encoding.UTF8.GetBytes(json); - req.Headers["accept"] = "application/json"; - req.Headers["Content-Type"] = "application/json"; + TranslateReq req = new TranslateReq(); + req.Callback = callback; + req.OnResponse = TranslateResponse; + req.Send = Encoding.UTF8.GetBytes(json); + req.Headers["accept"] = "application/json"; + req.Headers["Content-Type"] = "application/json"; - return connector.Send(req); - } + return connector.Send(req); + } - private class TranslateReq : RESTConnector.Request - { - public TranslateCallback Callback { get; set; } - }; - private void TranslateResponse(RESTConnector.Request req, RESTConnector.Response resp) + private class TranslateReq : RESTConnector.Request + { + public TranslateCallback Callback { get; set; } + }; + private void TranslateResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Translations translations = new Translations(); + if (resp.Success) + { + try { - Translations translations = new Translations(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = translations; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetTranslation Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((TranslateReq)req).Callback != null) - ((TranslateReq)req).Callback(resp.Success ? translations : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = translations; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Models Functions - /// - /// This determines the types of models to return with GetModels. - /// - public enum TypeFilter + catch (Exception e) { - /// - /// Default types - /// - DEFAULT, - /// - /// Non-Default types - /// - NON_DEFAULT, - /// - /// All types are returned. - /// - ALL + Log.Error("Natural Language Classifier", "GetTranslation Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Retrieve the translation models with optional filters. - /// - /// The callback to invoke with the array of models. - /// Optional source language filter. - /// Optional target language filter. - /// Controls if we get default, non-default, or all models. - /// Returns a true on success, false if it failed to submit the request. - public bool GetModels(GetModelsCallback callback, - string sourceFilter = null, - string targetFilter = null, - TypeFilter defaults = TypeFilter.ALL) - { - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models"); - if (connector == null) - return false; - - GetModelsReq req = new GetModelsReq(); - req.Callback = callback; - req.OnResponse = GetModelsResponse; - - if (!string.IsNullOrEmpty(sourceFilter)) - req.Parameters["source"] = sourceFilter; - if (!string.IsNullOrEmpty(targetFilter)) - req.Parameters["target"] = targetFilter; - if (defaults == TypeFilter.DEFAULT) - req.Parameters["default"] = "true"; - else if (defaults == TypeFilter.NON_DEFAULT) - req.Parameters["default"] = "false"; - - return connector.Send(req); - } + if (((TranslateReq)req).Callback != null) + ((TranslateReq)req).Callback(resp.Success ? translations : null); + } + #endregion - private class GetModelsReq : RESTConnector.Request + #region Models Functions + /// + /// This determines the types of models to return with GetModels. + /// + public enum TypeFilter + { + /// + /// Default types + /// + DEFAULT, + /// + /// Non-Default types + /// + NON_DEFAULT, + /// + /// All types are returned. + /// + ALL + } + + /// + /// Retrieve the translation models with optional filters. + /// + /// The callback to invoke with the array of models. + /// Optional source language filter. + /// Optional target language filter. + /// Controls if we get default, non-default, or all models. + /// Returns a true on success, false if it failed to submit the request. + public bool GetModels(GetModelsCallback callback, + string sourceFilter = null, + string targetFilter = null, + TypeFilter defaults = TypeFilter.ALL) + { + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models"); + if (connector == null) + return false; + + GetModelsReq req = new GetModelsReq(); + req.Callback = callback; + req.OnResponse = GetModelsResponse; + + if (!string.IsNullOrEmpty(sourceFilter)) + req.Parameters["source"] = sourceFilter; + if (!string.IsNullOrEmpty(targetFilter)) + req.Parameters["target"] = targetFilter; + if (defaults == TypeFilter.DEFAULT) + req.Parameters["default"] = "true"; + else if (defaults == TypeFilter.NON_DEFAULT) + req.Parameters["default"] = "false"; + + return connector.Send(req); + } + + private class GetModelsReq : RESTConnector.Request + { + public GetModelsCallback Callback { get; set; } + } + + private void GetModelsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TranslationModels models = new TranslationModels(); + if (resp.Success) + { + try { - public GetModelsCallback Callback { get; set; } + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = models; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - private void GetModelsResponse(RESTConnector.Request req, RESTConnector.Response resp) + catch (Exception e) { - TranslationModels models = new TranslationModels(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = models; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetModels Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetModelsReq)req).Callback != null) - ((GetModelsReq)req).Callback(resp.Success ? models : null); + Log.Error("Natural Language Classifier", "GetModels Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// Get a specific model by it's ID. - /// - /// - /// - /// - public bool GetModel(string model_id, GetModelCallback callback) - { - if (string.IsNullOrEmpty(model_id)) - throw new ArgumentNullException("model_id"); - if (callback == null) - throw new ArgumentNullException("callback"); + if (((GetModelsReq)req).Callback != null) + ((GetModelsReq)req).Callback(resp.Success ? models : null); + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models/"); - if (connector == null) - return false; + /// + /// Get a specific model by it's ID. + /// + /// + /// + /// + public bool GetModel(string model_id, GetModelCallback callback) + { + if (string.IsNullOrEmpty(model_id)) + throw new ArgumentNullException("model_id"); + if (callback == null) + throw new ArgumentNullException("callback"); - GetModelReq req = new GetModelReq(); - req.Callback = callback; - req.Function = WWW.EscapeURL(model_id); - req.OnResponse = GetModelResponse; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models/"); + if (connector == null) + return false; - return connector.Send(req); - } + GetModelReq req = new GetModelReq(); + req.Callback = callback; + req.Function = WWW.EscapeURL(model_id); + req.OnResponse = GetModelResponse; - private class GetModelReq : RESTConnector.Request - { - public GetModelCallback Callback { get; set; } - } + return connector.Send(req); + } - private void GetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) + private class GetModelReq : RESTConnector.Request + { + public GetModelCallback Callback { get; set; } + } + + private void GetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + TranslationModel model = new TranslationModel(); + if (resp.Success) + { + try { - TranslationModel model = new TranslationModel(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = model; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetModel Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetModelReq)req).Callback != null) - ((GetModelReq)req).Callback(resp.Success ? model : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = model; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetLanguages Functions - /// - /// This function returns a list to the callback of all identifiable languages. - /// - /// The callback to invoke with a Language array, null on error. - /// Returns true if the request was submitted. - public bool GetLanguages(GetLanguagesCallback callback) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); + Log.Error("Natural Language Classifier", "GetModel Exception: {0}", e.ToString()); + resp.Success = false; + } + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identifiable_languages"); - if (connector == null) - return false; + if (((GetModelReq)req).Callback != null) + ((GetModelReq)req).Callback(resp.Success ? model : null); + } + #endregion + + #region GetLanguages Functions + /// + /// This function returns a list to the callback of all identifiable languages. + /// + /// The callback to invoke with a Language array, null on error. + /// Returns true if the request was submitted. + public bool GetLanguages(GetLanguagesCallback callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); - GetLanguagesReq req = new GetLanguagesReq(); - req.Callback = callback; - req.OnResponse = GetLanguagesResponse; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identifiable_languages"); + if (connector == null) + return false; - return connector.Send(req); - } + GetLanguagesReq req = new GetLanguagesReq(); + req.Callback = callback; + req.OnResponse = GetLanguagesResponse; - private class GetLanguagesReq : RESTConnector.Request - { - public GetLanguagesCallback Callback { get; set; } - } + return connector.Send(req); + } - private void GetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + private class GetLanguagesReq : RESTConnector.Request + { + public GetLanguagesCallback Callback { get; set; } + } + + private void GetLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Languages langs = new Languages(); + if (resp.Success) + { + try { - Languages langs = new Languages(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = langs; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetLanguages Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetLanguagesReq)req).Callback != null) - ((GetLanguagesReq)req).Callback(resp.Success ? langs : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = langs; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Identify Functions - /// - /// Identifies a language from the given text. - /// - /// The text sample to ID. - /// The callback to receive the results. - /// - public bool Identify(string text, IdentifyCallback callback) + catch (Exception e) { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identify"); - if (connector == null) - return false; - - IdentifyReq req = new IdentifyReq(); - req.Callback = callback; - req.Send = Encoding.UTF8.GetBytes(text); - req.Headers["Content-Type"] = "text/plain"; - req.OnResponse = OnIdentifyResponse; - - return connector.Send(req); + Log.Error("Natural Language Classifier", "GetLanguages Exception: {0}", e.ToString()); + resp.Success = false; } + } - private class IdentifyReq : RESTConnector.Request - { - public IdentifyCallback Callback { get; set; } - }; + if (((GetLanguagesReq)req).Callback != null) + ((GetLanguagesReq)req).Callback(resp.Success ? langs : null); + } + #endregion + + #region Identify Functions + /// + /// Identifies a language from the given text. + /// + /// The text sample to ID. + /// The callback to receive the results. + /// + public bool Identify(string text, IdentifyCallback callback) + { + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/identify"); + if (connector == null) + return false; + + IdentifyReq req = new IdentifyReq(); + req.Callback = callback; + req.Send = Encoding.UTF8.GetBytes(text); + req.Headers["Content-Type"] = "text/plain"; + req.OnResponse = OnIdentifyResponse; + + return connector.Send(req); + } - private void OnIdentifyResponse(RESTConnector.Request r, RESTConnector.Response resp) - { - IdentifyReq req = r as IdentifyReq; - if (req == null) - throw new WatsonException("Unexpected Request type."); - - if (resp.Success) - { - if (req.Callback != null) - req.Callback(Encoding.UTF8.GetString(resp.Data)); - } - else - { - Log.Error("Translate", "Identify() failed: {0}", resp.Error); - if (req.Callback != null) - req.Callback(null); - } - } - #endregion + private class IdentifyReq : RESTConnector.Request + { + public IdentifyCallback Callback { get; set; } + }; - #region IWatsonService interface - /// - public string GetServiceID() - { - return SERVICE_ID; - } + private void OnIdentifyResponse(RESTConnector.Request r, RESTConnector.Response resp) + { + IdentifyReq req = r as IdentifyReq; + if (req == null) + throw new WatsonException("Unexpected Request type."); + + if (resp.Success) + { + if (req.Callback != null) + req.Callback(Encoding.UTF8.GetString(resp.Data)); + } + else + { + Log.Error("Translate", "Identify() failed: {0}", resp.Error); + if (req.Callback != null) + req.Callback(null); + } + } + #endregion - /// - public void GetServiceStatus(ServiceStatus callback) - { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); - } + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - private class CheckServiceStatus - { - private LanguageTranslator m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(LanguageTranslator service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - if (!m_Service.GetLanguages(OnCheckService)) - m_Callback(SERVICE_ID, false); - } - - private void OnCheckService(Languages langs) - { - if (m_Callback != null) - m_Callback(SERVICE_ID, langs != null); - } - }; - #endregion + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); } + + private class CheckServiceStatus + { + private LanguageTranslator m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(LanguageTranslator service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.GetLanguages(OnCheckService)) + m_Callback(SERVICE_ID, false); + } + + private void OnCheckService(Languages langs) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, langs != null); + } + }; + #endregion + } } diff --git a/Scripts/Services/NaturalLanguageClassifier/DataModels.cs b/Scripts/Services/NaturalLanguageClassifier/DataModels.cs old mode 100644 new mode 100755 index 243dcf020..a876780e8 --- a/Scripts/Services/NaturalLanguageClassifier/DataModels.cs +++ b/Scripts/Services/NaturalLanguageClassifier/DataModels.cs @@ -21,109 +21,109 @@ namespace IBM.Watson.DeveloperCloud.Services.NaturalLanguageClassifier.v1 { + /// + /// This data class holds the data for a given classifier returned by GetClassifier(). + /// + [fsObject] + public class Classifier + { /// - /// This data class holds the data for a given classifier returned by GetClassifier(). + /// The name of the classifier. /// - [fsObject] - public class Classifier - { - /// - /// The name of the classifier. - /// - public string name { get; set; } - /// - /// The language ID of the classifier (e.g. en) - /// - public string language { get; set; } - /// - /// The URL for the classifier. - /// - public string url { get; set; } - /// - /// The classifier ID. - /// - public string classifier_id { get; set; } - /// - /// When was this classifier created. - /// - public string created { get; set; } - /// - /// Whats the current status of this classifier. - /// - public string status { get; set; } - /// - /// A description of the classifier status. - /// - public string status_description { get; set; } - }; - /// - /// This data class wraps an array of Classifiers. - /// - [fsObject] - public class Classifiers - { - /// - /// An array of classifiers. - /// - public Classifier[] classifiers { get; set; } - }; + public string name { get; set; } /// - /// A class returned by the ClassifyResult object. + /// The language ID of the classifier (e.g. en) /// - [fsObject] - public class Class - { - /// - /// The confidence in this class. - /// - public double confidence { get; set; } - /// - /// The name of the class. - /// - public string class_name { get; set; } - }; - /// - /// This result object is returned by the Classify() method. - /// - [fsObject] - public class ClassifyResult - { - /// - /// The ID of the classifier used. - /// - public string classifier_id { get; set; } - /// - /// The URL of the classifier. - /// - public string url { get; set; } - /// - /// The input text into the classifier. - /// - public string text { get; set; } - /// - /// The top class found for the text. - /// - public string top_class { get; set; } - /// - /// A array of all classifications for the input text. - /// - public Class[] classes { get; set; } + public string language { get; set; } + /// + /// The URL for the classifier. + /// + public string url { get; set; } + /// + /// The classifier ID. + /// + public string classifier_id { get; set; } + /// + /// When was this classifier created. + /// + public string created { get; set; } + /// + /// Whats the current status of this classifier. + /// + public string status { get; set; } + /// + /// A description of the classifier status. + /// + public string status_description { get; set; } + }; + /// + /// This data class wraps an array of Classifiers. + /// + [fsObject] + public class Classifiers + { + /// + /// An array of classifiers. + /// + public Classifier[] classifiers { get; set; } + }; + /// + /// A class returned by the ClassifyResult object. + /// + [fsObject] + public class Class + { + /// + /// The confidence in this class. + /// + public double confidence { get; set; } + /// + /// The name of the class. + /// + public string class_name { get; set; } + }; + /// + /// This result object is returned by the Classify() method. + /// + [fsObject] + public class ClassifyResult + { + /// + /// The ID of the classifier used. + /// + public string classifier_id { get; set; } + /// + /// The URL of the classifier. + /// + public string url { get; set; } + /// + /// The input text into the classifier. + /// + public string text { get; set; } + /// + /// The top class found for the text. + /// + public string top_class { get; set; } + /// + /// A array of all classifications for the input text. + /// + public Class[] classes { get; set; } - /// - /// Helper function to return the top confidence value of all the returned classes. - /// - public double topConfidence + /// + /// Helper function to return the top confidence value of all the returned classes. + /// + public double topConfidence + { + get + { + double fTop = 0.0; + if (classes != null) { - get - { - double fTop = 0.0; - if (classes != null) - { - foreach (var c in classes) - fTop = Math.Max(c.confidence, fTop); - } - return fTop; - } + foreach (var c in classes) + fTop = Math.Max(c.confidence, fTop); } - }; + return fTop; + } + } + }; } diff --git a/Scripts/Services/NaturalLanguageClassifier/NaturalLanguageClassifier.cs b/Scripts/Services/NaturalLanguageClassifier/NaturalLanguageClassifier.cs old mode 100644 new mode 100755 index afd989b19..7469a8497 --- a/Scripts/Services/NaturalLanguageClassifier/NaturalLanguageClassifier.cs +++ b/Scripts/Services/NaturalLanguageClassifier/NaturalLanguageClassifier.cs @@ -26,605 +26,605 @@ namespace IBM.Watson.DeveloperCloud.Services.NaturalLanguageClassifier.v1 { - /// - /// This class wraps the Natural Language Classifier service. - /// Natural Language Classifier Service - /// - public class NaturalLanguageClassifier : IWatsonService + /// + /// This class wraps the Natural Language Classifier service. + /// Natural Language Classifier Service + /// + public class NaturalLanguageClassifier : IWatsonService + { + #region Public Types + /// + /// Callback used by the GetClassifier() method. + /// + /// The classifier found by ID. + public delegate void OnGetClassifier(Classifier classifier); + /// + /// Callback used by the TrainClassifier() method. + /// + /// The classifier created. + public delegate void OnTrainClassifier(Classifier classifier); + /// + /// Callback used by FindClassifier(). + /// + /// The classifer found by name. + public delegate void OnFindClassifier(Classifier classifier); + + /// + /// The callback used by the GetClassifiers() method. + /// + /// + public delegate void OnGetClassifiers(Classifiers classifiers); + + /// + /// This callback is used by the Classify() method. + /// + /// + public delegate void OnClassify(ClassifyResult classify); + /// + /// This callback is used by the DeleteClassifier() method. + /// + /// + public delegate void OnDeleteClassifier(bool success); + #endregion + + #region Public Properties + /// + /// Disable the classify cache. + /// + public bool DisableCache { get; set; } + #endregion + + #region Private Data + private const string SERVICE_ID = "NaturalLanguageClassifierV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + private Dictionary m_ClassifyCache = new Dictionary(); + #endregion + + #region FindClassifier + /// + /// Find a classifier by name. + /// + /// + /// + public void FindClassifier(string classifierName, OnFindClassifier callback) { - #region Public Types - /// - /// Callback used by the GetClassifier() method. - /// - /// The classifier found by ID. - public delegate void OnGetClassifier(Classifier classifier); - /// - /// Callback used by the TrainClassifier() method. - /// - /// The classifier created. - public delegate void OnTrainClassifier(Classifier classifier); - /// - /// Callback used by FindClassifier(). - /// - /// The classifer found by name. - public delegate void OnFindClassifier(Classifier classifier); - - /// - /// The callback used by the GetClassifiers() method. - /// - /// - public delegate void OnGetClassifiers(Classifiers classifiers); - - /// - /// This callback is used by the Classify() method. - /// - /// - public delegate void OnClassify(ClassifyResult classify); - /// - /// This callback is used by the DeleteClassifier() method. - /// - /// - public delegate void OnDeleteClassifier(bool success); - #endregion - - #region Public Properties - /// - /// Disable the classify cache. - /// - public bool DisableCache { get; set; } - #endregion - - #region Private Data - private const string SERVICE_ID = "NaturalLanguageClassifierV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - private Dictionary m_ClassifyCache = new Dictionary(); - #endregion - - #region FindClassifier - /// - /// Find a classifier by name. - /// - /// - /// - public void FindClassifier(string classifierName, OnFindClassifier callback) - { - new FindClassifierReq(this, classifierName, callback); - } + new FindClassifierReq(this, classifierName, callback); + } - private class FindClassifierReq + private class FindClassifierReq + { + public FindClassifierReq(NaturalLanguageClassifier service, string classifierName, OnFindClassifier callback) + { + if (service == null) + throw new ArgumentNullException("service"); + if (string.IsNullOrEmpty(classifierName)) + throw new ArgumentNullException("classifierName"); + if (callback == null) + throw new ArgumentNullException("callback"); + + Service = service; + ClassifierName = classifierName; + Callback = callback; + + Service.GetClassifiers(GetClassifiers); + } + + public NaturalLanguageClassifier Service { get; set; } + public string ClassifierName { get; set; } + public OnFindClassifier Callback { get; set; } + + private void GetClassifiers(Classifiers classifiers) + { + bool bFound = false; + foreach (var c in classifiers.classifiers) + if (c.name.ToLower().StartsWith(ClassifierName.ToLower())) + { + // now get the classifier details.. + bFound = Service.GetClassifier(c.classifier_id, GetClassifier); + break; + } + + if (!bFound) { - public FindClassifierReq(NaturalLanguageClassifier service, string classifierName, OnFindClassifier callback) - { - if (service == null) - throw new ArgumentNullException("service"); - if (string.IsNullOrEmpty(classifierName)) - throw new ArgumentNullException("classifierName"); - if (callback == null) - throw new ArgumentNullException("callback"); - - Service = service; - ClassifierName = classifierName; - Callback = callback; - - Service.GetClassifiers(GetClassifiers); - } + Log.Error("Natural Language Classifier", "Fail to find classifier {0}", ClassifierName); + Callback(null); + } + } + + private void GetClassifier(Classifier classifier) + { + if (Callback != null) + Callback(classifier); + } + }; + #endregion + + #region GetClassifiers + /// + /// Returns an array of all classifiers to the callback function. + /// + /// The callback to invoke with the Classifiers object. + /// Returns true if the request is submitted. + public bool GetClassifiers(OnGetClassifiers callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); - public NaturalLanguageClassifier Service { get; set; } - public string ClassifierName { get; set; } - public OnFindClassifier Callback { get; set; } + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers"); + if (connector == null) + return false; - private void GetClassifiers(Classifiers classifiers) - { - bool bFound = false; - foreach (var c in classifiers.classifiers) - if (c.name.ToLower().StartsWith(ClassifierName.ToLower())) - { - // now get the classifier details.. - bFound = Service.GetClassifier(c.classifier_id, GetClassifier); - break; - } - - if (!bFound) - { - Log.Error("Natural Language Classifier", "Fail to find classifier {0}", ClassifierName); - Callback(null); - } - } + GetClassifiersReq req = new GetClassifiersReq(); + req.Callback = callback; + req.OnResponse = OnGetClassifiersResp; - private void GetClassifier(Classifier classifier) - { - if (Callback != null) - Callback(classifier); - } - }; - #endregion - - #region GetClassifiers - /// - /// Returns an array of all classifiers to the callback function. - /// - /// The callback to invoke with the Classifiers object. - /// Returns true if the request is submitted. - public bool GetClassifiers(OnGetClassifiers callback) + return connector.Send(req); + } + private class GetClassifiersReq : RESTConnector.Request + { + public OnGetClassifiers Callback { get; set; } + }; + private void OnGetClassifiersResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Classifiers classifiers = new Classifiers(); + if (resp.Success) + { + try { - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers"); - if (connector == null) - return false; - - GetClassifiersReq req = new GetClassifiersReq(); - req.Callback = callback; - req.OnResponse = OnGetClassifiersResp; - - return connector.Send(req); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = classifiers; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - private class GetClassifiersReq : RESTConnector.Request + catch (Exception e) { - public OnGetClassifiers Callback { get; set; } - }; - private void OnGetClassifiersResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Classifiers classifiers = new Classifiers(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = classifiers; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetClassifiersReq)req).Callback != null) - ((GetClassifiersReq)req).Callback(resp.Success ? classifiers : null); + Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); + resp.Success = false; } - #endregion - - #region GetClassifier - /// - /// Returns a specific classifer. - /// - /// The ID of the classifier to get. - /// The callback to invoke with the Classifier object. - /// Returns true if the request is submitted. - public bool GetClassifier(string classifierId, OnGetClassifier callback) - { - if (string.IsNullOrEmpty(classifierId)) - throw new ArgumentNullException("classifierId"); - if (callback == null) - throw new ArgumentNullException("callback"); + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers/" + classifierId); - if (connector == null) - return false; + if (((GetClassifiersReq)req).Callback != null) + ((GetClassifiersReq)req).Callback(resp.Success ? classifiers : null); + } + #endregion + + #region GetClassifier + /// + /// Returns a specific classifer. + /// + /// The ID of the classifier to get. + /// The callback to invoke with the Classifier object. + /// Returns true if the request is submitted. + public bool GetClassifier(string classifierId, OnGetClassifier callback) + { + if (string.IsNullOrEmpty(classifierId)) + throw new ArgumentNullException("classifierId"); + if (callback == null) + throw new ArgumentNullException("callback"); - GetClassifierReq req = new GetClassifierReq(); - req.Callback = callback; - req.OnResponse = OnGetClassifierResp; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers/" + classifierId); + if (connector == null) + return false; - return connector.Send(req); - } - private class GetClassifierReq : RESTConnector.Request - { - public OnGetClassifier Callback { get; set; } - }; - private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Classifier classifier = new Classifier(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = classifier; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); - resp.Success = false; - } - } + GetClassifierReq req = new GetClassifierReq(); + req.Callback = callback; + req.OnResponse = OnGetClassifierResp; - if (((GetClassifierReq)req).Callback != null) - ((GetClassifierReq)req).Callback(resp.Success ? classifier : null); - } - #endregion - - #region TrainClassifier - /// - /// Train a new classifier. - /// - /// A name to give the classifier. - /// Language of the classifier. - /// CSV training data. - /// Callback to invoke with the results. - /// Returns true if training data was submitted correctly. - public bool TrainClassifier(string classifierName, string language, string trainingData, OnTrainClassifier callback) + return connector.Send(req); + } + private class GetClassifierReq : RESTConnector.Request + { + public OnGetClassifier Callback { get; set; } + }; + private void OnGetClassifierResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Classifier classifier = new Classifier(); + if (resp.Success) + { + try { - if (string.IsNullOrEmpty(classifierName)) - throw new ArgumentNullException("classifierId"); - if (string.IsNullOrEmpty(language)) - throw new ArgumentNullException("language"); - if (string.IsNullOrEmpty(trainingData)) - throw new ArgumentNullException("trainingData"); - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers"); - if (connector == null) - return false; - - Dictionary trainingMetaData = new Dictionary(); - trainingMetaData["language"] = language; - trainingMetaData["name"] = classifierName; - - TrainClassifierReq req = new TrainClassifierReq(); - req.Callback = callback; - req.OnResponse = OnTrainClassifierResp; - req.Forms = new Dictionary(); - req.Forms["training_metadata"] = new RESTConnector.Form(Encoding.UTF8.GetBytes(Json.Serialize(trainingMetaData))); - req.Forms["training_data"] = new RESTConnector.Form(Encoding.UTF8.GetBytes(trainingData)); - - return connector.Send(req); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = classifier; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - private class TrainClassifierReq : RESTConnector.Request - { - public OnTrainClassifier Callback { get; set; } - }; - private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Response resp) + catch (Exception e) { - Classifier classifier = new Classifier(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = classifier; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); - resp.Success = false; - } - } + Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); + resp.Success = false; + } + } - if (((TrainClassifierReq)req).Callback != null) - ((TrainClassifierReq)req).Callback(resp.Success ? classifier : null); + if (((GetClassifierReq)req).Callback != null) + ((GetClassifierReq)req).Callback(resp.Success ? classifier : null); + } + #endregion + + #region TrainClassifier + /// + /// Train a new classifier. + /// + /// A name to give the classifier. + /// Language of the classifier. + /// CSV training data. + /// Callback to invoke with the results. + /// Returns true if training data was submitted correctly. + public bool TrainClassifier(string classifierName, string language, string trainingData, OnTrainClassifier callback) + { + if (string.IsNullOrEmpty(classifierName)) + throw new ArgumentNullException("classifierId"); + if (string.IsNullOrEmpty(language)) + throw new ArgumentNullException("language"); + if (string.IsNullOrEmpty(trainingData)) + throw new ArgumentNullException("trainingData"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers"); + if (connector == null) + return false; + + Dictionary trainingMetaData = new Dictionary(); + trainingMetaData["language"] = language; + trainingMetaData["name"] = classifierName; + + TrainClassifierReq req = new TrainClassifierReq(); + req.Callback = callback; + req.OnResponse = OnTrainClassifierResp; + req.Forms = new Dictionary(); + req.Forms["training_metadata"] = new RESTConnector.Form(Encoding.UTF8.GetBytes(Json.Serialize(trainingMetaData))); + req.Forms["training_data"] = new RESTConnector.Form(Encoding.UTF8.GetBytes(trainingData)); + + return connector.Send(req); + } + private class TrainClassifierReq : RESTConnector.Request + { + public OnTrainClassifier Callback { get; set; } + }; + private void OnTrainClassifierResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Classifier classifier = new Classifier(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = classifier; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region DeleteClassifier - /// - /// Deletes the specified classifier. - /// - /// The ID of the classifier. - /// The callback to invoke with the results. - /// Returns false if we failed to submit a request. - public bool DeleteClassifer(string classifierId, OnDeleteClassifier callback) + catch (Exception e) { - if (string.IsNullOrEmpty(classifierId)) - throw new ArgumentNullException("classiferId"); - if (callback == null) - throw new ArgumentNullException("callback"); + Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); + resp.Success = false; + } + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers/" + classifierId); - if (connector == null) - return false; + if (((TrainClassifierReq)req).Callback != null) + ((TrainClassifierReq)req).Callback(resp.Success ? classifier : null); + } + #endregion + + #region DeleteClassifier + /// + /// Deletes the specified classifier. + /// + /// The ID of the classifier. + /// The callback to invoke with the results. + /// Returns false if we failed to submit a request. + public bool DeleteClassifer(string classifierId, OnDeleteClassifier callback) + { + if (string.IsNullOrEmpty(classifierId)) + throw new ArgumentNullException("classiferId"); + if (callback == null) + throw new ArgumentNullException("callback"); - DeleteClassifierReq req = new DeleteClassifierReq(); - req.Callback = callback; - req.OnResponse = OnDeleteClassifierResp; - req.Delete = true; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers/" + classifierId); + if (connector == null) + return false; - return connector.Send(req); - } - private class DeleteClassifierReq : RESTConnector.Request - { - public OnDeleteClassifier Callback { get; set; } - }; - private void OnDeleteClassifierResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteClassifierReq)req).Callback != null) - ((DeleteClassifierReq)req).Callback(resp.Success); - } - #endregion - - #region Classify - /// - /// Flush all classifier caches or a specific cache. - /// - /// If not null or empty, then the specific cache will be flushed. - public void FlushClassifyCache(string classifierId = null) + DeleteClassifierReq req = new DeleteClassifierReq(); + req.Callback = callback; + req.OnResponse = OnDeleteClassifierResp; + req.Delete = true; + + return connector.Send(req); + } + private class DeleteClassifierReq : RESTConnector.Request + { + public OnDeleteClassifier Callback { get; set; } + }; + private void OnDeleteClassifierResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteClassifierReq)req).Callback != null) + ((DeleteClassifierReq)req).Callback(resp.Success); + } + #endregion + + #region Classify + /// + /// Flush all classifier caches or a specific cache. + /// + /// If not null or empty, then the specific cache will be flushed. + public void FlushClassifyCache(string classifierId = null) + { + if (!string.IsNullOrEmpty(classifierId)) + { + DataCache cache = null; + if (m_ClassifyCache.TryGetValue(classifierId, out cache)) + cache.Flush(); + } + else + { + foreach (var kp in m_ClassifyCache) + kp.Value.Flush(); + } + } + + /// + /// Classifies the given text, invokes the callback with the results. + /// + /// The ID of the classifier to use. + /// The text to classify. + /// The callback to invoke with the results. + /// Returns false if we failed to submit the request. + public bool Classify(string classifierId, string text, OnClassify callback) + { + if (string.IsNullOrEmpty(classifierId)) + throw new ArgumentNullException("classifierId"); + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (callback == null) + throw new ArgumentNullException("callback"); + + string textId = Utility.GetMD5(text); + if (!DisableCache) + { + DataCache cache = null; + if (!m_ClassifyCache.TryGetValue(classifierId, out cache)) { - if (!string.IsNullOrEmpty(classifierId)) - { - DataCache cache = null; - if (m_ClassifyCache.TryGetValue(classifierId, out cache)) - cache.Flush(); - } - else - { - foreach (var kp in m_ClassifyCache) - kp.Value.Flush(); - } + cache = new DataCache("NaturalLanguageClassifier_" + classifierId); + m_ClassifyCache[classifierId] = cache; } - /// - /// Classifies the given text, invokes the callback with the results. - /// - /// The ID of the classifier to use. - /// The text to classify. - /// The callback to invoke with the results. - /// Returns false if we failed to submit the request. - public bool Classify(string classifierId, string text, OnClassify callback) + byte[] cached = cache.Find(textId); + if (cached != null) { - if (string.IsNullOrEmpty(classifierId)) - throw new ArgumentNullException("classifierId"); - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (callback == null) - throw new ArgumentNullException("callback"); - - string textId = Utility.GetMD5(text); - if (!DisableCache) - { - DataCache cache = null; - if (!m_ClassifyCache.TryGetValue(classifierId, out cache)) - { - cache = new DataCache("NaturalLanguageClassifier_" + classifierId); - m_ClassifyCache[classifierId] = cache; - } - - byte[] cached = cache.Find(textId); - if (cached != null) - { - ClassifyResult res = ProcessClassifyResult(cached); - if (res != null) - { - callback(res); - return true; - } - } - } + ClassifyResult res = ProcessClassifyResult(cached); + if (res != null) + { + callback(res); + return true; + } + } + } - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers"); - if (connector == null) - return false; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/classifiers"); + if (connector == null) + return false; - ClassifyReq req = new ClassifyReq(); - req.TextId = textId; - req.ClassiferId = classifierId; - req.Callback = callback; - req.OnResponse = OnClassifyResp; - req.Function = "/" + classifierId + "/classify"; - req.Headers["Content-Type"] = "application/json"; + ClassifyReq req = new ClassifyReq(); + req.TextId = textId; + req.ClassiferId = classifierId; + req.Callback = callback; + req.OnResponse = OnClassifyResp; + req.Function = "/" + classifierId + "/classify"; + req.Headers["Content-Type"] = "application/json"; - Dictionary body = new Dictionary(); - body["text"] = text; - req.Send = Encoding.UTF8.GetBytes(Json.Serialize(body)); + Dictionary body = new Dictionary(); + body["text"] = text; + req.Send = Encoding.UTF8.GetBytes(Json.Serialize(body)); - return connector.Send(req); - } - private class ClassifyReq : RESTConnector.Request - { - public string TextId { get; set; } - public string ClassiferId { get; set; } - public OnClassify Callback { get; set; } - }; + return connector.Send(req); + } + private class ClassifyReq : RESTConnector.Request + { + public string TextId { get; set; } + public string ClassiferId { get; set; } + public OnClassify Callback { get; set; } + }; - private void OnClassifyResp(RESTConnector.Request req, RESTConnector.Response resp) + private void OnClassifyResp(RESTConnector.Request req, RESTConnector.Response resp) + { + ClassifyResult classify = null; + if (resp.Success) + { + classify = ProcessClassifyResult(resp.Data); + if (classify != null) { - ClassifyResult classify = null; - if (resp.Success) - { - classify = ProcessClassifyResult(resp.Data); - if (classify != null) - { - DataCache cache = null; - if (m_ClassifyCache.TryGetValue(((ClassifyReq)req).ClassiferId, out cache)) - cache.Save(((ClassifyReq)req).TextId, resp.Data); - } - } - - if (((ClassifyReq)req).Callback != null) - ((ClassifyReq)req).Callback(classify); + DataCache cache = null; + if (m_ClassifyCache.TryGetValue(((ClassifyReq)req).ClassiferId, out cache)) + cache.Save(((ClassifyReq)req).TextId, resp.Data); } + } - private ClassifyResult ProcessClassifyResult(byte[] json_data) - { - ClassifyResult classify = null; - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(json_data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); + if (((ClassifyReq)req).Callback != null) + ((ClassifyReq)req).Callback(classify); + } - classify = new ClassifyResult(); + private ClassifyResult ProcessClassifyResult(byte[] json_data) + { + ClassifyResult classify = null; + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(json_data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + classify = new ClassifyResult(); + + object obj = classify; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); + } + + return classify; + } - object obj = classify; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetClassifiers Exception: {0}", e.ToString()); - } + #endregion - return classify; - } + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - #endregion + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } - #region IWatsonService interface - /// - public string GetServiceID() + private class CheckServiceStatus + { + private NaturalLanguageClassifier m_Service = null; + private ServiceStatus m_Callback = null; + private int m_GetClassifierCount = 0; + private int m_ClassifyCount = 0; + + public CheckServiceStatus(NaturalLanguageClassifier service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + string customClassifierID = Config.Instance.GetVariableValue(SERVICE_ID + "_ID"); + m_Service.DisableCache = true; + //If custom classifierID is defined then we are using it to check the service health + if (!string.IsNullOrEmpty(customClassifierID)) { - return SERVICE_ID; - } - /// - public void GetServiceStatus(ServiceStatus callback) + if (!m_Service.GetClassifier(customClassifierID, OnCheckService)) + { + OnFailure("Failed to call GetClassifier()"); + } + else + { + m_GetClassifierCount += 1; + } + } + else { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); + if (!m_Service.GetClassifiers(OnCheckServices)) + OnFailure("Failed to call GetClassifiers()"); } - private class CheckServiceStatus - { - private NaturalLanguageClassifier m_Service = null; - private ServiceStatus m_Callback = null; - private int m_GetClassifierCount = 0; - private int m_ClassifyCount = 0; + } - public CheckServiceStatus(NaturalLanguageClassifier service, ServiceStatus callback) + private void OnCheckServices(Classifiers classifiers) + { + if (m_Callback != null) + { + if (classifiers.classifiers.Length > 0) + { + foreach (var classifier in classifiers.classifiers) { - m_Service = service; - m_Callback = callback; - - string customClassifierID = Config.Instance.GetVariableValue(SERVICE_ID + "_ID"); - m_Service.DisableCache = true; - //If custom classifierID is defined then we are using it to check the service health - if (!string.IsNullOrEmpty(customClassifierID)) - { - - if (!m_Service.GetClassifier(customClassifierID, OnCheckService)) - { - OnFailure("Failed to call GetClassifier()"); - } - else - { - m_GetClassifierCount += 1; - } - } - else - { - if (!m_Service.GetClassifiers(OnCheckServices)) - OnFailure("Failed to call GetClassifiers()"); - } - + // check the status of one classifier, if it's listed as "Unavailable" then fail + if (!m_Service.GetClassifier(classifier.classifier_id, OnCheckService)) + { + OnFailure("Failed to call GetClassifier()"); + break; + } + else + m_GetClassifierCount += 1; } - - private void OnCheckServices(Classifiers classifiers) + } + else + { + if (m_Callback != null && m_Callback.Target != null) { - if (m_Callback != null) - { - if (classifiers.classifiers.Length > 0) - { - foreach (var classifier in classifiers.classifiers) - { - // check the status of one classifier, if it's listed as "Unavailable" then fail - if (!m_Service.GetClassifier(classifier.classifier_id, OnCheckService)) - { - OnFailure("Failed to call GetClassifier()"); - break; - } - else - m_GetClassifierCount += 1; - } - } - else - { - if (m_Callback != null && m_Callback.Target != null) - { - m_Callback(SERVICE_ID, true); // no classifiers to check, just return success then.. - } - } - } - else - { - if (m_Callback != null && m_Callback.Target != null) - { - m_Callback(SERVICE_ID, false); - } - } + m_Callback(SERVICE_ID, true); // no classifiers to check, just return success then.. } + } + } + else + { + if (m_Callback != null && m_Callback.Target != null) + { + m_Callback(SERVICE_ID, false); + } + } + } - private void OnCheckService(Classifier classifier) + private void OnCheckService(Classifier classifier) + { + if (m_GetClassifierCount > 0) + { + m_GetClassifierCount -= 1; + if (classifier != null) + { + if (classifier.status == "Unavailable" || classifier.status == "Failed") { - if (m_GetClassifierCount > 0) - { - m_GetClassifierCount -= 1; - if (classifier != null) - { - if (classifier.status == "Unavailable" || classifier.status == "Failed") - { - OnFailure(string.Format("Status of classifier {0} came back as {1}.", - classifier.classifier_id, classifier.status)); - } - else - { - // try to classify something with this classifier.. - if (!m_Service.Classify(classifier.classifier_id, "Hello World", OnClassify)) - OnFailure("Failed to invoke Classify"); - else - m_ClassifyCount += 1; - } - } - else - OnFailure("Failed to get classifier."); - } + OnFailure(string.Format("Status of classifier {0} came back as {1}.", + classifier.classifier_id, classifier.status)); } - - private void OnClassify(ClassifyResult result) + else { - if (m_ClassifyCount > 0) - { - m_ClassifyCount -= 1; - if (result != null) - { - // success! - if (m_ClassifyCount == 0 && m_Callback != null && m_Callback.Target != null) - { - m_Callback(SERVICE_ID, true); - } - } - else - OnFailure("Failed to classify."); - } + // try to classify something with this classifier.. + if (!m_Service.Classify(classifier.classifier_id, "Hello World", OnClassify)) + OnFailure("Failed to invoke Classify"); + else + m_ClassifyCount += 1; } + } + else + OnFailure("Failed to get classifier."); + } + } - void OnFailure(string msg) + private void OnClassify(ClassifyResult result) + { + if (m_ClassifyCount > 0) + { + m_ClassifyCount -= 1; + if (result != null) + { + // success! + if (m_ClassifyCount == 0 && m_Callback != null && m_Callback.Target != null) { - Log.Error("NaturalLanguageClassifier", msg); - if (m_Callback != null && m_Callback.Target != null) - { - m_Callback(SERVICE_ID, false); - } - m_GetClassifierCount = m_ClassifyCount = 0; + m_Callback(SERVICE_ID, true); } + } + else + OnFailure("Failed to classify."); + } + } - }; - #endregion - } + void OnFailure(string msg) + { + Log.Error("NaturalLanguageClassifier", msg); + if (m_Callback != null && m_Callback.Target != null) + { + m_Callback(SERVICE_ID, false); + } + m_GetClassifierCount = m_ClassifyCount = 0; + } + + }; + #endregion + } } diff --git a/Scripts/Services/PersonalityInsights/v2/DataModels.cs b/Scripts/Services/PersonalityInsights/v2/DataModels.cs old mode 100644 new mode 100755 index d72b75123..086070227 --- a/Scripts/Services/PersonalityInsights/v2/DataModels.cs +++ b/Scripts/Services/PersonalityInsights/v2/DataModels.cs @@ -21,256 +21,256 @@ namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v2 { - /// - /// The profile result from Personality Insights. - /// - [fsObject] - public class Profile - { - /// - /// Detailed results for a specific characteristic of the input text. - /// - /// The tree. - public TraitTreeNode tree { get; set; } - - /// - /// The unique user identifier for which these characteristics were computed. The value is derived from the userid field of the input ContentItem objects. The field is passed as-is from JSON input. Sanitize the contents of the field before displaying them to prevent cross-site scripting attacks. - /// - /// The identifier. - public string id { get; set; } - - /// - /// The source identifier for which these characteristics were computed. The value is derived from the sourceid field of the input ContentItem objects. The field is passed as-is from JSON input. Sanitize the contents of the field before displaying them to prevent cross-site scripting attacks. - /// - /// The source. - public string source { get; set; } - - /// - /// The language model that was used to process the input; for example, en. - /// - /// The processed lang. - public string processed_lang { get; set; } - - /// - /// The number of words that were found in the input. - /// - /// The word count. - public string word_count { get; set; } - - /// - /// When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. - /// - /// The word count message. - public string word_count_message { get; set; } - - /// - /// Warning messages associated with the input text submitted with the request. The array is empty if the input generated no warnings. - /// - /// The warnings. - public Warning[] warnings { get; set; } - } - - /// - /// The trait tree node of the trait tree. - /// - [fsObject] - public class TraitTreeNode - { - /// - /// The unique identifier of the characteristic to which the results pertain. - /// - /// The identifier. - public string id { get; set; } - - /// - /// The user-visible name of the characteristic. - /// - /// The name. - public string name { get; set; } - - /// - /// The category of the characteristic: personality, needs, values, or behavior (for temporal data). - /// - /// The category. - public string category { get; set; } - - /// - /// For personality, needs, and values characteristics, the normalized percentile score for the characteristic. The range is 0 to 1. For example, if the percentage for Openness is 0.25, the author scored in the 25th percentile; the author is more open than 24% of the population and less open than 74% of the population. For temporal behavior characteristics, the percentage of timestamped data that occurred during that day or hour. - /// - /// The percentage. - public string percentage { get; set; } - - /// - /// For personality, needs, and values characteristics, indicates the sampling error of the percentage based on the number of words in the input text. The range is 0 to 1. The number defines a 95% confidence interval around the percentage. For example, if the sampling error is 4% and the percentage is 61%, it is 95% likely that the actual percentage value is between 57% and 65% if more words are given. - /// - /// The sampling error. - public string sampling_error { get; set; } - - /// - /// For personality, needs, and values characteristics, the raw score for the characteristic. A positive or negative score indicates more or less of the characteristic; zero indicates neutrality or no evidence for a score. The raw score is computed based on the input and the service model; it is not normalized or compared with a sample population. The raw score enables comparison of the results against a different sampling population and with a custom normalization approach. - /// - /// The raw score. - public string raw_score { get; set; } - - /// - /// For personality, needs, and values characteristics, indicates the sampling error of the raw score based on the number of words in the input. The practical range is 0 to 1. The number defines a 95% confidence interval around the raw score. For example, if the raw sampling error is 5% and the raw score is 65%, it is 95% likely that the actual raw score is between 60% and 70% if more words are given. - /// - /// The raw sampling error. - public string raw_sampling_error { get; set; } - - /// - /// Recursive array of more detailed characteristics inferred from the input text. - /// - /// The children. - public TraitTreeNode[] children { get; set; } - } - - /// - /// The warning object. - /// - [fsObject] - public class Warning - { - /// - /// The identifier of the warning message, one of WORD_COUNT_MESSAGE or JSON_AS_TEXT. - /// - /// The identifier. - public string id { get; set; } - - /// - /// The message associated with the id. For WORD_COUNT_MESSAGE, "There were [number] words in the input. We need a minimum of 3,500, preferably 6,000 or more, to compute statistically significant estimates"; for JSON_AS_TEXT, "Request input was processed as text/plain as indicated, however detected a JSON input. Did you mean application/json?". - /// - /// The message. - public string message { get; set; } - } - - /// - /// Holder for content items. - /// - [fsObject] - public class ContentListContainer - { - /// - /// An array of content items for personality insight profile request. - /// - /// The content items. - public ContentItem[] contentItems { get; set; } - } - - /// - /// The content item. - /// - [fsObject] - public class ContentItem - { - /// - /// Unique identifier for this content item. - /// - /// The identifier. - public string id { get; set; } - - /// - /// Unique identifier for the author of this content. - /// - /// The userid. - public string userid { get; set; } - - /// - /// Identifier for the source of this content, for example, blog123 or twitter. - /// - /// The sourceid. - public string sourceid { get; set; } - - /// - /// Timestamp that identifies when this content was created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. - /// - /// The created. - public string created { get; set; } - - /// - /// Timestamp that identifies when this content was last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. - /// - /// The updated. - public string updated { get; set; } - - /// - /// MIME type of the content, for example, text/plain (the default) or text/html. The tags are stripped from HTML content before it is analyzed; other MIME types are processed as is. - /// - /// The contenttype. - public string contenttype { get; set; } - - /// - /// Language identifier (two-letter ISO 639-1 identifier) for the input text: ar (Arabic), en (English), es (Spanish), or ja (Japanese). The default is English. Regional variants are treated as their parent language; for example, en-US is interpreted as en. A language specified with the Content-Type header overrides the value of this parameter; any content items that specify a different language are ignored. Omit the Content-Type header to base the language on the most prevalent specification among the content items; again, content items that specify a different language are ignored. You can specify any combination of languages for the input text and the response (Accept-Language). - /// - /// The language. - public string language { get; set; } - - /// - /// Content to be analyzed. Up to 20 MB of content is supported. - /// - /// The content. - public string content { get; set; } - - /// - /// Unique ID of the parent content item for this item. Used to identify hierarchical relationships between posts/replies, messages/replies, and so on. - /// - /// The parentid. - public string parentid { get; set; } - - /// - /// Indicates whether this content item is a reply to another content item. - /// - /// true if reply; otherwise, false. - public bool reply { get; set; } - - /// - /// Indicates whether this content item is a forwarded/copied version of another content item. - /// - /// true if forward; otherwise, false. - public bool forward { get; set; } - } - - /// - /// The content type. Either text, html or json. - /// - public class ContentType - { - /// - /// Mime type for plain text. - /// - public const string TEXT_PLAIN = "text/plain"; - - /// - /// Mime type for HTML. - /// - public const string TEXT_HTML = "text/html"; - - /// - /// Mime type for json. - /// - public const string APPLICATION_JSON = "application/json"; - } - - /// - /// The content language. Either English, Arabic, Spanish or Japanese. - /// - public class Language - { - /// - /// English. - /// - public const string ENGLISH = "en"; - /// - /// Arabic. - /// - public const string ARABIC = "ar"; - /// - /// Spanish. - /// - public const string SPANISH = "es"; - /// - /// Japanese - /// - public const string JAPANESE = "ja"; - } + /// + /// The profile result from Personality Insights. + /// + [fsObject] + public class Profile + { + /// + /// Detailed results for a specific characteristic of the input text. + /// + /// The tree. + public TraitTreeNode tree { get; set; } + + /// + /// The unique user identifier for which these characteristics were computed. The value is derived from the userid field of the input ContentItem objects. The field is passed as-is from JSON input. Sanitize the contents of the field before displaying them to prevent cross-site scripting attacks. + /// + /// The identifier. + public string id { get; set; } + + /// + /// The source identifier for which these characteristics were computed. The value is derived from the sourceid field of the input ContentItem objects. The field is passed as-is from JSON input. Sanitize the contents of the field before displaying them to prevent cross-site scripting attacks. + /// + /// The source. + public string source { get; set; } + + /// + /// The language model that was used to process the input; for example, en. + /// + /// The processed lang. + public string processed_lang { get; set; } + + /// + /// The number of words that were found in the input. + /// + /// The word count. + public string word_count { get; set; } + + /// + /// When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. + /// + /// The word count message. + public string word_count_message { get; set; } + + /// + /// Warning messages associated with the input text submitted with the request. The array is empty if the input generated no warnings. + /// + /// The warnings. + public Warning[] warnings { get; set; } + } + + /// + /// The trait tree node of the trait tree. + /// + [fsObject] + public class TraitTreeNode + { + /// + /// The unique identifier of the characteristic to which the results pertain. + /// + /// The identifier. + public string id { get; set; } + + /// + /// The user-visible name of the characteristic. + /// + /// The name. + public string name { get; set; } + + /// + /// The category of the characteristic: personality, needs, values, or behavior (for temporal data). + /// + /// The category. + public string category { get; set; } + + /// + /// For personality, needs, and values characteristics, the normalized percentile score for the characteristic. The range is 0 to 1. For example, if the percentage for Openness is 0.25, the author scored in the 25th percentile; the author is more open than 24% of the population and less open than 74% of the population. For temporal behavior characteristics, the percentage of timestamped data that occurred during that day or hour. + /// + /// The percentage. + public string percentage { get; set; } + + /// + /// For personality, needs, and values characteristics, indicates the sampling error of the percentage based on the number of words in the input text. The range is 0 to 1. The number defines a 95% confidence interval around the percentage. For example, if the sampling error is 4% and the percentage is 61%, it is 95% likely that the actual percentage value is between 57% and 65% if more words are given. + /// + /// The sampling error. + public string sampling_error { get; set; } + + /// + /// For personality, needs, and values characteristics, the raw score for the characteristic. A positive or negative score indicates more or less of the characteristic; zero indicates neutrality or no evidence for a score. The raw score is computed based on the input and the service model; it is not normalized or compared with a sample population. The raw score enables comparison of the results against a different sampling population and with a custom normalization approach. + /// + /// The raw score. + public string raw_score { get; set; } + + /// + /// For personality, needs, and values characteristics, indicates the sampling error of the raw score based on the number of words in the input. The practical range is 0 to 1. The number defines a 95% confidence interval around the raw score. For example, if the raw sampling error is 5% and the raw score is 65%, it is 95% likely that the actual raw score is between 60% and 70% if more words are given. + /// + /// The raw sampling error. + public string raw_sampling_error { get; set; } + + /// + /// Recursive array of more detailed characteristics inferred from the input text. + /// + /// The children. + public TraitTreeNode[] children { get; set; } + } + + /// + /// The warning object. + /// + [fsObject] + public class Warning + { + /// + /// The identifier of the warning message, one of WORD_COUNT_MESSAGE or JSON_AS_TEXT. + /// + /// The identifier. + public string id { get; set; } + + /// + /// The message associated with the id. For WORD_COUNT_MESSAGE, "There were [number] words in the input. We need a minimum of 3,500, preferably 6,000 or more, to compute statistically significant estimates"; for JSON_AS_TEXT, "Request input was processed as text/plain as indicated, however detected a JSON input. Did you mean application/json?". + /// + /// The message. + public string message { get; set; } + } + + /// + /// Holder for content items. + /// + [fsObject] + public class ContentListContainer + { + /// + /// An array of content items for personality insight profile request. + /// + /// The content items. + public ContentItem[] contentItems { get; set; } + } + + /// + /// The content item. + /// + [fsObject] + public class ContentItem + { + /// + /// Unique identifier for this content item. + /// + /// The identifier. + public string id { get; set; } + + /// + /// Unique identifier for the author of this content. + /// + /// The userid. + public string userid { get; set; } + + /// + /// Identifier for the source of this content, for example, blog123 or twitter. + /// + /// The sourceid. + public string sourceid { get; set; } + + /// + /// Timestamp that identifies when this content was created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. + /// + /// The created. + public string created { get; set; } + + /// + /// Timestamp that identifies when this content was last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at 0:00 UTC). Required only for results that include temporal behavior data. + /// + /// The updated. + public string updated { get; set; } + + /// + /// MIME type of the content, for example, text/plain (the default) or text/html. The tags are stripped from HTML content before it is analyzed; other MIME types are processed as is. + /// + /// The contenttype. + public string contenttype { get; set; } + + /// + /// Language identifier (two-letter ISO 639-1 identifier) for the input text: ar (Arabic), en (English), es (Spanish), or ja (Japanese). The default is English. Regional variants are treated as their parent language; for example, en-US is interpreted as en. A language specified with the Content-Type header overrides the value of this parameter; any content items that specify a different language are ignored. Omit the Content-Type header to base the language on the most prevalent specification among the content items; again, content items that specify a different language are ignored. You can specify any combination of languages for the input text and the response (Accept-Language). + /// + /// The language. + public string language { get; set; } + + /// + /// Content to be analyzed. Up to 20 MB of content is supported. + /// + /// The content. + public string content { get; set; } + + /// + /// Unique ID of the parent content item for this item. Used to identify hierarchical relationships between posts/replies, messages/replies, and so on. + /// + /// The parentid. + public string parentid { get; set; } + + /// + /// Indicates whether this content item is a reply to another content item. + /// + /// true if reply; otherwise, false. + public bool reply { get; set; } + + /// + /// Indicates whether this content item is a forwarded/copied version of another content item. + /// + /// true if forward; otherwise, false. + public bool forward { get; set; } + } + + /// + /// The content type. Either text, html or json. + /// + public class ContentType + { + /// + /// Mime type for plain text. + /// + public const string TEXT_PLAIN = "text/plain"; + + /// + /// Mime type for HTML. + /// + public const string TEXT_HTML = "text/html"; + + /// + /// Mime type for json. + /// + public const string APPLICATION_JSON = "application/json"; + } + + /// + /// The content language. Either English, Arabic, Spanish or Japanese. + /// + public class Language + { + /// + /// English. + /// + public const string ENGLISH = "en"; + /// + /// Arabic. + /// + public const string ARABIC = "ar"; + /// + /// Spanish. + /// + public const string SPANISH = "es"; + /// + /// Japanese + /// + public const string JAPANESE = "ja"; + } } diff --git a/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs index 48b477c9a..3318e4f4e 100755 --- a/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs +++ b/Scripts/Services/PersonalityInsights/v2/PersonalityInsights.cs @@ -26,162 +26,162 @@ namespace IBM.Watson.DeveloperCloud.Services.PersonalityInsights.v2 { - /// - /// This class wraps the Personality Insights service. - /// Personality Insights Service - /// - public class PersonalityInsights : IWatsonService + /// + /// This class wraps the Personality Insights service. + /// Personality Insights Service + /// + public class PersonalityInsights : IWatsonService + { + #region Private Data + private const string SERVICE_ID = "PersonalityInsightsV2"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Profile + private const string SERVICE_GET_PROFILE = "/v2/profile"; + + /// + /// On get profile delegate. + /// + public delegate void OnGetProfile(Profile profile, string data); + + /// + /// Uses Personality Insights to get the source profile. + /// + /// true, if profile was gotten, false otherwise. + /// Callback. + /// Json or Text source. Json data must follow the ContentListContainer Model. + /// Content mime type. + /// Content language. + /// Accept mime type. + /// Accept language. + /// If set to true include raw. + /// If set to true headers. + /// Data. + public bool GetProfile(OnGetProfile callback, string source, + string contentType = ContentType.TEXT_PLAIN, + string contentLanguage = Language.ENGLISH, + string accept = ContentType.APPLICATION_JSON, + string acceptLanguage = Language.ENGLISH, + bool includeRaw = false, + bool headers = false, + string data = default(string)) { - #region Private Data - private const string SERVICE_ID = "PersonalityInsightsV2"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Profile - private const string SERVICE_GET_PROFILE = "/v2/profile"; - - /// - /// On get profile delegate. - /// - public delegate void OnGetProfile(Profile profile, string data); - - /// - /// Uses Personality Insights to get the source profile. - /// - /// true, if profile was gotten, false otherwise. - /// Callback. - /// Json or Text source. Json data must follow the ContentListContainer Model. - /// Content mime type. - /// Content language. - /// Accept mime type. - /// Accept language. - /// If set to true include raw. - /// If set to true headers. - /// Data. - public bool GetProfile(OnGetProfile callback, string source, - string contentType = ContentType.TEXT_PLAIN, - string contentLanguage = Language.ENGLISH, - string accept = ContentType.APPLICATION_JSON, - string acceptLanguage = Language.ENGLISH, - bool includeRaw = false, - bool headers = false, - string data = default(string)) - { - if(callback == null) - throw new ArgumentNullException("callback"); - if(string.IsNullOrEmpty(source)) - throw new ArgumentNullException("A JSON or Text source is required for GetProfile!"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_PROFILE); - if(connector == null) - return false; - - GetProfileRequest req = new GetProfileRequest(); - req.Callback = callback; - req.OnResponse = GetProfileResponse; - - req.Parameters["include_raw"] = includeRaw.ToString(); - req.Parameters["headers"] = headers.ToString(); - - req.Headers["Content-Type"] = contentType; - req.Headers["Content-Language"] = contentLanguage; - req.Headers["Accept"] = accept; - req.Headers["Accept-Language"] = acceptLanguage; - - if (source.StartsWith(Application.dataPath)) - { - string jsonData = default(string); - jsonData = File.ReadAllText(source); - req.Send = System.Text.Encoding.UTF8.GetBytes(jsonData); - } - else - { - req.Send = System.Text.Encoding.UTF8.GetBytes(source); - } - - return connector.Send(req); - } - - /// - /// Get profile request. - /// - public class GetProfileRequest:RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetProfile Callback { get; set; } - } + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(source)) + throw new ArgumentNullException("A JSON or Text source is required for GetProfile!"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_GET_PROFILE); + if (connector == null) + return false; + + GetProfileRequest req = new GetProfileRequest(); + req.Callback = callback; + req.OnResponse = GetProfileResponse; + + req.Parameters["include_raw"] = includeRaw.ToString(); + req.Parameters["headers"] = headers.ToString(); + + req.Headers["Content-Type"] = contentType; + req.Headers["Content-Language"] = contentLanguage; + req.Headers["Accept"] = accept; + req.Headers["Accept-Language"] = acceptLanguage; + + if (source.StartsWith(Application.dataPath)) + { + string jsonData = default(string); + jsonData = File.ReadAllText(source); + req.Send = System.Text.Encoding.UTF8.GetBytes(jsonData); + } + else + { + req.Send = System.Text.Encoding.UTF8.GetBytes(source); + } + + return connector.Send(req); + } - private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - Profile response = new Profile(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetProfileRequest)req).Callback != null) - ((GetProfileRequest)req).Callback(resp.Success ? response : null, ((GetProfileRequest)req).Data); - } - #endregion + /// + /// Get profile request. + /// + public class GetProfileRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetProfile Callback { get; set; } + } - #region IWatsonService implementation - /// - public string GetServiceID() + private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Profile response = new Profile(); + if (resp.Success) + { + try { - return SERVICE_ID; + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - /// - public void GetServiceStatus(ServiceStatus callback) + catch (Exception e) { - if ( Utilities.Config.Instance.FindCredentials( SERVICE_ID ) != null ) - new CheckServiceStatus( this, callback ); - else - callback( SERVICE_ID, false ); + Log.Error("PersonalityInsights", "GetProfileResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - private class CheckServiceStatus - { - private PersonalityInsights m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(PersonalityInsights service, ServiceStatus callback ) - { - m_Service = service; - m_Callback = callback; - string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; - if(!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, Language.ENGLISH)) - m_Callback(SERVICE_ID, false); - } - - private void OnGetProfile(Profile resp , string data) - { - if(m_Callback != null ) - m_Callback(SERVICE_ID, resp != null); - } - }; - #endregion + if (((GetProfileRequest)req).Callback != null) + ((GetProfileRequest)req).Callback(resp.Success ? response : null, ((GetProfileRequest)req).Data); + } + #endregion + + #region IWatsonService implementation + /// + public string GetServiceID() + { + return SERVICE_ID; } + + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Utilities.Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + private class CheckServiceStatus + { + private PersonalityInsights m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(PersonalityInsights service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + string dataPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/personalityInsights.json"; + if (!m_Service.GetProfile(OnGetProfile, dataPath, ContentType.TEXT_PLAIN, Language.ENGLISH)) + m_Callback(SERVICE_ID, false); + } + + private void OnGetProfile(Profile resp, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, resp != null); + } + }; + #endregion + } } \ No newline at end of file diff --git a/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs b/Scripts/Services/PersonalityInsights/v3/PersonalityInsights.cs old mode 100644 new mode 100755 diff --git a/Scripts/Services/RetrieveAndRank/DataModels.cs b/Scripts/Services/RetrieveAndRank/DataModels.cs index bdfae17d5..6757a255f 100755 --- a/Scripts/Services/RetrieveAndRank/DataModels.cs +++ b/Scripts/Services/RetrieveAndRank/DataModels.cs @@ -19,454 +19,454 @@ namespace IBM.Watson.DeveloperCloud.Services.RetrieveAndRank.v1 { - #region Solr Clusters - /// - /// Array of Solr Clusters. - /// - [fsObject] - public class SolrClusterListResponse - { - /// - /// An array of [clusters] that are available for the service instance. - /// - public SolrClusterResponse[] clusters { get; set; } - } + #region Solr Clusters + /// + /// Array of Solr Clusters. + /// + [fsObject] + public class SolrClusterListResponse + { + /// + /// An array of [clusters] that are available for the service instance. + /// + public SolrClusterResponse[] clusters { get; set; } + } + /// + /// Solr cluster object. + /// + [fsObject] + public class SolrClusterResponse + { + /// + /// Unique identifier for this cluster. + /// + public string solr_cluster_id { get; set; } + /// + /// Name that identifies the cluster. + /// + public string cluster_name { get; set; } + /// + /// Size of the cluster to create. + /// + public string cluster_size { get; set; } /// - /// Solr cluster object. - /// - [fsObject] - public class SolrClusterResponse - { - /// - /// Unique identifier for this cluster. - /// - public string solr_cluster_id { get; set; } - /// - /// Name that identifies the cluster. - /// - public string cluster_name { get; set; } - /// - /// Size of the cluster to create. - /// - public string cluster_size { get; set; } - /// - /// The state of the cluster: NOT_AVAILABLE or READY. - /// - public string solr_cluster_status { get; set; } - } + /// The state of the cluster: NOT_AVAILABLE or READY. + /// + public string solr_cluster_status { get; set; } + } + /// + /// Array of Solr Configs. + /// + [fsObject] + public class SolrConfigList + { /// - /// Array of Solr Configs. + /// The Solr configs. /// - [fsObject] - public class SolrConfigList - { - /// - /// The Solr configs. - /// - public string[] solr_configs { get; set; } - } + public string[] solr_configs { get; set; } + } + /// + /// The error response for deleting Solr clusters. + /// + [fsObject] + public class ErrorResponsePayload + { + /// + /// The error message. + /// + public string msg { get; set; } /// - /// The error response for deleting Solr clusters. - /// - [fsObject] - public class ErrorResponsePayload - { - /// - /// The error message. - /// - public string msg { get; set; } - /// - /// The error code. - /// - public int code { get; set; } - } + /// The error code. + /// + public int code { get; set; } + } + /// + /// The response for uploading Solr config. + /// + [fsObject] + public class UploadResponse + { + /// + /// Status message. + /// + public string message { get; set; } /// - /// The response for uploading Solr config. - /// - [fsObject] - public class UploadResponse - { - /// - /// Status message. - /// - public string message { get; set; } - /// - /// Status code. - /// - public string statusCode { get; set; } - } + /// Status code. + /// + public string statusCode { get; set; } + } + /// + /// The response for deleting Solr cluster. + /// + [fsObject] + public class DeleteResponse + { + /// + /// Status message. + /// + public string message { get; set; } /// - /// The response for deleting Solr cluster. - /// - [fsObject] - public class DeleteResponse - { - /// - /// Status message. - /// - public string message { get; set; } - /// - /// Status code. - /// - public string statusCode { get; set; } - } + /// Status code. + /// + public string statusCode { get; set; } + } + /// + /// The response for deleting Solr cluster config. + /// + [fsObject] + public class DeleteConfigResponse + { /// - /// The response for deleting Solr cluster config. - /// - [fsObject] - public class DeleteConfigResponse - { - /// - /// Status message. - /// - public string message { get; set; } - /// - /// Status code. - /// - public string statusCode { get; set; } - } + /// Status message. + /// + public string message { get; set; } + /// + /// Status code. + /// + public string statusCode { get; set; } + } + /// + /// The error response for deleting Solr configs. + /// + [fsObject] + public class MessageResponsePayload + { /// - /// The error response for deleting Solr configs. + /// The error message. /// - [fsObject] - public class MessageResponsePayload - { - /// - /// The error message. - /// - public string message { get; set; } - } + public string message { get; set; } + } + /// + /// Response for listing collections. + /// + [fsObject] + public class CollectionsResponse + { + /// + /// The response header. + /// + public ResponseHeader responseHeader { get; set; } + /// + /// Array of collection names. + /// + public string[] collections { get; set; } + /// + /// Array of CollectionsResponses for each core. + /// + public CollectionsResponse[] response { get; set; } /// - /// Response for listing collections. - /// - [fsObject] - public class CollectionsResponse - { - /// - /// The response header. - /// - public ResponseHeader responseHeader { get; set; } - /// - /// Array of collection names. - /// - public string[] collections { get; set; } - /// - /// Array of CollectionsResponses for each core. - /// - public CollectionsResponse[] response { get; set; } - /// - /// The core name. - /// - public string core { get; set; } - } + /// The core name. + /// + public string core { get; set; } + } + /// + /// Response header for collections actions. + /// + [fsObject] + public class ResponseHeader + { + /// + /// The response status. + /// + public int status { get; set; } /// - /// Response header for collections actions. - /// - [fsObject] - public class ResponseHeader - { - /// - /// The response status. - /// - public int status { get; set; } - /// - /// The response QTime. - /// - public int QTime { get; set; } - /// - /// Params for Solr query - /// - [fsProperty("params")] - public QueryParams _params { get; set; } - } + /// The response QTime. + /// + public int QTime { get; set; } + /// + /// Params for Solr query + /// + [fsProperty("params")] + public QueryParams _params { get; set; } + } + /// + /// Collection actions for CollectionsRequest + /// + public class CollectionsAction + { /// - /// Collection actions for CollectionsRequest - /// - public class CollectionsAction - { - /// - /// List collections. - /// - public const string LIST = "LIST"; - /// - /// Create a collection. - /// - public const string CREATE = "CREATE"; - /// - /// Delete a collection. - /// - public const string DELETE = "DELETE"; - } + /// List collections. + /// + public const string LIST = "LIST"; + /// + /// Create a collection. + /// + public const string CREATE = "CREATE"; + /// + /// Delete a collection. + /// + public const string DELETE = "DELETE"; + } + /// + /// The response for indexing documents. + /// + [fsObject] + public class IndexResponse + { /// - /// The response for indexing documents. + /// The response header. /// - [fsObject] - public class IndexResponse - { - /// - /// The response header. - /// - public ResponseHeader responseHeader { get; set; } - } + public ResponseHeader responseHeader { get; set; } + } - /// - /// The query parameters. - /// - [fsObject] - public class QueryParams - { - /// - /// The query. - /// - public string q { get; set; } - /// - /// The filters. - /// - public string fl { get; set; } - /// - /// The writer type. - /// - public string wt { get; set; } - } + /// + /// The query parameters. + /// + [fsObject] + public class QueryParams + { + /// + /// The query. + /// + public string q { get; set; } + /// + /// The filters. + /// + public string fl { get; set; } + /// + /// The writer type. + /// + public string wt { get; set; } + } + /// + /// The search response + /// + [fsObject] + public class SearchResponse + { /// - /// The search response - /// - [fsObject] - public class SearchResponse - { - /// - /// The response header info. - /// - public ResponseHeader responseHeader { get; set; } - /// - /// The response. - /// - public Response response { get; set; } - } + /// The response header info. + /// + public ResponseHeader responseHeader { get; set; } + /// + /// The response. + /// + public Response response { get; set; } + } + /// + /// The response object. + /// + [fsObject] + public class Response + { /// - /// The response object. - /// - [fsObject] - public class Response - { - /// - /// Number of results found. - /// - public int numFound { get; set; } - /// - /// Start index. - /// - public int start { get; set; } - /// - /// Array of result documents. - /// - public Doc[] docs { get; set; } - } + /// Number of results found. + /// + public int numFound { get; set; } + /// + /// Start index. + /// + public int start { get; set; } + /// + /// Array of result documents. + /// + public Doc[] docs { get; set; } + } + /// + /// The doucment object. + /// + [fsObject] + public class Doc + { /// - /// The doucment object. - /// - [fsObject] - public class Doc - { - /// - /// The document identifier. - /// - public string id { get; set; } - /// - /// The document body. - /// - public string[] body { get; set; } - /// - /// The doucument title. - /// - public string[] title { get; set; } - /// - /// The document author. - /// - public string[] author { get; set; } - /// - /// The bibliography info. - /// - public string[] bibliography { get; set; } - } + /// The document identifier. + /// + public string id { get; set; } + /// + /// The document body. + /// + public string[] body { get; set; } + /// + /// The doucument title. + /// + public string[] title { get; set; } + /// + /// The document author. + /// + public string[] author { get; set; } + /// + /// The bibliography info. + /// + public string[] bibliography { get; set; } + } + + /// + /// Cluster object containing it's associated configs and collections. + /// + public class ClusterInfo + { + /// + /// The Cluster's info. + /// + public SolrClusterResponse Cluster { get; set; } + /// + /// Cluster's configs. + /// + public string[] Configs { get; set; } + /// + /// Cluster's collections. + /// + public string[] Collections { get; set; } + } + #endregion + #region Rankers + /// + /// Array of Rankers. + /// + [fsObject] + public class ListRankersPayload + { /// - /// Cluster object containing it's associated configs and collections. - /// - public class ClusterInfo - { - /// - /// The Cluster's info. - /// - public SolrClusterResponse Cluster { get; set; } - /// - /// Cluster's configs. - /// - public string[] Configs { get; set; } - /// - /// Cluster's collections. - /// - public string[] Collections { get; set; } - } - #endregion + /// An array of [rankers] that available for the service instance (http://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#rankerinfopayload). + /// + public RankerInfoPayload[] rankers { get; set; } + } - #region Rankers - /// - /// Array of Rankers. - /// - [fsObject] - public class ListRankersPayload - { - /// - /// An array of [rankers] that available for the service instance (http://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#rankerinfopayload). - /// - public RankerInfoPayload[] rankers { get; set; } - } + /// + /// The Ranker object. + /// + [fsObject] + public class RankerInfoPayload + { + /// + /// Unique identifier for this ranker + /// + public string ranker_id { get; set; } + /// + /// Link to the ranker + /// + public string url { get; set; } + /// + /// User-supplied name for the ranker + /// + public string name { get; set; } + /// + /// Date and time in Coordinated Universal Time that the ranker was created + /// + public string created { get; set; } + } + /// + /// The Ranker status object. + /// + [fsObject] + public class RankerStatusPayload + { + /// + /// Unique identifier for this ranker. + /// + public string ranker_id { get; set; } /// - /// The Ranker object. - /// - [fsObject] - public class RankerInfoPayload - { - /// - /// Unique identifier for this ranker - /// - public string ranker_id { get; set; } - /// - /// Link to the ranker - /// - public string url { get; set; } - /// - /// User-supplied name for the ranker - /// - public string name { get; set; } - /// - /// Date and time in Coordinated Universal Time that the ranker was created - /// - public string created { get; set; } - } + /// Link to the ranker. + /// + public string url { get; set; } + /// + /// User-supplied name for the ranker. + /// + public string name { get; set; } + /// + /// Date and time in Coordinated Universal Time that the ranker was created. + /// + public string created { get; set; } + /// + /// The state of the ranker: Non_Existent, Training, Failed, Available, or Unavailable. + /// + public string status { get; set; } + /// + /// Additional detail about the status. + /// + public string status_description { get; set; } + } + /// + /// Additionial Ranker training metadata. + /// + [fsObject] + public class RankerTrainingMetadataPayload + { /// - /// The Ranker status object. - /// - [fsObject] - public class RankerStatusPayload - { - /// - /// Unique identifier for this ranker. - /// - public string ranker_id { get; set; } - /// - /// Link to the ranker. - /// - public string url { get; set; } - /// - /// User-supplied name for the ranker. - /// - public string name { get; set; } - /// - /// Date and time in Coordinated Universal Time that the ranker was created. - /// - public string created { get; set; } - /// - /// The state of the ranker: Non_Existent, Training, Failed, Available, or Unavailable. - /// - public string status { get; set; } - /// - /// Additional detail about the status. - /// - public string status_description { get; set; } - } + /// The Ranker name. + /// + public string name { get; set; } + } + /// + /// Ranker error response. + /// + [fsObject] + public class RankerErrorResponsePayload + { + /// + /// The error code. + /// + public int code { get; set; } + /// + /// The error string. + /// + public string error { get; set; } /// - /// Additionial Ranker training metadata. + /// The error description. /// - [fsObject] - public class RankerTrainingMetadataPayload - { - /// - /// The Ranker name. - /// - public string name { get; set; } - } + public string description { get; set; } + } + /// + /// Ranker answer output + /// + [fsObject] + public class RankerOutputPayload + { + /// + /// Unique identifier for this ranker. + /// + public string ranker_id { get; set; } + /// + /// Link to the ranker. + /// + public string url { get; set; } + /// + /// The answer with the highest score. + /// + public string top_answer { get; set; } /// - /// Ranker error response. - /// - [fsObject] - public class RankerErrorResponsePayload - { - /// - /// The error code. - /// - public int code { get; set; } - /// - /// The error string. - /// - public string error { get; set; } - /// - /// The error description. - /// - public string description { get; set; } - } + /// An array of of up to 10 answers that are sorted in descending order of score. + /// + public RankedAnswer[] answers { get; set; } + } + /// + /// The ranked answer object. + /// + [fsObject] + public class RankedAnswer + { + /// + /// Pointer to the answer in the collection. + /// + public string answer_id { get; set; } /// - /// Ranker answer output - /// - [fsObject] - public class RankerOutputPayload - { - /// - /// Unique identifier for this ranker. - /// - public string ranker_id { get; set; } - /// - /// Link to the ranker. - /// - public string url { get; set; } - /// - /// The answer with the highest score. - /// - public string top_answer { get; set; } - /// - /// An array of of up to 10 answers that are sorted in descending order of score. - /// - public RankedAnswer[] answers { get; set; } - } - - /// - /// The ranked answer object. - /// - [fsObject] - public class RankedAnswer - { - /// - /// Pointer to the answer in the collection. - /// - public string answer_id { get; set; } - /// - /// The rank of an answer among the candidate answers. Higher values represent higher relevance. The maximum score is the total number of candidate answers in the answer_data. You can use the score to sort the answers within the response. - /// - public int score { get; set; } - /// - /// A decimal percentage from 0 - 1 that represents the preference that Watson has for this answer. Higher values represent higher confidences. - /// - public double confidence { get; set; } - } - #endregion + /// The rank of an answer among the candidate answers. Higher values represent higher relevance. The maximum score is the total number of candidate answers in the answer_data. You can use the score to sort the answers within the response. + /// + public int score { get; set; } + /// + /// A decimal percentage from 0 - 1 that represents the preference that Watson has for this answer. Higher values represent higher confidences. + /// + public double confidence { get; set; } + } + #endregion } diff --git a/Scripts/Services/RetrieveAndRank/RetrieveAndRank.cs b/Scripts/Services/RetrieveAndRank/RetrieveAndRank.cs index 2e2dc20ef..e5db3cf75 100755 --- a/Scripts/Services/RetrieveAndRank/RetrieveAndRank.cs +++ b/Scripts/Services/RetrieveAndRank/RetrieveAndRank.cs @@ -28,1651 +28,1651 @@ namespace IBM.Watson.DeveloperCloud.Services.RetrieveAndRank.v1 { - /// - /// This class wraps the Retrieve and Rank service. - /// Retrieve and Rank Service - /// - public class RetrieveAndRank : IWatsonService + /// + /// This class wraps the Retrieve and Rank service. + /// Retrieve and Rank Service + /// + public class RetrieveAndRank : IWatsonService + { + #region Private Data + private const string SERVICE_ID = "RetrieveAndRankV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + private const float REQUEST_TIMEOUT = 10.0f * 60.0f; + + // List clusters or create cluster. + private const string SERVICE_CLUSTERS = "/v1/solr_clusters"; + // Delete cluster or get cluster info. + private const string SERVICE_CLUSTER = "/v1/solr_clusters/{0}"; + // List Solr cluster configurations. + private const string SERVICE_CLUSTER_CONFIGS = "/v1/solr_clusters/{0}/config"; + // Upload, Get or Delete Solr configuration. + private const string SERVICE_CLUSTER_CONFIG = "/v1/solr_clusters/{0}/config/{1}"; + // Forward requests to Solr (Create, Delete, List). + private const string SERVICE_CLUSTER_COLLECTIONS = "/v1/solr_clusters/{0}/solr/admin/collections"; + // Index documents. + private const string SERVICE_CLUSTER_COLLECTION_UPDATE = "/v1/solr_clusters/{0}/solr/{1}/update"; + // Search Solr standard query parser. + private const string SERVICE_CLUSTER_COLLECTION_SELECT = "/v1/solr_clusters/{0}/solr/{1}/select"; + // Search Solr ranked query parser. + private const string SERVICE_CLUSTER_COLLECTION_FCSELECT = "/v1/solr_clusters/{0}/solr/{1}/fcselect"; + + // List rankers or create ranker. + private const string SERVICE_RANKERS = "/v1/rankers"; + // Get ranker information or delete ranker. + private const string SERVICE_RANKER = "/v1/rankers/{0}"; + // Rank. + private const string SERVICE_RANK = "/v1/rankers/{0}/rank"; + #endregion + + #region Public Types + /// + /// The delegate for loading a file, used by TrainClassifier(). + /// + /// The filename to load. + /// Should return a byte array of the file contents or null of failure. + public delegate byte[] LoadFileDelegate(string filename); + /// + /// Set this property to overload the internal file loading of this class. + /// + public LoadFileDelegate LoadFile { get; set; } + /// + /// The delegate for saving a file, used by DownloadDialog(). + /// + /// The filename to save. + /// The data to save into the file. + public delegate void SaveFileDelegate(string filename, byte[] data); + + /// + /// Set this property to overload the internal file saving for this class. + /// + public SaveFileDelegate SaveFile { get; set; } + #endregion + + #region GetClusters + /// + /// OnGetClusters delegate. + /// + /// + /// + public delegate void OnGetClusters(SolrClusterListResponse resp, string data); + + /// + /// Retrieves the list of Solr clusters for the service instance. + /// + /// + /// + /// + public bool GetClusters(OnGetClusters callback, string customData = default(string)) { - #region Private Data - private const string SERVICE_ID = "RetrieveAndRankV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - private const float REQUEST_TIMEOUT = 10.0f * 60.0f; - - // List clusters or create cluster. - private const string SERVICE_CLUSTERS = "/v1/solr_clusters"; - // Delete cluster or get cluster info. - private const string SERVICE_CLUSTER = "/v1/solr_clusters/{0}"; - // List Solr cluster configurations. - private const string SERVICE_CLUSTER_CONFIGS = "/v1/solr_clusters/{0}/config"; - // Upload, Get or Delete Solr configuration. - private const string SERVICE_CLUSTER_CONFIG = "/v1/solr_clusters/{0}/config/{1}"; - // Forward requests to Solr (Create, Delete, List). - private const string SERVICE_CLUSTER_COLLECTIONS = "/v1/solr_clusters/{0}/solr/admin/collections"; - // Index documents. - private const string SERVICE_CLUSTER_COLLECTION_UPDATE = "/v1/solr_clusters/{0}/solr/{1}/update"; - // Search Solr standard query parser. - private const string SERVICE_CLUSTER_COLLECTION_SELECT = "/v1/solr_clusters/{0}/solr/{1}/select"; - // Search Solr ranked query parser. - private const string SERVICE_CLUSTER_COLLECTION_FCSELECT = "/v1/solr_clusters/{0}/solr/{1}/fcselect"; - - // List rankers or create ranker. - private const string SERVICE_RANKERS = "/v1/rankers"; - // Get ranker information or delete ranker. - private const string SERVICE_RANKER = "/v1/rankers/{0}"; - // Rank. - private const string SERVICE_RANK = "/v1/rankers/{0}/rank"; - #endregion - - #region Public Types - /// - /// The delegate for loading a file, used by TrainClassifier(). - /// - /// The filename to load. - /// Should return a byte array of the file contents or null of failure. - public delegate byte[] LoadFileDelegate(string filename); - /// - /// Set this property to overload the internal file loading of this class. - /// - public LoadFileDelegate LoadFile { get; set; } - /// - /// The delegate for saving a file, used by DownloadDialog(). - /// - /// The filename to save. - /// The data to save into the file. - public delegate void SaveFileDelegate(string filename, byte[] data); - - /// - /// Set this property to overload the internal file saving for this class. - /// - public SaveFileDelegate SaveFile { get; set; } - #endregion - - #region GetClusters - /// - /// OnGetClusters delegate. - /// - /// - /// - public delegate void OnGetClusters(SolrClusterListResponse resp, string data); - - /// - /// Retrieves the list of Solr clusters for the service instance. - /// - /// - /// - /// - public bool GetClusters(OnGetClusters callback, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); + if (callback == null) + throw new ArgumentNullException("callback"); - GetClustersRequest req = new GetClustersRequest(); - req.Callback = callback; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; + GetClustersRequest req = new GetClustersRequest(); + req.Callback = callback; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLUSTERS); - if (connector == null) - return false; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLUSTERS); + if (connector == null) + return false; - req.OnResponse = OnGetClustersResponse; - return connector.Send(req); - } + req.OnResponse = OnGetClustersResponse; + return connector.Send(req); + } - /// - /// The GetCluster request. - /// - public class GetClustersRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetClusters Callback { get; set; } - } + /// + /// The GetCluster request. + /// + public class GetClustersRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetClusters Callback { get; set; } + } - private void OnGetClustersResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnGetClustersResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + SolrClusterListResponse clustersData = new SolrClusterListResponse(); + if (resp.Success) + { + try { - SolrClusterListResponse clustersData = new SolrClusterListResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = clustersData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnGetClustersResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetClustersRequest)req).Callback != null) - ((GetClustersRequest)req).Callback(resp.Success ? clustersData : null, ((GetClustersRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = clustersData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region CreateCluster - /// - /// OnCreateCluster callback delegate. - /// - /// - /// - public delegate void OnCreateCluster(SolrClusterResponse resp, string data); - - /// - /// Provisions a Solr cluster asynchronously. When the operation is successful, the status of the cluster is set to NOT_AVAILABLE. The status must be READY before you can use the cluster. For information about cluster sizing see http://www.ibm.com/watson/developercloud/doc/retrieve-rank/solr_ops.shtml#sizing. - /// - /// - /// Name to identify the cluster. - /// Size of the cluster to create. Ranges from 1 to 7. Send an empty value to create a small free cluster for testing. You can create only one free cluster. - /// - /// - public bool CreateCluster(OnCreateCluster callback, string clusterName = default(string), string clusterSize = default(string), string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - - CreateClusterRequest req = new CreateClusterRequest(); - req.Callback = callback; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLUSTERS); - if (connector == null) - return false; - - string reqJson = ""; - if(!string.IsNullOrEmpty(clusterName) && !string.IsNullOrEmpty(clusterSize)) - reqJson = "{\n\t\"cluster_name\": \"" + clusterName + "\",\n\t\"cluster_size\": \"" + clusterSize + "\"\n}"; - - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(reqJson); - req.OnResponse = OnCreateClusterResponse; - return connector.Send(req); + Log.Error("RetriveAndRank", "OnGetClustersResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// The Create Cluster request. - /// - public class CreateClusterRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnCreateCluster Callback { get; set; } - } + if (((GetClustersRequest)req).Callback != null) + ((GetClustersRequest)req).Callback(resp.Success ? clustersData : null, ((GetClustersRequest)req).Data); + } + #endregion + + #region CreateCluster + /// + /// OnCreateCluster callback delegate. + /// + /// + /// + public delegate void OnCreateCluster(SolrClusterResponse resp, string data); + + /// + /// Provisions a Solr cluster asynchronously. When the operation is successful, the status of the cluster is set to NOT_AVAILABLE. The status must be READY before you can use the cluster. For information about cluster sizing see http://www.ibm.com/watson/developercloud/doc/retrieve-rank/solr_ops.shtml#sizing. + /// + /// + /// Name to identify the cluster. + /// Size of the cluster to create. Ranges from 1 to 7. Send an empty value to create a small free cluster for testing. You can create only one free cluster. + /// + /// + public bool CreateCluster(OnCreateCluster callback, string clusterName = default(string), string clusterSize = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + + CreateClusterRequest req = new CreateClusterRequest(); + req.Callback = callback; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_CLUSTERS); + if (connector == null) + return false; + + string reqJson = ""; + if (!string.IsNullOrEmpty(clusterName) && !string.IsNullOrEmpty(clusterSize)) + reqJson = "{\n\t\"cluster_name\": \"" + clusterName + "\",\n\t\"cluster_size\": \"" + clusterSize + "\"\n}"; + + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes(reqJson); + req.OnResponse = OnCreateClusterResponse; + return connector.Send(req); + } + + /// + /// The Create Cluster request. + /// + public class CreateClusterRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnCreateCluster Callback { get; set; } + } - /// - /// The Create Cluster response. - /// - /// - /// - private void OnCreateClusterResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// The Create Cluster response. + /// + /// + /// + private void OnCreateClusterResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + SolrClusterResponse clusterResponseData = new SolrClusterResponse(); + if (resp.Success) + { + try { - SolrClusterResponse clusterResponseData = new SolrClusterResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = clusterResponseData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnCreateClusterResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((CreateClusterRequest)req).Callback != null) - ((CreateClusterRequest)req).Callback(resp.Success ? clusterResponseData : null, ((CreateClusterRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = clusterResponseData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region DeleteClusters - /// - /// Delete cluster callback delegate. - /// - /// - /// - public delegate void OnDeleteCluster(bool success, string data); - - /// - /// Delete a Solr cluster. - /// - /// - /// - /// - /// - public bool DeleteCluster(OnDeleteCluster callback, string clusterID, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("ClusterID to be deleted is required!"); - if (clusterID == Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestClusterID")) - throw new WatsonException("You cannot delete the example cluster!"); - - DeleteClusterRequest req = new DeleteClusterRequest(); - req.Callback = callback; - req.Data = customData; - req.ClusterID = clusterID; - req.Delete = true; - req.Timeout = REQUEST_TIMEOUT; - req.OnResponse = OnDeleteClusterResponse; - string service = string.Format(SERVICE_CLUSTER, clusterID); - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); - if (connector == null) - return false; - - return connector.Send(req); + Log.Error("RetriveAndRank", "OnCreateClusterResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// The Delete Cluster request - /// - public class DeleteClusterRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier. - /// - public string ClusterID { get; set; } - /// - /// The callback. - /// - public OnDeleteCluster Callback { get; set; } - } + if (((CreateClusterRequest)req).Callback != null) + ((CreateClusterRequest)req).Callback(resp.Success ? clusterResponseData : null, ((CreateClusterRequest)req).Data); + } + #endregion + + #region DeleteClusters + /// + /// Delete cluster callback delegate. + /// + /// + /// + public delegate void OnDeleteCluster(bool success, string data); + + /// + /// Delete a Solr cluster. + /// + /// + /// + /// + /// + public bool DeleteCluster(OnDeleteCluster callback, string clusterID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("ClusterID to be deleted is required!"); + if (clusterID == Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestClusterID")) + throw new WatsonException("You cannot delete the example cluster!"); + + DeleteClusterRequest req = new DeleteClusterRequest(); + req.Callback = callback; + req.Data = customData; + req.ClusterID = clusterID; + req.Delete = true; + req.Timeout = REQUEST_TIMEOUT; + req.OnResponse = OnDeleteClusterResponse; + string service = string.Format(SERVICE_CLUSTER, clusterID); + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, service); + if (connector == null) + return false; + + return connector.Send(req); + } - /// - /// The Delete Cluster response. - /// - /// - /// - private void OnDeleteClusterResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - Log.Debug("RetrieveAndRank", "OnDeleteClusterResponse success: {0}", resp.Success); - if (((DeleteClusterRequest)req).Callback != null) - ((DeleteClusterRequest)req).Callback(resp.Success, ((DeleteClusterRequest)req).Data); - } - #endregion - - #region GetCluster - /// - /// Get cluster info callback delegate. - /// - /// - /// - public delegate void OnGetCluster(SolrClusterResponse resp, string data); - - /// - /// Returns status and other information about a cluster. - /// - /// - /// Unique identifier for this cluster. - /// - /// - public bool GetCluster(OnGetCluster callback, string clusterID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("ClusterID to get is required!"); - - GetClusterRequest req = new GetClusterRequest(); - req.Callback = callback; - req.Data = customData; - req.ClusterID = clusterID; - req.Timeout = REQUEST_TIMEOUT; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER, clusterID)); - if (connector == null) - return false; - - req.OnResponse = OnGetClusterResponse; - return connector.Send(req); - } + /// + /// The Delete Cluster request + /// + public class DeleteClusterRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier. + /// + public string ClusterID { get; set; } + /// + /// The callback. + /// + public OnDeleteCluster Callback { get; set; } + } - /// - /// The Get Cluster request - /// - public class GetClusterRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier. - /// - public string ClusterID { get; set; } - /// - /// The callback. - /// - public OnGetCluster Callback { get; set; } - } + /// + /// The Delete Cluster response. + /// + /// + /// + private void OnDeleteClusterResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Log.Debug("RetrieveAndRank", "OnDeleteClusterResponse success: {0}", resp.Success); + if (((DeleteClusterRequest)req).Callback != null) + ((DeleteClusterRequest)req).Callback(resp.Success, ((DeleteClusterRequest)req).Data); + } + #endregion + + #region GetCluster + /// + /// Get cluster info callback delegate. + /// + /// + /// + public delegate void OnGetCluster(SolrClusterResponse resp, string data); + + /// + /// Returns status and other information about a cluster. + /// + /// + /// Unique identifier for this cluster. + /// + /// + public bool GetCluster(OnGetCluster callback, string clusterID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("ClusterID to get is required!"); + + GetClusterRequest req = new GetClusterRequest(); + req.Callback = callback; + req.Data = customData; + req.ClusterID = clusterID; + req.Timeout = REQUEST_TIMEOUT; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER, clusterID)); + if (connector == null) + return false; + + req.OnResponse = OnGetClusterResponse; + return connector.Send(req); + } - /// - /// The Get Cluster response. - /// - /// - /// - private void OnGetClusterResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// The Get Cluster request + /// + public class GetClusterRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier. + /// + public string ClusterID { get; set; } + /// + /// The callback. + /// + public OnGetCluster Callback { get; set; } + } + + /// + /// The Get Cluster response. + /// + /// + /// + private void OnGetClusterResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + SolrClusterResponse clusterData = new SolrClusterResponse(); + if (resp.Success) + { + try { - SolrClusterResponse clusterData = new SolrClusterResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = clusterData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnGetClusterResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetClusterRequest)req).Callback != null) - ((GetClusterRequest)req).Callback(resp.Success ? clusterData : null, ((GetClusterRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = clusterData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region ListClusterConfigs - /// - /// Get Cluster Configs callback delegate. - /// - /// - /// - public delegate void OnGetClusterConfigs(SolrConfigList resp, string data); - - /// - /// Returns a configuration .zip file for a cluster. - /// - /// - /// - /// - /// - public bool GetClusterConfigs(OnGetClusterConfigs callback, string clusterID, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("ClusterID to get is required!"); - - GetClusterConfigsRequest req = new GetClusterConfigsRequest(); - req.Callback = callback; - req.ClusterID = clusterID; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - req.OnResponse = OnGetClusterConfigsResponse; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIGS, clusterID)); - if (connector == null) - return false; - - return connector.Send(req); + Log.Error("RetriveAndRank", "OnGetClusterResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// The GetClusterConfigs request. - /// - public class GetClusterConfigsRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier. - /// - public string ClusterID { get; set; } - /// - /// The callback. - /// - public OnGetClusterConfigs Callback { get; set; } - } + if (((GetClusterRequest)req).Callback != null) + ((GetClusterRequest)req).Callback(resp.Success ? clusterData : null, ((GetClusterRequest)req).Data); + } + #endregion + + #region ListClusterConfigs + /// + /// Get Cluster Configs callback delegate. + /// + /// + /// + public delegate void OnGetClusterConfigs(SolrConfigList resp, string data); + + /// + /// Returns a configuration .zip file for a cluster. + /// + /// + /// + /// + /// + public bool GetClusterConfigs(OnGetClusterConfigs callback, string clusterID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("ClusterID to get is required!"); + + GetClusterConfigsRequest req = new GetClusterConfigsRequest(); + req.Callback = callback; + req.ClusterID = clusterID; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + req.OnResponse = OnGetClusterConfigsResponse; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIGS, clusterID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + /// + /// The GetClusterConfigs request. + /// + public class GetClusterConfigsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier. + /// + public string ClusterID { get; set; } + /// + /// The callback. + /// + public OnGetClusterConfigs Callback { get; set; } + } - /// - /// The OnGetClusterConfigs response. - /// - /// - /// - private void OnGetClusterConfigsResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// The OnGetClusterConfigs response. + /// + /// + /// + private void OnGetClusterConfigsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + SolrConfigList configData = new SolrConfigList(); + if (resp.Success) + { + try { - SolrConfigList configData = new SolrConfigList(); - if (resp.Success) - { - try - { - fsData data = null; - string json = Encoding.UTF8.GetString(resp.Data); - fsResult r = fsJsonParser.Parse(json, out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = configData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnGetClusterConfigsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetClusterConfigsRequest)req).Callback != null) - ((GetClusterConfigsRequest)req).Callback(resp.Success ? configData : null, ((GetClusterConfigsRequest)req).Data); + fsData data = null; + string json = Encoding.UTF8.GetString(resp.Data); + fsResult r = fsJsonParser.Parse(json, out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = configData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region DeleteClusterConfig - /// - /// Delete cluster config callback delegate. - /// - /// - /// - public delegate void OnDeleteClusterConfig(bool success, string data); - - /// - /// Deletes the configuration for a cluster. Before you delete the configuration, delete any collections that point to it. - /// - /// - /// The name of the configuration to delete. - /// Cluster ID for the configuration. - /// - /// - public bool DeleteClusterConfig(OnDeleteClusterConfig callback, string clusterID, string configID, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("clusterID to is required!"); - if (string.IsNullOrEmpty(configID)) - throw new ArgumentNullException("configID to be deleted is required!"); - if (configID == Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestClusterConfigID")) - throw new WatsonException("You cannot delete the example cluster config!"); - - DeleteClusterConfigRequest req = new DeleteClusterConfigRequest(); - req.Callback = callback; - req.Data = customData; - req.ClusterID = clusterID; - req.ConfigID = configID; - req.Timeout = REQUEST_TIMEOUT; - req.Delete = true; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIG, clusterID, configID)); - if (connector == null) - return false; - - req.OnResponse = OnDeleteClusterConfigResponse; - return connector.Send(req); + Log.Error("RetriveAndRank", "OnGetClusterConfigsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// The Delete Cluster Config request - /// - public class DeleteClusterConfigRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier. - /// - public string ClusterID { get; set; } - /// - /// The config identifier. - /// - public string ConfigID { get; set; } - /// - /// The callback. - /// - public OnDeleteClusterConfig Callback { get; set; } - } + if (((GetClusterConfigsRequest)req).Callback != null) + ((GetClusterConfigsRequest)req).Callback(resp.Success ? configData : null, ((GetClusterConfigsRequest)req).Data); + } + #endregion + + #region DeleteClusterConfig + /// + /// Delete cluster config callback delegate. + /// + /// + /// + public delegate void OnDeleteClusterConfig(bool success, string data); + + /// + /// Deletes the configuration for a cluster. Before you delete the configuration, delete any collections that point to it. + /// + /// + /// The name of the configuration to delete. + /// Cluster ID for the configuration. + /// + /// + public bool DeleteClusterConfig(OnDeleteClusterConfig callback, string clusterID, string configID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("clusterID to is required!"); + if (string.IsNullOrEmpty(configID)) + throw new ArgumentNullException("configID to be deleted is required!"); + if (configID == Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestClusterConfigID")) + throw new WatsonException("You cannot delete the example cluster config!"); + + DeleteClusterConfigRequest req = new DeleteClusterConfigRequest(); + req.Callback = callback; + req.Data = customData; + req.ClusterID = clusterID; + req.ConfigID = configID; + req.Timeout = REQUEST_TIMEOUT; + req.Delete = true; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIG, clusterID, configID)); + if (connector == null) + return false; + + req.OnResponse = OnDeleteClusterConfigResponse; + return connector.Send(req); + } - private void OnDeleteClusterConfigResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteClusterConfigRequest)req).Callback != null) - ((DeleteClusterConfigRequest)req).Callback(resp.Success, ((DeleteClusterConfigRequest)req).Data); - } - #endregion - - #region GetClusterConfig - /// - /// The GetClusterConfig delegate. - /// - /// - /// - public delegate void OnGetClusterConfig(byte[] resp, string data); - - /// - /// Retrieves the configuration for a cluster by its name. - /// - /// - /// Cluster ID for the configuration. - /// The name of the configuration to retrieve. - /// - /// - public bool GetClusterConfig(OnGetClusterConfig callback, string clusterID, string configName, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("A clusterID is required for GetClusterConfig!"); - if (string.IsNullOrEmpty(configName)) - throw new ArgumentNullException("A configName is required for GetClusterConfig!"); - - GetClusterConfigRequest req = new GetClusterConfigRequest(); - req.Data = customData; - req.Callback = callback; - req.ClusterID = clusterID; - req.ConfigName = configName; - req.OnResponse = GetClusterConfigResponse; - req.Timeout = REQUEST_TIMEOUT; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIG, clusterID, configName)); - if (connector == null) - return false; - - return connector.Send(req); - } + /// + /// The Delete Cluster Config request + /// + public class DeleteClusterConfigRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier. + /// + public string ClusterID { get; set; } + /// + /// The config identifier. + /// + public string ConfigID { get; set; } + /// + /// The callback. + /// + public OnDeleteClusterConfig Callback { get; set; } + } - private class GetClusterConfigRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier. - /// - public string ClusterID { get; set; } - /// - /// The confguration name. - /// - public string ConfigName { get; set; } - /// - /// The callback. - /// - public OnGetClusterConfig Callback { get; set; } - } + private void OnDeleteClusterConfigResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteClusterConfigRequest)req).Callback != null) + ((DeleteClusterConfigRequest)req).Callback(resp.Success, ((DeleteClusterConfigRequest)req).Data); + } + #endregion + + #region GetClusterConfig + /// + /// The GetClusterConfig delegate. + /// + /// + /// + public delegate void OnGetClusterConfig(byte[] resp, string data); + + /// + /// Retrieves the configuration for a cluster by its name. + /// + /// + /// Cluster ID for the configuration. + /// The name of the configuration to retrieve. + /// + /// + public bool GetClusterConfig(OnGetClusterConfig callback, string clusterID, string configName, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("A clusterID is required for GetClusterConfig!"); + if (string.IsNullOrEmpty(configName)) + throw new ArgumentNullException("A configName is required for GetClusterConfig!"); + + GetClusterConfigRequest req = new GetClusterConfigRequest(); + req.Data = customData; + req.Callback = callback; + req.ClusterID = clusterID; + req.ConfigName = configName; + req.OnResponse = GetClusterConfigResponse; + req.Timeout = REQUEST_TIMEOUT; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIG, clusterID, configName)); + if (connector == null) + return false; + + return connector.Send(req); + } - private void GetClusterConfigResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - byte[] respData = null; + private class GetClusterConfigRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier. + /// + public string ClusterID { get; set; } + /// + /// The confguration name. + /// + public string ConfigName { get; set; } + /// + /// The callback. + /// + public OnGetClusterConfig Callback { get; set; } + } - if(resp.Success) - { - respData = resp.Data; - } + private void GetClusterConfigResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + byte[] respData = null; - if (((GetClusterConfigRequest)req).Callback != null) - ((GetClusterConfigRequest)req).Callback(respData, ((GetClusterConfigRequest)req).Data); - } + if (resp.Success) + { + respData = resp.Data; + } + + if (((GetClusterConfigRequest)req).Callback != null) + ((GetClusterConfigRequest)req).Callback(respData, ((GetClusterConfigRequest)req).Data); + } - /// - /// OnSaveClusterConfig callback delegate. - /// - /// - /// - public delegate void OnSaveClusterConfig(bool success, string data); - - /// - /// Saves the config zip to the file system. - /// - /// - /// Byte array of the config data. - /// Where to save the zip file in the file system. - /// - public void SaveConfig(OnSaveClusterConfig callback, byte[] configData, string configFileName, string customData) + /// + /// OnSaveClusterConfig callback delegate. + /// + /// + /// + public delegate void OnSaveClusterConfig(bool success, string data); + + /// + /// Saves the config zip to the file system. + /// + /// + /// Byte array of the config data. + /// Where to save the zip file in the file system. + /// + public void SaveConfig(OnSaveClusterConfig callback, byte[] configData, string configFileName, string customData) + { + bool success = true; + if (configData != null) + { + try { - bool success = true; - if(configData != null) - { - try - { - if (SaveFile != null) - SaveFile(configFileName, configData); - else - { + if (SaveFile != null) + SaveFile(configFileName, configData); + else + { #if !UNITY_WEBPLAYER - File.WriteAllBytes(configFileName, configData); + File.WriteAllBytes(configFileName, configData); #endif - } - } - catch (Exception e) - { - success = false; - Log.Error("RetrieveAndRank", "Caught exception: {0}", e.ToString()); - } - } - - if (callback != null) - callback(success, customData); + } } - #endregion - - #region UploadClusterConfig - /// - /// UploadClusterConfig callback delegate. - /// - /// - /// - public delegate void OnUploadClusterConfig(UploadResponse resp, string data); - - /// - /// Uploads a zip file containing the configuration files for your Solr collection. The zip file must include schema.xml, solrconfig.xml, and other files you need for your configuration. Configuration files on the zip file's path are not uploaded. The request fails if a configuration with the same name exists. To update an existing config, use the Solr configuration API (https://cwiki.apache.org/confluence/display/solr/Config+API). - /// - /// - /// Cluster ID for the configuration. - /// The name of the configuration to create. - /// The path to the compressed configuration files. - /// - /// - public bool UploadClusterConfig(OnUploadClusterConfig callback, string clusterID, string configName, string configPath, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("A clusterID is required for UploadClusterConfig!"); - if (string.IsNullOrEmpty(configName)) - throw new ArgumentNullException("A configName is required for UploadClusterConfig!"); - if (string.IsNullOrEmpty(configPath)) - throw new ArgumentNullException("A configPath is required for UploadClusterConfig!"); - - UploadClusterConfigRequest req = new UploadClusterConfigRequest(); - req.Callback = callback; - req.Data = customData; - req.ClusterID = clusterID; - req.ConfigName = configName; - req.OnResponse = UploadClusterConfigResponse; - req.Timeout = REQUEST_TIMEOUT; - - byte[] configData = null; - if (LoadFile != null) - { - configData = LoadFile(configPath); - } - else - { + success = false; + Log.Error("RetrieveAndRank", "Caught exception: {0}", e.ToString()); + } + } + + if (callback != null) + callback(success, customData); + } + #endregion + + #region UploadClusterConfig + /// + /// UploadClusterConfig callback delegate. + /// + /// + /// + public delegate void OnUploadClusterConfig(UploadResponse resp, string data); + + /// + /// Uploads a zip file containing the configuration files for your Solr collection. The zip file must include schema.xml, solrconfig.xml, and other files you need for your configuration. Configuration files on the zip file's path are not uploaded. The request fails if a configuration with the same name exists. To update an existing config, use the Solr configuration API (https://cwiki.apache.org/confluence/display/solr/Config+API). + /// + /// + /// Cluster ID for the configuration. + /// The name of the configuration to create. + /// The path to the compressed configuration files. + /// + /// + public bool UploadClusterConfig(OnUploadClusterConfig callback, string clusterID, string configName, string configPath, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("A clusterID is required for UploadClusterConfig!"); + if (string.IsNullOrEmpty(configName)) + throw new ArgumentNullException("A configName is required for UploadClusterConfig!"); + if (string.IsNullOrEmpty(configPath)) + throw new ArgumentNullException("A configPath is required for UploadClusterConfig!"); + + UploadClusterConfigRequest req = new UploadClusterConfigRequest(); + req.Callback = callback; + req.Data = customData; + req.ClusterID = clusterID; + req.ConfigName = configName; + req.OnResponse = UploadClusterConfigResponse; + req.Timeout = REQUEST_TIMEOUT; + + byte[] configData = null; + if (LoadFile != null) + { + configData = LoadFile(configPath); + } + else + { #if !UNITY_WEBPLAYER - configData = File.ReadAllBytes(configPath); + configData = File.ReadAllBytes(configPath); #endif - } + } - if (configData == null) - Log.Error("RetrieveAndRank", "Failed to upload {0}!", configPath); + if (configData == null) + Log.Error("RetrieveAndRank", "Failed to upload {0}!", configPath); - req.Headers["Content-Type"] = "application/zip"; - req.Send = configData; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIG, clusterID, configName)); - if (connector == null) - return false; + req.Headers["Content-Type"] = "application/zip"; + req.Send = configData; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_CONFIG, clusterID, configName)); + if (connector == null) + return false; - return connector.Send(req); - } + return connector.Send(req); + } - private class UploadClusterConfigRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier. - /// - public string ClusterID { get; set; } - /// - /// The configuration name. - /// - public string ConfigName { get; set; } - /// - /// The callback. - /// - public OnUploadClusterConfig Callback { get; set; } - } + private class UploadClusterConfigRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier. + /// + public string ClusterID { get; set; } + /// + /// The configuration name. + /// + public string ConfigName { get; set; } + /// + /// The callback. + /// + public OnUploadClusterConfig Callback { get; set; } + } - private void UploadClusterConfigResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void UploadClusterConfigResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + UploadResponse uploadResponse = new UploadResponse(); + if (resp.Success) + { + try { - UploadResponse uploadResponse = new UploadResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = uploadResponse; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "UploadClusterConfigResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((UploadClusterConfigRequest)req).Callback != null) - ((UploadClusterConfigRequest)req).Callback(resp.Success ? uploadResponse : null, ((UploadClusterConfigRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = uploadResponse; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region ForwardCollectionRequest - /// - /// The OnGetCollections delegate. - /// - /// - /// - public delegate void OnCollections(CollectionsResponse resp, string data); - - /// - /// An example of a method that forwards to the Solr Collections API (https://cwiki.apache.org/confluence/display/solr/Collections+API). This Retrieve and Rank resource improves error handling and resiliency of the Solr Collections API. - /// - /// - /// Cluster ID for the collection. - /// Operation to carry out. Either "CREATE", "LIST", or "DELETE" - /// The collectionName required for "CREATE" or "DELETE". - /// The cluster configuration name to use for "CREATE". - /// - /// - public bool ForwardCollectionRequest(OnCollections callback, string clusterID, string action, string collectionName = default(string), string configName = default(string), string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(action)) - throw new ArgumentNullException("An Action is required for ForwardCollectionRequest (CREATE, DELETE or LIST)"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("A clusterID is required for ForwardCollectionRequest!"); - - CollectionRequest req = new CollectionRequest(); - req.Callback = callback; - req.ClusterID = clusterID; - req.Data = customData; - req.Action = action; - req.CollectionName = collectionName; - req.ConfigName = configName; - req.Parameters["action"] = action; - req.Parameters["wt"] = "json"; - req.Timeout = REQUEST_TIMEOUT; - - switch (action) - { - case CollectionsAction.LIST: - break; - case CollectionsAction.CREATE: - if (string.IsNullOrEmpty(collectionName)) - throw new ArgumentNullException("A collectionName is required for ForwardCollectionRequest (CREATE)!"); - if (string.IsNullOrEmpty(configName)) - throw new ArgumentNullException("A configName is required for ForwardCollectionRequest (CREATE)!"); - req.Parameters["name"] = collectionName; - req.Parameters["collection.configName"] = configName; - break; - case CollectionsAction.DELETE: - if (string.IsNullOrEmpty(collectionName)) - throw new ArgumentNullException("A collectionName is required for ForwardCollectionRequest (DELETE)!"); - req.Parameters["name"] = collectionName; - break; - default: - throw new WatsonException(string.Format("No case exists for action {0}!", action)); - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTIONS, clusterID)); - if (connector == null) - return false; - - req.OnResponse = OnForwardCollectionRequestResponse; - return connector.Send(req); + Log.Error("RetriveAndRank", "UploadClusterConfigResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// The ForwardCollectionRequest request - /// - public class CollectionRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnCollections Callback { get; set; } - /// - /// Cluster ID required for all actions. - /// - public string ClusterID { get; set; } - /// - /// Action for the call. Either "CREATE", "LIST", or "DELETE" - /// - public string Action { get; set; } - /// - /// The collectionName required for "CREATE" or "DELETE". - /// - public string CollectionName { get; set; } - /// - /// The cluster configuration name to use for "CREATE". - /// - public string ConfigName { get; set; } - } + if (((UploadClusterConfigRequest)req).Callback != null) + ((UploadClusterConfigRequest)req).Callback(resp.Success ? uploadResponse : null, ((UploadClusterConfigRequest)req).Data); + } + #endregion + + #region ForwardCollectionRequest + /// + /// The OnGetCollections delegate. + /// + /// + /// + public delegate void OnCollections(CollectionsResponse resp, string data); + + /// + /// An example of a method that forwards to the Solr Collections API (https://cwiki.apache.org/confluence/display/solr/Collections+API). This Retrieve and Rank resource improves error handling and resiliency of the Solr Collections API. + /// + /// + /// Cluster ID for the collection. + /// Operation to carry out. Either "CREATE", "LIST", or "DELETE" + /// The collectionName required for "CREATE" or "DELETE". + /// The cluster configuration name to use for "CREATE". + /// + /// + public bool ForwardCollectionRequest(OnCollections callback, string clusterID, string action, string collectionName = default(string), string configName = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(action)) + throw new ArgumentNullException("An Action is required for ForwardCollectionRequest (CREATE, DELETE or LIST)"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("A clusterID is required for ForwardCollectionRequest!"); + + CollectionRequest req = new CollectionRequest(); + req.Callback = callback; + req.ClusterID = clusterID; + req.Data = customData; + req.Action = action; + req.CollectionName = collectionName; + req.ConfigName = configName; + req.Parameters["action"] = action; + req.Parameters["wt"] = "json"; + req.Timeout = REQUEST_TIMEOUT; + + switch (action) + { + case CollectionsAction.LIST: + break; + case CollectionsAction.CREATE: + if (string.IsNullOrEmpty(collectionName)) + throw new ArgumentNullException("A collectionName is required for ForwardCollectionRequest (CREATE)!"); + if (string.IsNullOrEmpty(configName)) + throw new ArgumentNullException("A configName is required for ForwardCollectionRequest (CREATE)!"); + req.Parameters["name"] = collectionName; + req.Parameters["collection.configName"] = configName; + break; + case CollectionsAction.DELETE: + if (string.IsNullOrEmpty(collectionName)) + throw new ArgumentNullException("A collectionName is required for ForwardCollectionRequest (DELETE)!"); + req.Parameters["name"] = collectionName; + break; + default: + throw new WatsonException(string.Format("No case exists for action {0}!", action)); + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTIONS, clusterID)); + if (connector == null) + return false; + + req.OnResponse = OnForwardCollectionRequestResponse; + return connector.Send(req); + } - private void OnForwardCollectionRequestResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// The ForwardCollectionRequest request + /// + public class CollectionRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnCollections Callback { get; set; } + /// + /// Cluster ID required for all actions. + /// + public string ClusterID { get; set; } + /// + /// Action for the call. Either "CREATE", "LIST", or "DELETE" + /// + public string Action { get; set; } + /// + /// The collectionName required for "CREATE" or "DELETE". + /// + public string CollectionName { get; set; } + /// + /// The cluster configuration name to use for "CREATE". + /// + public string ConfigName { get; set; } + } + + private void OnForwardCollectionRequestResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + CollectionsResponse collectionsData = new CollectionsResponse(); + if (resp.Success) + { + try { - CollectionsResponse collectionsData = new CollectionsResponse(); - if(resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = collectionsData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnForwardCollectionRequestResponse exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((CollectionRequest)req).Callback != null) - ((CollectionRequest)req).Callback(resp.Success ? collectionsData : null, ((CollectionRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = collectionsData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region IndexDocuments - /// - /// OnIndexDocuments callback delegate. - /// - /// - /// - public delegate void OnIndexDocuments(IndexResponse resp, string data); - - /// - /// Adds content to a Solr index so you can search it. An example of a method that forwards to Solr. For more information about indexing, see Indexing and Basic Data Operations in the Apache Solr Reference (https://cwiki.apache.org/confluence/display/solr/Indexing+and+Basic+Data+Operations). You must commit your documents to the index to search for them. For more information about when to commit, see UpdateHandlers in SolrConfig in the Solr Reference (https://cwiki.apache.org/confluence/display/solr/UpdateHandlers+in+SolrConfig). - /// - /// - /// Path to the file that defines the content. - /// Cluster ID. - /// Collection. - /// - /// - public bool IndexDocuments(OnIndexDocuments callback, string indexDataPath, string clusterID, string collectionName, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(indexDataPath)) - throw new ArgumentNullException("A index data json path is required to index documents!"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("A clusterID is required to index documents!"); - if (string.IsNullOrEmpty(collectionName)) - throw new ArgumentNullException("A collectionName is required to index documents!"); - - IndexDocumentsRequest req = new IndexDocumentsRequest(); - req.Callback = callback; - req.IndexDataPath = indexDataPath; - req.ClusterID = clusterID; - req.CollectionName = collectionName; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - - byte[] indexData; - if (LoadFile != null) - { - indexData = File.ReadAllBytes(indexDataPath); - } - else - { + Log.Error("RetriveAndRank", "OnForwardCollectionRequestResponse exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((CollectionRequest)req).Callback != null) + ((CollectionRequest)req).Callback(resp.Success ? collectionsData : null, ((CollectionRequest)req).Data); + } + #endregion + + #region IndexDocuments + /// + /// OnIndexDocuments callback delegate. + /// + /// + /// + public delegate void OnIndexDocuments(IndexResponse resp, string data); + + /// + /// Adds content to a Solr index so you can search it. An example of a method that forwards to Solr. For more information about indexing, see Indexing and Basic Data Operations in the Apache Solr Reference (https://cwiki.apache.org/confluence/display/solr/Indexing+and+Basic+Data+Operations). You must commit your documents to the index to search for them. For more information about when to commit, see UpdateHandlers in SolrConfig in the Solr Reference (https://cwiki.apache.org/confluence/display/solr/UpdateHandlers+in+SolrConfig). + /// + /// + /// Path to the file that defines the content. + /// Cluster ID. + /// Collection. + /// + /// + public bool IndexDocuments(OnIndexDocuments callback, string indexDataPath, string clusterID, string collectionName, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(indexDataPath)) + throw new ArgumentNullException("A index data json path is required to index documents!"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("A clusterID is required to index documents!"); + if (string.IsNullOrEmpty(collectionName)) + throw new ArgumentNullException("A collectionName is required to index documents!"); + + IndexDocumentsRequest req = new IndexDocumentsRequest(); + req.Callback = callback; + req.IndexDataPath = indexDataPath; + req.ClusterID = clusterID; + req.CollectionName = collectionName; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + + byte[] indexData; + if (LoadFile != null) + { + indexData = File.ReadAllBytes(indexDataPath); + } + else + { #if !UNITY_WEBPLAYER - indexData = File.ReadAllBytes(indexDataPath); + indexData = File.ReadAllBytes(indexDataPath); #endif - } + } - if (indexData == null) - Log.Error("RetrieveAndRank", "Failed to upload {0}!", indexDataPath); + if (indexData == null) + Log.Error("RetrieveAndRank", "Failed to upload {0}!", indexDataPath); - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTION_UPDATE, clusterID, collectionName)); - if (connector == null) - return false; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTION_UPDATE, clusterID, collectionName)); + if (connector == null) + return false; - req.Headers["Content-Type"] = "multipart/form-data"; - req.Forms = new Dictionary(); - req.Forms["body"] = new RESTConnector.Form(indexData, "indexData.json", "application/json"); - req.OnResponse = OnIndexDocumentsResponse; - return connector.Send(req); - } + req.Headers["Content-Type"] = "multipart/form-data"; + req.Forms = new Dictionary(); + req.Forms["body"] = new RESTConnector.Form(indexData, "indexData.json", "application/json"); + req.OnResponse = OnIndexDocumentsResponse; + return connector.Send(req); + } - /// - /// The Create Ranker request. - /// - public class IndexDocumentsRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The index data path. - /// - public string IndexDataPath { get; set; } - /// - /// The cluster identifier to use. - /// - public string ClusterID { get; set; } - /// - /// The collection name to use. - /// - public string CollectionName { get; set; } - /// - /// The callback. - /// - public OnIndexDocuments Callback { get; set; } - } + /// + /// The Create Ranker request. + /// + public class IndexDocumentsRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The index data path. + /// + public string IndexDataPath { get; set; } + /// + /// The cluster identifier to use. + /// + public string ClusterID { get; set; } + /// + /// The collection name to use. + /// + public string CollectionName { get; set; } + /// + /// The callback. + /// + public OnIndexDocuments Callback { get; set; } + } - private void OnIndexDocumentsResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void OnIndexDocumentsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + IndexResponse indexResponseData = new IndexResponse(); + if (resp.Success) + { + try { - IndexResponse indexResponseData = new IndexResponse(); - if (resp.Success) - { - try - { - fsData data = null; - string json = Encoding.UTF8.GetString(resp.Data); - Log.Debug("RetriveAndRank", "json: {0}", json); - fsResult r = fsJsonParser.Parse(json, out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - object obj = indexResponseData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnIndexDocumentsResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((IndexDocumentsRequest)req).Callback != null) - ((IndexDocumentsRequest)req).Callback(resp.Success ? indexResponseData : null, ((IndexDocumentsRequest)req).Data); + fsData data = null; + string json = Encoding.UTF8.GetString(resp.Data); + Log.Debug("RetriveAndRank", "json: {0}", json); + fsResult r = fsJsonParser.Parse(json, out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + object obj = indexResponseData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Search - /// - /// The OnSearch callback delegate. - /// - /// - /// - public delegate void OnSearch(SearchResponse resp, string data); - - /// - /// Return reranked results for your query. The request is similar to the Search Solr standard query parser method, but includes the ranker_id and, in the default configuration, fcselect replaces the select request handler. (https://cwiki.apache.org/confluence/display/solr/The+Standard+Query+Parser). - /// - /// - /// Cluster ID. - /// The name of the collection to use. - /// The query. Uses Solr standard query syntax. - /// The fields to return. - /// Use ranked search instead of standard search. - /// The trained ranker to query. - /// - /// - public bool Search(OnSearch callback, string clusterID, string collectionName, string query, string[] fl, bool isRankedSearch = false, string rankerID = default(string), string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(clusterID)) - throw new ArgumentNullException("A clusterID is required to search!"); - if (string.IsNullOrEmpty(collectionName)) - throw new ArgumentNullException("A collectionName is required to search!"); - if (string.IsNullOrEmpty(query)) - throw new ArgumentNullException("A query is required to search!"); - if (fl == default(string[])) - throw new ArgumentNullException("An array of filters are required to search!"); - - SearchRequest req = new SearchRequest(); - req.Callback = callback; - req.ClusterID = clusterID; - req.CollectionName = collectionName; - req.Query = query; - req.Fl = fl; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - - req.Parameters["wt"] = "json"; - req.Parameters["q"] = query; - req.Parameters["fl"] = string.Join(",", fl); - - req.OnResponse = OnSearchResponse; - - RESTConnector connector; - if (!isRankedSearch) - connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTION_SELECT, clusterID, collectionName)); - else - { - connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTION_FCSELECT, clusterID, collectionName)); - req.Parameters["ranker_id"] = rankerID; - } - - if (connector == null) - return false; - - return connector.Send(req); + Log.Error("RetriveAndRank", "OnIndexDocumentsResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - /// The search request. - /// - public class SearchRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The cluster identifier to use. - /// - public string ClusterID { get; set; } - /// - /// The collectionName to use. - /// - public string CollectionName { get; set; } - /// - /// The query. - /// - public string Query { get; set; } - /// - /// The query fields to use. - /// - public string[] Fl { get; set; } - /// - /// The callback. - /// - public OnSearch Callback { get; set; } - } + if (((IndexDocumentsRequest)req).Callback != null) + ((IndexDocumentsRequest)req).Callback(resp.Success ? indexResponseData : null, ((IndexDocumentsRequest)req).Data); + } + #endregion + + #region Search + /// + /// The OnSearch callback delegate. + /// + /// + /// + public delegate void OnSearch(SearchResponse resp, string data); + + /// + /// Return reranked results for your query. The request is similar to the Search Solr standard query parser method, but includes the ranker_id and, in the default configuration, fcselect replaces the select request handler. (https://cwiki.apache.org/confluence/display/solr/The+Standard+Query+Parser). + /// + /// + /// Cluster ID. + /// The name of the collection to use. + /// The query. Uses Solr standard query syntax. + /// The fields to return. + /// Use ranked search instead of standard search. + /// The trained ranker to query. + /// + /// + public bool Search(OnSearch callback, string clusterID, string collectionName, string query, string[] fl, bool isRankedSearch = false, string rankerID = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(clusterID)) + throw new ArgumentNullException("A clusterID is required to search!"); + if (string.IsNullOrEmpty(collectionName)) + throw new ArgumentNullException("A collectionName is required to search!"); + if (string.IsNullOrEmpty(query)) + throw new ArgumentNullException("A query is required to search!"); + if (fl == default(string[])) + throw new ArgumentNullException("An array of filters are required to search!"); + + SearchRequest req = new SearchRequest(); + req.Callback = callback; + req.ClusterID = clusterID; + req.CollectionName = collectionName; + req.Query = query; + req.Fl = fl; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + + req.Parameters["wt"] = "json"; + req.Parameters["q"] = query; + req.Parameters["fl"] = string.Join(",", fl); + + req.OnResponse = OnSearchResponse; + + RESTConnector connector; + if (!isRankedSearch) + connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTION_SELECT, clusterID, collectionName)); + else + { + connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_CLUSTER_COLLECTION_FCSELECT, clusterID, collectionName)); + req.Parameters["ranker_id"] = rankerID; + } + + if (connector == null) + return false; + + return connector.Send(req); + } - private void OnSearchResponse(RESTConnector.Request req, RESTConnector.Response resp) + /// + /// The search request. + /// + public class SearchRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The cluster identifier to use. + /// + public string ClusterID { get; set; } + /// + /// The collectionName to use. + /// + public string CollectionName { get; set; } + /// + /// The query. + /// + public string Query { get; set; } + /// + /// The query fields to use. + /// + public string[] Fl { get; set; } + /// + /// The callback. + /// + public OnSearch Callback { get; set; } + } + + private void OnSearchResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + SearchResponse searchData = new SearchResponse(); + if (resp.Success) + { + try { - SearchResponse searchData = new SearchResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = searchData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnSearchResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((SearchRequest)req).Callback != null) - ((SearchRequest)req).Callback(resp.Success ? searchData : null, ((SearchRequest)req).Data); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = searchData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetRankers - /// - /// OnGetRankers delegate. - /// - /// - /// - public delegate void OnGetRankers(ListRankersPayload resp, string data); - - /// - /// Retrieves the list of rankers for the service instance. - /// - /// - /// - /// - public bool GetRankers(OnGetRankers callback, string customData = default(string)) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); + Log.Error("RetriveAndRank", "OnSearchResponse Exception: {0}", e.ToString()); + resp.Success = false; + } + } - GetRankersRequest req = new GetRankersRequest(); - req.Callback = callback; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; + if (((SearchRequest)req).Callback != null) + ((SearchRequest)req).Callback(resp.Success ? searchData : null, ((SearchRequest)req).Data); + } + #endregion + + #region GetRankers + /// + /// OnGetRankers delegate. + /// + /// + /// + public delegate void OnGetRankers(ListRankersPayload resp, string data); + + /// + /// Retrieves the list of rankers for the service instance. + /// + /// + /// + /// + public bool GetRankers(OnGetRankers callback, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_RANKERS); - if (connector == null) - return false; + GetRankersRequest req = new GetRankersRequest(); + req.Callback = callback; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; - req.OnResponse = OnGetRankersResponse; - return connector.Send(req); - } + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_RANKERS); + if (connector == null) + return false; - /// - /// The GetRanker request. - /// - public class GetRankersRequest : RESTConnector.Request + req.OnResponse = OnGetRankersResponse; + return connector.Send(req); + } + + /// + /// The GetRanker request. + /// + public class GetRankersRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The callback. + /// + public OnGetRankers Callback { get; set; } + } + + private void OnGetRankersResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + ListRankersPayload rankersData = new ListRankersPayload(); + if (resp.Success) + { + try { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The callback. - /// - public OnGetRankers Callback { get; set; } + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = rankersData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - private void OnGetRankersResponse(RESTConnector.Request req, RESTConnector.Response resp) + catch (Exception e) { - ListRankersPayload rankersData = new ListRankersPayload(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = rankersData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnGetRankersResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetRankersRequest)req).Callback != null) - ((GetRankersRequest)req).Callback(resp.Success ? rankersData : null, ((GetRankersRequest)req).Data); + Log.Error("RetriveAndRank", "OnGetRankersResponse Exception: {0}", e.ToString()); + resp.Success = false; } - #endregion - - #region CreateRanker - /// - /// OnCreateCluster callback delegate. - /// - /// - /// - public delegate void OnCreateRanker(RankerStatusPayload resp, string data); - - /// - /// Sends data to create and train a ranker and returns information about the new ranker. When the operation is successful, the status of the ranker is set to Training. The status must be Available before you can use the ranker. - /// - /// - /// Training data in CSV format. The first header must be question_id and the last header must be the relevance label. The other headers are alphanumeric feature names. For details, see Using your own data (http://www.ibm.com/watson/developercloud/doc/retrieve-rank/data_format.shtml). - /// Metadata in JSON format. The metadata identifies an optional name to identify the ranker. - /// - /// - public bool CreateRanker(OnCreateRanker callback, string trainingDataPath, string name = default(string), string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(name)) - throw new ArgumentNullException("A ranker name is required to create a ranker!"); - if (string.IsNullOrEmpty(trainingDataPath)) - throw new ArgumentNullException("Training data is required to create a ranker!"); - - CreateRankerRequest req = new CreateRankerRequest(); - req.Callback = callback; - req.Name = name; - req.TrainingDataPath = trainingDataPath; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - - byte[] trainingData; - if (LoadFile != null) - { - trainingData = File.ReadAllBytes(trainingDataPath); - } - else - { + } + + if (((GetRankersRequest)req).Callback != null) + ((GetRankersRequest)req).Callback(resp.Success ? rankersData : null, ((GetRankersRequest)req).Data); + } + #endregion + + #region CreateRanker + /// + /// OnCreateCluster callback delegate. + /// + /// + /// + public delegate void OnCreateRanker(RankerStatusPayload resp, string data); + + /// + /// Sends data to create and train a ranker and returns information about the new ranker. When the operation is successful, the status of the ranker is set to Training. The status must be Available before you can use the ranker. + /// + /// + /// Training data in CSV format. The first header must be question_id and the last header must be the relevance label. The other headers are alphanumeric feature names. For details, see Using your own data (http://www.ibm.com/watson/developercloud/doc/retrieve-rank/data_format.shtml). + /// Metadata in JSON format. The metadata identifies an optional name to identify the ranker. + /// + /// + public bool CreateRanker(OnCreateRanker callback, string trainingDataPath, string name = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(name)) + throw new ArgumentNullException("A ranker name is required to create a ranker!"); + if (string.IsNullOrEmpty(trainingDataPath)) + throw new ArgumentNullException("Training data is required to create a ranker!"); + + CreateRankerRequest req = new CreateRankerRequest(); + req.Callback = callback; + req.Name = name; + req.TrainingDataPath = trainingDataPath; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + + byte[] trainingData; + if (LoadFile != null) + { + trainingData = File.ReadAllBytes(trainingDataPath); + } + else + { #if !UNITY_WEBPLAYER - trainingData = File.ReadAllBytes(trainingDataPath); + trainingData = File.ReadAllBytes(trainingDataPath); #endif - } - - if (trainingData == null) - Log.Error("RetrieveAndRank", "Failed to upload {0}!", trainingDataPath); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_RANKERS); - if (connector == null) - return false; - - req.Forms = new Dictionary(); - req.Forms["training_data"] = new RESTConnector.Form(trainingData, "training_data.csv", "text/csv"); - if (!string.IsNullOrEmpty(name)) - { - string reqJson = "{\n\t\"name\": \"" + name + "\"\n}"; - req.Forms["training_metadata"] = new RESTConnector.Form(reqJson); - } - req.OnResponse = OnCreateRankerResponse; - return connector.Send(req); - } - - /// - /// The Create Ranker request. - /// - public class CreateRankerRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The ranker name. - /// - public string Name { get; set; } - /// - /// The ranker training data path. - /// - public string TrainingDataPath { get; set; } - /// - /// The callback. - /// - public OnCreateRanker Callback { get; set; } - } - - private void OnCreateRankerResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - RankerStatusPayload rankerResponseData = new RankerStatusPayload(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = rankerResponseData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnCreateRankerResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((CreateRankerRequest)req).Callback != null) - ((CreateRankerRequest)req).Callback(resp.Success ? rankerResponseData : null, ((CreateRankerRequest)req).Data); - } - #endregion - - #region Rank - /// - /// OnRank callback delegate. - /// - /// - /// - public delegate void OnRank(RankerOutputPayload resp, string data); - - /// - /// Returns the top answer and a list of ranked answers with their ranked scores and confidence values. Use the Get information about a ranker method to retrieve the status (http://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#get_status). Use this method to return answers when you train the ranker with custom features. However, in most cases, you can use the Search and rank method (http://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#query_ranker). - /// - /// - /// ID of the ranker to use. - /// The path to the CSV file that contains the search results that you want to rank. The first column header of the CSV must be labeled answer_id. The remaining column headers must match the names of the features in the training data that was used when this ranker was created. - /// - /// - public bool Rank(OnRank callback, string rankerID, string searchResultPath = default(string), string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(rankerID)) - throw new ArgumentNullException("A rankerID is required rank!"); - if (string.IsNullOrEmpty(searchResultPath)) - throw new ArgumentNullException("Search results are required to rank!"); - - RankRequest req = new RankRequest(); - req.Callback = callback; - req.RankerID = rankerID; - req.SearchResultsPath = searchResultPath; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - - byte[] searchResultData; - if (LoadFile != null) - { - searchResultData = File.ReadAllBytes(searchResultPath); - } - else - { + } + + if (trainingData == null) + Log.Error("RetrieveAndRank", "Failed to upload {0}!", trainingDataPath); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, SERVICE_RANKERS); + if (connector == null) + return false; + + req.Forms = new Dictionary(); + req.Forms["training_data"] = new RESTConnector.Form(trainingData, "training_data.csv", "text/csv"); + if (!string.IsNullOrEmpty(name)) + { + string reqJson = "{\n\t\"name\": \"" + name + "\"\n}"; + req.Forms["training_metadata"] = new RESTConnector.Form(reqJson); + } + req.OnResponse = OnCreateRankerResponse; + return connector.Send(req); + } + + /// + /// The Create Ranker request. + /// + public class CreateRankerRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The ranker name. + /// + public string Name { get; set; } + /// + /// The ranker training data path. + /// + public string TrainingDataPath { get; set; } + /// + /// The callback. + /// + public OnCreateRanker Callback { get; set; } + } + + private void OnCreateRankerResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + RankerStatusPayload rankerResponseData = new RankerStatusPayload(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = rankerResponseData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("RetriveAndRank", "OnCreateRankerResponse Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((CreateRankerRequest)req).Callback != null) + ((CreateRankerRequest)req).Callback(resp.Success ? rankerResponseData : null, ((CreateRankerRequest)req).Data); + } + #endregion + + #region Rank + /// + /// OnRank callback delegate. + /// + /// + /// + public delegate void OnRank(RankerOutputPayload resp, string data); + + /// + /// Returns the top answer and a list of ranked answers with their ranked scores and confidence values. Use the Get information about a ranker method to retrieve the status (http://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#get_status). Use this method to return answers when you train the ranker with custom features. However, in most cases, you can use the Search and rank method (http://www.ibm.com/watson/developercloud/retrieve-and-rank/api/v1/#query_ranker). + /// + /// + /// ID of the ranker to use. + /// The path to the CSV file that contains the search results that you want to rank. The first column header of the CSV must be labeled answer_id. The remaining column headers must match the names of the features in the training data that was used when this ranker was created. + /// + /// + public bool Rank(OnRank callback, string rankerID, string searchResultPath = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(rankerID)) + throw new ArgumentNullException("A rankerID is required rank!"); + if (string.IsNullOrEmpty(searchResultPath)) + throw new ArgumentNullException("Search results are required to rank!"); + + RankRequest req = new RankRequest(); + req.Callback = callback; + req.RankerID = rankerID; + req.SearchResultsPath = searchResultPath; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + + byte[] searchResultData; + if (LoadFile != null) + { + searchResultData = File.ReadAllBytes(searchResultPath); + } + else + { #if !UNITY_WEBPLAYER - searchResultData = File.ReadAllBytes(searchResultPath); + searchResultData = File.ReadAllBytes(searchResultPath); #endif - } - - if (searchResultData == null) - Log.Error("RetrieveAndRank", "Failed to upload {0}!", searchResultData); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_RANK, rankerID)); - if (connector == null) - return false; - - //req.Headers["Content-Type"] = "multipart/form-data"; - //req.Headers["Accept"] = "*/*"; - - req.Forms = new Dictionary(); - req.Forms["answer_data"] = new RESTConnector.Form(searchResultData, "searck_data.csv", "text/csv"); - - req.OnResponse = OnRankResponse; - return connector.Send(req); - } - - /// - /// The Rank request. - /// - public class RankRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The ranker identifier. - /// - public string RankerID { get; set; } - /// - /// The search results path. - /// - public string SearchResultsPath { get; set; } - /// - /// The callback. - /// - public OnRank Callback { get; set; } - } - - /// - /// Rank response. - /// - /// - /// - private void OnRankResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - RankerOutputPayload rankData = new RankerOutputPayload(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = rankData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnRankResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((RankRequest)req).Callback != null) - ((RankRequest)req).Callback(resp.Success ? rankData : null, ((RankRequest)req).Data); - } - #endregion - - #region DeleteRanker - /// - /// Delete Ranker callback delegate. - /// - /// - /// - public delegate void OnDeleteRanker(bool success, string data); - - /// - /// Deletes a ranker. - /// - /// - /// ID of the ranker to delete. - /// - /// - public bool DeleteRanker(OnDeleteRanker callback, string rankerID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(rankerID)) - throw new ArgumentNullException("RankerID to be deleted is required!"); - if (rankerID == Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestRankerID")) - throw new WatsonException("You cannot delete the example ranker!"); - - DeleteRankerRequest req = new DeleteRankerRequest(); - req.Callback = callback; - req.Data = customData; - req.RankerID = rankerID; - req.Timeout = REQUEST_TIMEOUT; - req.Delete = true; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_RANKER, rankerID)); - if (connector == null) - return false; - - req.OnResponse = OnDeleteRankerResponse; - return connector.Send(req); - } - - /// - /// The Delete Ranker request - /// - public class DeleteRankerRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The ranker identifier. - /// - public string RankerID { get; set; } - /// - /// The callback. - /// - public OnDeleteRanker Callback { get; set; } - } - - /// - /// The Delete Cluster response. - /// - /// - /// - private void OnDeleteRankerResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteRankerRequest)req).Callback != null) - ((DeleteRankerRequest)req).Callback(resp.Success, ((DeleteRankerRequest)req).Data); - } - #endregion - - #region GetRankerInfo - /// - /// Get ranker info callback delegate. - /// - /// - /// - public delegate void OnGetRanker(RankerStatusPayload resp, string data); - - /// - /// Returns status and other information about a ranker. - /// - /// - /// ID of the ranker to query. - /// - /// - public bool GetRanker(OnGetRanker callback, string rankerID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(rankerID)) - throw new ArgumentNullException("RankerID to get is required!"); - - GetRankerRequest req = new GetRankerRequest(); - req.Callback = callback; - req.Data = customData; - req.RankerID = rankerID; - req.Timeout = REQUEST_TIMEOUT; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_RANKER, rankerID)); - if (connector == null) - return false; - - req.OnResponse = OnGetRankerResponse; - return connector.Send(req); - } - - /// - /// The Get Ranker request - /// - public class GetRankerRequest : RESTConnector.Request - { - /// - /// Custom data. - /// - public string Data { get; set; } - /// - /// The ranker identifier. - /// - public string RankerID { get; set; } - /// - /// The callback. - /// - public OnGetRanker Callback { get; set; } - } - - /// - /// The Get Ranker response. - /// - /// - /// - private void OnGetRankerResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - RankerStatusPayload rankerData = new RankerStatusPayload(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = rankerData; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("RetriveAndRank", "OnGetRankerResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetRankerRequest)req).Callback != null) - ((GetRankerRequest)req).Callback(resp.Success ? rankerData : null, ((GetRankerRequest)req).Data); - } - #endregion - - #region IWatsonService Interface - /// - public string GetServiceID() + } + + if (searchResultData == null) + Log.Error("RetrieveAndRank", "Failed to upload {0}!", searchResultData); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_RANK, rankerID)); + if (connector == null) + return false; + + //req.Headers["Content-Type"] = "multipart/form-data"; + //req.Headers["Accept"] = "*/*"; + + req.Forms = new Dictionary(); + req.Forms["answer_data"] = new RESTConnector.Form(searchResultData, "searck_data.csv", "text/csv"); + + req.OnResponse = OnRankResponse; + return connector.Send(req); + } + + /// + /// The Rank request. + /// + public class RankRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The ranker identifier. + /// + public string RankerID { get; set; } + /// + /// The search results path. + /// + public string SearchResultsPath { get; set; } + /// + /// The callback. + /// + public OnRank Callback { get; set; } + } + + /// + /// Rank response. + /// + /// + /// + private void OnRankResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + RankerOutputPayload rankData = new RankerOutputPayload(); + if (resp.Success) + { + try { - return SERVICE_ID; + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = rankData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - /// - public void GetServiceStatus(ServiceStatus callback) + catch (Exception e) { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); + Log.Error("RetriveAndRank", "OnRankResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } + + if (((RankRequest)req).Callback != null) + ((RankRequest)req).Callback(resp.Success ? rankData : null, ((RankRequest)req).Data); + } + #endregion + + #region DeleteRanker + /// + /// Delete Ranker callback delegate. + /// + /// + /// + public delegate void OnDeleteRanker(bool success, string data); + + /// + /// Deletes a ranker. + /// + /// + /// ID of the ranker to delete. + /// + /// + public bool DeleteRanker(OnDeleteRanker callback, string rankerID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(rankerID)) + throw new ArgumentNullException("RankerID to be deleted is required!"); + if (rankerID == Config.Instance.GetVariableValue("RetrieveAndRank_IntegrationTestRankerID")) + throw new WatsonException("You cannot delete the example ranker!"); + + DeleteRankerRequest req = new DeleteRankerRequest(); + req.Callback = callback; + req.Data = customData; + req.RankerID = rankerID; + req.Timeout = REQUEST_TIMEOUT; + req.Delete = true; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_RANKER, rankerID)); + if (connector == null) + return false; + + req.OnResponse = OnDeleteRankerResponse; + return connector.Send(req); + } + + /// + /// The Delete Ranker request + /// + public class DeleteRankerRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The ranker identifier. + /// + public string RankerID { get; set; } + /// + /// The callback. + /// + public OnDeleteRanker Callback { get; set; } + } + + /// + /// The Delete Cluster response. + /// + /// + /// + private void OnDeleteRankerResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteRankerRequest)req).Callback != null) + ((DeleteRankerRequest)req).Callback(resp.Success, ((DeleteRankerRequest)req).Data); + } + #endregion + + #region GetRankerInfo + /// + /// Get ranker info callback delegate. + /// + /// + /// + public delegate void OnGetRanker(RankerStatusPayload resp, string data); + + /// + /// Returns status and other information about a ranker. + /// + /// + /// ID of the ranker to query. + /// + /// + public bool GetRanker(OnGetRanker callback, string rankerID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(rankerID)) + throw new ArgumentNullException("RankerID to get is required!"); + + GetRankerRequest req = new GetRankerRequest(); + req.Callback = callback; + req.Data = customData; + req.RankerID = rankerID; + req.Timeout = REQUEST_TIMEOUT; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(SERVICE_RANKER, rankerID)); + if (connector == null) + return false; + + req.OnResponse = OnGetRankerResponse; + return connector.Send(req); + } - private class CheckServiceStatus + /// + /// The Get Ranker request + /// + public class GetRankerRequest : RESTConnector.Request + { + /// + /// Custom data. + /// + public string Data { get; set; } + /// + /// The ranker identifier. + /// + public string RankerID { get; set; } + /// + /// The callback. + /// + public OnGetRanker Callback { get; set; } + } + + /// + /// The Get Ranker response. + /// + /// + /// + private void OnGetRankerResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + RankerStatusPayload rankerData = new RankerStatusPayload(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = rankerData; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) { - private RetrieveAndRank m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(RetrieveAndRank service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - if (!m_Service.GetClusters(OnGetClusters)) - m_Callback(SERVICE_ID, false); - } - - void OnGetClusters(SolrClusterListResponse clustersData, string data) - { - if (m_Callback != null) - m_Callback(SERVICE_ID, clustersData != null); - } - }; - #endregion + Log.Error("RetriveAndRank", "OnGetRankerResponse Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetRankerRequest)req).Callback != null) + ((GetRankerRequest)req).Callback(resp.Success ? rankerData : null, ((GetRankerRequest)req).Data); + } + #endregion + + #region IWatsonService Interface + /// + public string GetServiceID() + { + return SERVICE_ID; } + + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + private class CheckServiceStatus + { + private RetrieveAndRank m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(RetrieveAndRank service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.GetClusters(OnGetClusters)) + m_Callback(SERVICE_ID, false); + } + + void OnGetClusters(SolrClusterListResponse clustersData, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, clustersData != null); + } + }; + #endregion + } } diff --git a/Scripts/Services/SpeechToText/DataModels.cs b/Scripts/Services/SpeechToText/DataModels.cs index a99bed71c..9ed36fa3e 100755 --- a/Scripts/Services/SpeechToText/DataModels.cs +++ b/Scripts/Services/SpeechToText/DataModels.cs @@ -21,660 +21,660 @@ namespace IBM.Watson.DeveloperCloud.Services.SpeechToText.v1 { - #region Models - /// - /// This data class holds multiple speech models. - /// - [fsObject] - public class ModelSet - { - /// - /// Information about each available model. - /// - public Model[] models { get; set; } - } - /// - /// This data class holds the data for a given speech model. - /// - [fsObject] - public class Model - { - /// - /// The name of the speech model. - /// - public string name { get; set; } - /// - /// The language ID for this model. (e.g. en) - /// - public string language { get; set; } - /// - /// The optimal sample rate for this model. - /// - public long rate { get; set; } - /// - /// The URL for this model. - /// - public string url { get; set; } - /// - /// Information about each available model. - /// - public string sessions { get; set; } - /// - /// Describes the additional service features supported with the model. - /// - public SupportedFeatures supported_features { get; set; } - /// - /// A description for this model. - /// - public string description { get; set; } - }; - - /// - /// This data class holds all supported features. - /// - [fsObject] - public class SupportedFeatures - { - /// - /// Describes the additional service features supported with the model. - /// - public bool custom_language_model { get; set; } - } - #endregion - - #region Sessions and Sessionless - /// - /// This data class holds the Session data. - /// - [fsObject] - public class Session - { - /// - /// Describes the additional service features supported with the model. - /// - public string session_id { get; set; } - /// - /// Describes the additional service features supported with the model. - /// - public string new_session_uri { get; set; } - /// - /// URI for REST recognition requests. - /// - public string recognize { get; set; } - /// - /// URI for REST results observers. - /// - public string observe_result { get; set; } - /// - /// URI for WebSocket recognition requests. Needed only for working with the WebSocket interface. - /// - public string recognizeWS { get; set; } - } - - /// - /// This data object contains data for the speechRecognitionEvent. - /// - [fsObject] - public class SpeechRecognitionEvent - { - /// - /// The results array consists of zero or more final results followed by zero or one interim result. The final results are guaranteed not to change; the interim result may be replaced by zero or more final results (followed by zero or one interim result). The service periodically sends updates to the result list, with the result_index set to the lowest index in the array that has changed. - /// - public SpeechRecognitionResult[] results { get; set; } - /// - /// An index that indicates the change point in the results array. - /// - public int result_index { get; set; } - /// - /// An array of warning messages about invalid query parameters or JSON fields included with the request. Each warning includes a descriptive message and a list of invalid argument strings. For example, a message such as "Unknown arguments:" or "Unknown url query arguments:" followed by a list of the form "invalid_arg_1, invalid_arg_2." The request succeeds despite the warnings. - /// - public string[] warnings { get; set; } - - /// - public SpeechRecognitionEvent(SpeechRecognitionResult[] _results) - { - results = _results; - } - - /// - /// Check if our result list has atleast one valid result. - /// - /// Returns true if a result is found. - public bool HasResult() - { - return results != null && results.Length > 0 - && results[0].alternatives != null && results[0].alternatives.Length > 0; - } - - /// - /// Returns true if we have a final result. - /// - /// - public bool HasFinalResult() - { - return HasResult() && results[0].final; - } - } - - /// - /// The speech recognition result. - /// - [fsObject] - public class SpeechRecognitionResult - { - /// - /// If true, the result for this utterance is not updated further. - /// - public bool final { get; set; } - /// - /// Array of alternative transcripts. - /// - public SpeechRecognitionAlternative[] alternatives { get; set; } - /// - /// Dictionary (or associative array) whose keys are the strings specified for keywords if both that parameter and keywords_threshold are specified. A keyword for which no matches are found is omitted from the array. - /// - public KeywordResults keywords_result { get; set; } - /// - /// Array of word alternative hypotheses found for words of the input audio if word_alternatives_threshold is not null. - /// - public WordAlternativeResults word_alternatives { get; set; } - } - - /// - /// The alternatives. - /// - [fsObject] - public class SpeechRecognitionAlternative - { - /// - /// Transcription of the audio. - /// - public string transcript { get; set; } - - /// - /// Confidence score of the transcript in the range of 0 to 1. Available only for the best alternative and only in results marked as final. - /// - public double confidence { get; set; } - /// - /// Time alignments for each word from transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds. Example: [["hello",0.0,1.2],["world",1.2,2.5]]. Available only for the best alternative. - /// - public string[] timestamps { get; set; } - /// - /// 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 to 1. Example: [["hello",0.95],["world",0.866]]. Available only for the best alternative and only in results marked as final. - /// - public string[] word_confidence { get; set; } - /// - /// A optional array of timestamps objects. - /// - public TimeStamp[] Timestamps { get; set; } - /// - /// A option array of word confidence values. - /// - public WordConfidence[] WordConfidence { get; set; } - } - - /// - /// The Keword Result - /// - [fsObject] - public class KeywordResults - { - /// - /// List of each keyword entered via the keywords parameter and, for each keyword, an array of KeywordResult objects that provides information about its occurrences in the input audio. The keys of the list are the actual keyword strings. A keyword for which no matches are spotted in the input is omitted from the array. - /// - public KeywordResult[] keyword { get; set; } - } - - /// - /// This class holds a Word Alternative Result. - /// - [fsObject] - public class WordAlternativeResults - { - /// - /// Specified keyword normalized to the spoken phrase that matched in the audio input. - /// - public double start_time { get; set; } - /// - /// Specified keyword normalized to the spoken phrase that matched in the audio input. - /// - public double end_time { get; set; } - /// - /// Specified keyword normalized to the spoken phrase that matched in the audio input. - /// - public WordAlternativeResult[] alternatives { get; set; } - } - - /// - /// This class holds a Keyword Result. - /// - [fsObject] - public class KeywordResult - { - /// - /// Specified keyword normalized to the spoken phrase that matched in the audio input. - /// - public string normalized_text { get; set; } - /// - /// Start time in seconds of the keyword match. - /// - public double start_time { get; set; } - /// - /// End time in seconds of the keyword match. - /// - public double end_time { get; set; } - /// - /// Confidence score of the keyword match in the range of 0 to 1. - /// - public double confidence { get; set; } - } - - /// - /// This data class holds a Word Alternative Result. - /// - [fsObject] - public class WordAlternativeResult - { - /// - /// Confidence score of the word alternative hypothesis. - /// - public double confidence { get; set; } - /// - /// Word alternative hypothesis for a word from the input audio. - /// - public string word { get; set; } - } - - /// - /// This data class holds the sesion data. - /// - [fsObject] - public class RecognizeStatus - { - /// - /// Description of the state and possible actions for the current session - /// - public SessionStatus session { get; set; } - } - - /// - /// This data class holds the description of teh state and possbile actions for the current session. - /// - [fsObject] - public class SessionStatus - { - /// - /// State of the session. The state must be initialized to perform a new recognition request on the session. - /// - public string state { get; set; } - /// - /// URI for information about the model that is used with the session. - /// - public string model { get; set; } - /// - /// URI for REST recognition requests. - /// - public string recognize { get; set; } - /// - /// URI for REST results observers. - /// - public string observe_result { get; set; } - /// - /// URI for WebSocket recognition requests. Needed only for working with the WebSocket interface. - /// - public string recognizeWS { get; set; } - } - - /// - /// This data class holds the confidence value for a given recognized word. - /// - [fsObject] - public class WordConfidence - { - /// - /// The word as a string. - /// - public string Word { get; set; } - /// - /// The confidence value for this word. - /// - public double Confidence { get; set; } - }; - /// - /// This data class holds the start and stop times for a word. - /// - [fsObject] - public class TimeStamp - { - /// - /// The word. - /// - public string Word { get; set; } - /// - /// The start time. - /// - public double Start { get; set; } - /// - /// The stop time. - /// - public double End { get; set; } - }; - #endregion - - #region Asynchronous - /// - /// This data class contains information about the register callback status. - /// - public class RegisterStatus - { - /// - /// The current status of the job: created if the callback URL was successfully white-listed as a result of the call or already created if the URL was already white-listed. - /// - public string status { get; set; } - /// - /// The callback URL that is successfully registered - /// - public string url { get; set; } - } - - /// - /// This data class contains information about the Jobs - /// - public class JobsStatusList - { - /// - /// The current status of the job: created if the callback URL was successfully white-listed as a result of the call or already created if the URL was already white-listed. - /// - public JobStatus[] recognitions { get; set; } - } - - /// - /// This data class contains information about the job status. - /// - public class JobStatus - { - /// - /// The ID of the job. - /// - public string id { get; set; } - /// - /// The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - /// - public string created { get; set; } - /// - /// The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - /// - public string updated { get; set; } - /// - /// The current status of the job. waiting: The service is preparing the job for processing; the service always returns this status when the job is initially created or when it is waiting for capacity to process the job. processing: The service is actively processing the job. completed: The service has finished processing the job; if the job specified a callback URL and the event recognitions.completed_with_results, the service sent the results with the callback notification; otherwise, use the GET /v1/recognitions/{id} method to retrieve the results. failed: The job failed. - /// - public string status { get; set; } - /// - /// The user token associated with a job that was created with a callback URL and a user token. - /// - public string user_token { get; set; } - } - - /// - /// This data class contains information about a newly created recognition job. - /// - public class JobStatusNew - { - /// - /// The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - /// - public string created { get; set; } - /// - /// The ID of the job. - /// - public string id { get; set; } - /// - /// The URL to use to request information about the job with the GET /v1/recognitions/{id} method. - /// - public string url { get; set; } - /// - /// The current status of the job. waiting: The service is preparing the job for processing; the service always returns this status when the job is initially created or when it is waiting for capacity to process the job. processing: The service is actively processing the job. completed: The service has finished processing the job; if the job specified a callback URL and the event recognitions.completed_with_results, the service sent the results with the callback notification; otherwise, use the GET /v1/recognitions/{id} method to retrieve the results. failed: The job failed. - /// - public string status { get; set; } - } - #endregion - - #region Custom Models - /// - /// This data class contains information about the speech to text model customizations. - /// - public class Customizations - { - /// - /// Information about each available custom model. The array is empty if the user owns no custom models (if no language is specified) or owns no custom models for the specified language. - /// - public Customization[] customizations { get; set; } - } - - /// - /// This data class contains information about the Speech to Text model customizations. - /// - public class Customization - { - /// - /// The GUID of the custom language model. - /// - public string customization_id { get; set; } - /// - /// The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - /// - public string created { get; set; } - /// - /// The language of the custom language model. Currently, only en-US is supported. - /// - public string language { get; set; } - /// - /// The GUID of the service credentials for the owner of the custom language model. - /// - public string owner { get; set; } - /// - /// The name of the custom language model. - /// - public string name { get; set; } - /// - /// The description of the custom language model. - /// - public string description { get; set; } - /// - /// The name of the base language model for which the custom language model was created. = ['en-US_BroadbandModel', 'en-US_NarrowbandModel']. - /// - public string base_model_name { get; set; } - /// - /// The current status of the custom language model: pending indicates that the model was created but is waiting either for training data to be added or for the service to finish analyzing added data. ready indicates that the model contains data and is ready to be trained. training indicates that the model is currently being trained. For this beta release, the status field continues to be ready while the model is being trained; the field does not currently report a status of training. available indicates that the model is trained and ready to use. failed indicates that training of the model failed. = ['pending', 'ready', 'training', 'available', 'failed']. - /// - public string status { get; set; } - /// - /// A percentage that indicates the progress of the model's current training. A value of 100 means that the model is fully trained. For this beta release, the progress field does not reflect the current progress of the training; the field changes from 0 to 100 when training is complete. - /// - public int progress { get; set; } - /// - /// If the request included unknown query parameters, the following message: Unexpected query parameter(s) ['parameters'] detected, where parameters is a list that includes a quoted string for each unknown parameter. - /// - public string warnings { get; set; } - } - - /// - /// This data class contains information about the language model customization identifier. - /// - public class CustomizationID - { - /// - /// The GUID of the new custom language model. - /// - public string customization_id { get; set; } - } - - /// - /// A data object that contains data to create a new empty custom language mode3l. - /// - [fsObject] - public class CustomLanguage - { - /// - /// Name of the new custom language model. - /// - public string name { get; set; } - /// - /// The base model name - Currently only en-US_BroadbandModel is supported. - /// - public string base_model_name { get; set; } - /// - /// Description of the new custom voice model. - /// - public string description { get; set; } - } - - /// - /// The type of words from the custom model's words resource on which to train the model: all (the default) trains the model on all new words, regardless of whether they were extracted from corpora or were added or modified by the user. user trains the model only on new words that were added or modified by the user; the model is not trained on new words extracted from corpora. - /// - public class WordTypeToAdd - { - /// - /// All word types. - /// - public const string ALL = "all"; - /// - /// User word types. - /// - public const string USER = "user"; - } - #endregion - - #region Custom Corpora - /// - /// This data class contains information about multiple custom corpora. - /// - public class Corpora - { - /// - /// Information about corpora of the custom model. The array is empty if the custom model has no corpora. - /// - public Corpus[] corpora { get; set; } - } - - /// - /// This data class contains information about the custom corpus. - /// - public class Corpus - { - /// - /// The name of the corpus. - /// - public string name { get; set; } - /// - /// The total number of words in the corpus. The value is 0 while the corpus is being processed. - /// - public int total_words { get; set; } - /// - /// The number of OOV words in the corpus. The value is 0 while the corpus is being processed. - /// - public int out_of_vocabulary_words { get; set; } - /// - /// The status of the corpus: analyzed indicates that the service has successfully analyzed the corpus; the custom model can be trained with data from the corpus. being_processed indicates that the service is still analyzing the corpus; the service cannot accept requests to add new corpora or words, or to train the custom model. undetermined indicates that the service encountered an error while processing the corpus. = ['analyzed', 'being_processed', 'undetermined'] - /// - public string status { get; set; } - /// - /// If the status of the corpus is undetermined, the following message: Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'. - /// - public string error { get; set; } - } - #endregion - - #region Custom Words - /// - /// This data class contains information about multiple custom words. - /// - [fsObject] - public class WordsList - { - /// - /// Information about each word in the custom model's words resource. The array is empty if the custom model has no words. - /// - public WordData[] words { get; set; } - } - - /// - /// This data class contains information about the custom word data. - /// - [fsObject] - public class WordData - { - /// - /// A custom word from the custom model. The spelling of the word is used to train the model. - /// - public string word { get; set; } - /// - /// An array of pronunciations for the custom word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes pre-processing the word. - /// - public string[] sounds_like { get; set; } - /// - /// The spelling of the custom word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. - /// - public string display_as { get; set; } - /// - /// An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string user. - /// - public string[] source { get; set; } - /// - /// If the service discovered a problem with the custom word's definition that you need to correct, a message that describes the problem, for example: Numbers are not allowed in sounds-like. You must correct the error before you can train the model. - /// - public string error { get; set; } - } - - /// - /// The type of words to be listed from the custom language model's words resource: all (the default) shows all words. user shows only custom words that were added or modified by the user. corpora shows only OOV that were extracted from corpora. - /// - public class WordType - { - /// - /// All words. - /// - public const string ALL = "all"; - /// - /// User words. - /// - public const string USER = "user"; - /// - /// Corpora words. - /// - public const string CORPORA = "corpora"; - } - - /// - /// Words object for adding words to a customization. - /// - [fsObject] - public class Words - { - /// - /// The words to add to a customization. - /// - public Word[] words { get; set; } - } - - /// - /// A word to add to a customization. - /// - [fsObject] - public class Word - { - /// - /// The word. - /// - public string word { get; set; } - /// - /// What the word sounds like. - /// - public string[] sounds_like { get; set; } - /// - /// How the word is displayed. - /// - public string display_as { get; set; } - } - #endregion + #region Models + /// + /// This data class holds multiple speech models. + /// + [fsObject] + public class ModelSet + { + /// + /// Information about each available model. + /// + public Model[] models { get; set; } + } + /// + /// This data class holds the data for a given speech model. + /// + [fsObject] + public class Model + { + /// + /// The name of the speech model. + /// + public string name { get; set; } + /// + /// The language ID for this model. (e.g. en) + /// + public string language { get; set; } + /// + /// The optimal sample rate for this model. + /// + public long rate { get; set; } + /// + /// The URL for this model. + /// + public string url { get; set; } + /// + /// Information about each available model. + /// + public string sessions { get; set; } + /// + /// Describes the additional service features supported with the model. + /// + public SupportedFeatures supported_features { get; set; } + /// + /// A description for this model. + /// + public string description { get; set; } + }; + + /// + /// This data class holds all supported features. + /// + [fsObject] + public class SupportedFeatures + { + /// + /// Describes the additional service features supported with the model. + /// + public bool custom_language_model { get; set; } + } + #endregion + + #region Sessions and Sessionless + /// + /// This data class holds the Session data. + /// + [fsObject] + public class Session + { + /// + /// Describes the additional service features supported with the model. + /// + public string session_id { get; set; } + /// + /// Describes the additional service features supported with the model. + /// + public string new_session_uri { get; set; } + /// + /// URI for REST recognition requests. + /// + public string recognize { get; set; } + /// + /// URI for REST results observers. + /// + public string observe_result { get; set; } + /// + /// URI for WebSocket recognition requests. Needed only for working with the WebSocket interface. + /// + public string recognizeWS { get; set; } + } + + /// + /// This data object contains data for the speechRecognitionEvent. + /// + [fsObject] + public class SpeechRecognitionEvent + { + /// + /// The results array consists of zero or more final results followed by zero or one interim result. The final results are guaranteed not to change; the interim result may be replaced by zero or more final results (followed by zero or one interim result). The service periodically sends updates to the result list, with the result_index set to the lowest index in the array that has changed. + /// + public SpeechRecognitionResult[] results { get; set; } + /// + /// An index that indicates the change point in the results array. + /// + public int result_index { get; set; } + /// + /// An array of warning messages about invalid query parameters or JSON fields included with the request. Each warning includes a descriptive message and a list of invalid argument strings. For example, a message such as "Unknown arguments:" or "Unknown url query arguments:" followed by a list of the form "invalid_arg_1, invalid_arg_2." The request succeeds despite the warnings. + /// + public string[] warnings { get; set; } + + /// + public SpeechRecognitionEvent(SpeechRecognitionResult[] _results) + { + results = _results; + } + + /// + /// Check if our result list has atleast one valid result. + /// + /// Returns true if a result is found. + public bool HasResult() + { + return results != null && results.Length > 0 + && results[0].alternatives != null && results[0].alternatives.Length > 0; + } + + /// + /// Returns true if we have a final result. + /// + /// + public bool HasFinalResult() + { + return HasResult() && results[0].final; + } + } + + /// + /// The speech recognition result. + /// + [fsObject] + public class SpeechRecognitionResult + { + /// + /// If true, the result for this utterance is not updated further. + /// + public bool final { get; set; } + /// + /// Array of alternative transcripts. + /// + public SpeechRecognitionAlternative[] alternatives { get; set; } + /// + /// Dictionary (or associative array) whose keys are the strings specified for keywords if both that parameter and keywords_threshold are specified. A keyword for which no matches are found is omitted from the array. + /// + public KeywordResults keywords_result { get; set; } + /// + /// Array of word alternative hypotheses found for words of the input audio if word_alternatives_threshold is not null. + /// + public WordAlternativeResults word_alternatives { get; set; } + } + + /// + /// The alternatives. + /// + [fsObject] + public class SpeechRecognitionAlternative + { + /// + /// Transcription of the audio. + /// + public string transcript { get; set; } + + /// + /// Confidence score of the transcript in the range of 0 to 1. Available only for the best alternative and only in results marked as final. + /// + public double confidence { get; set; } + /// + /// Time alignments for each word from transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds. Example: [["hello",0.0,1.2],["world",1.2,2.5]]. Available only for the best alternative. + /// + public string[] timestamps { get; set; } + /// + /// 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 to 1. Example: [["hello",0.95],["world",0.866]]. Available only for the best alternative and only in results marked as final. + /// + public string[] word_confidence { get; set; } + /// + /// A optional array of timestamps objects. + /// + public TimeStamp[] Timestamps { get; set; } + /// + /// A option array of word confidence values. + /// + public WordConfidence[] WordConfidence { get; set; } + } + + /// + /// The Keword Result + /// + [fsObject] + public class KeywordResults + { + /// + /// List of each keyword entered via the keywords parameter and, for each keyword, an array of KeywordResult objects that provides information about its occurrences in the input audio. The keys of the list are the actual keyword strings. A keyword for which no matches are spotted in the input is omitted from the array. + /// + public KeywordResult[] keyword { get; set; } + } + + /// + /// This class holds a Word Alternative Result. + /// + [fsObject] + public class WordAlternativeResults + { + /// + /// Specified keyword normalized to the spoken phrase that matched in the audio input. + /// + public double start_time { get; set; } + /// + /// Specified keyword normalized to the spoken phrase that matched in the audio input. + /// + public double end_time { get; set; } + /// + /// Specified keyword normalized to the spoken phrase that matched in the audio input. + /// + public WordAlternativeResult[] alternatives { get; set; } + } + + /// + /// This class holds a Keyword Result. + /// + [fsObject] + public class KeywordResult + { + /// + /// Specified keyword normalized to the spoken phrase that matched in the audio input. + /// + public string normalized_text { get; set; } + /// + /// Start time in seconds of the keyword match. + /// + public double start_time { get; set; } + /// + /// End time in seconds of the keyword match. + /// + public double end_time { get; set; } + /// + /// Confidence score of the keyword match in the range of 0 to 1. + /// + public double confidence { get; set; } + } + + /// + /// This data class holds a Word Alternative Result. + /// + [fsObject] + public class WordAlternativeResult + { + /// + /// Confidence score of the word alternative hypothesis. + /// + public double confidence { get; set; } + /// + /// Word alternative hypothesis for a word from the input audio. + /// + public string word { get; set; } + } + + /// + /// This data class holds the sesion data. + /// + [fsObject] + public class RecognizeStatus + { + /// + /// Description of the state and possible actions for the current session + /// + public SessionStatus session { get; set; } + } + + /// + /// This data class holds the description of teh state and possbile actions for the current session. + /// + [fsObject] + public class SessionStatus + { + /// + /// State of the session. The state must be initialized to perform a new recognition request on the session. + /// + public string state { get; set; } + /// + /// URI for information about the model that is used with the session. + /// + public string model { get; set; } + /// + /// URI for REST recognition requests. + /// + public string recognize { get; set; } + /// + /// URI for REST results observers. + /// + public string observe_result { get; set; } + /// + /// URI for WebSocket recognition requests. Needed only for working with the WebSocket interface. + /// + public string recognizeWS { get; set; } + } + + /// + /// This data class holds the confidence value for a given recognized word. + /// + [fsObject] + public class WordConfidence + { + /// + /// The word as a string. + /// + public string Word { get; set; } + /// + /// The confidence value for this word. + /// + public double Confidence { get; set; } + }; + /// + /// This data class holds the start and stop times for a word. + /// + [fsObject] + public class TimeStamp + { + /// + /// The word. + /// + public string Word { get; set; } + /// + /// The start time. + /// + public double Start { get; set; } + /// + /// The stop time. + /// + public double End { get; set; } + }; + #endregion + + #region Asynchronous + /// + /// This data class contains information about the register callback status. + /// + public class RegisterStatus + { + /// + /// The current status of the job: created if the callback URL was successfully white-listed as a result of the call or already created if the URL was already white-listed. + /// + public string status { get; set; } + /// + /// The callback URL that is successfully registered + /// + public string url { get; set; } + } + + /// + /// This data class contains information about the Jobs + /// + public class JobsStatusList + { + /// + /// The current status of the job: created if the callback URL was successfully white-listed as a result of the call or already created if the URL was already white-listed. + /// + public JobStatus[] recognitions { get; set; } + } + + /// + /// This data class contains information about the job status. + /// + public class JobStatus + { + /// + /// The ID of the job. + /// + public string id { get; set; } + /// + /// The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). + /// + public string created { get; set; } + /// + /// The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). + /// + public string updated { get; set; } + /// + /// The current status of the job. waiting: The service is preparing the job for processing; the service always returns this status when the job is initially created or when it is waiting for capacity to process the job. processing: The service is actively processing the job. completed: The service has finished processing the job; if the job specified a callback URL and the event recognitions.completed_with_results, the service sent the results with the callback notification; otherwise, use the GET /v1/recognitions/{id} method to retrieve the results. failed: The job failed. + /// + public string status { get; set; } + /// + /// The user token associated with a job that was created with a callback URL and a user token. + /// + public string user_token { get; set; } + } + + /// + /// This data class contains information about a newly created recognition job. + /// + public class JobStatusNew + { + /// + /// The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). + /// + public string created { get; set; } + /// + /// The ID of the job. + /// + public string id { get; set; } + /// + /// The URL to use to request information about the job with the GET /v1/recognitions/{id} method. + /// + public string url { get; set; } + /// + /// The current status of the job. waiting: The service is preparing the job for processing; the service always returns this status when the job is initially created or when it is waiting for capacity to process the job. processing: The service is actively processing the job. completed: The service has finished processing the job; if the job specified a callback URL and the event recognitions.completed_with_results, the service sent the results with the callback notification; otherwise, use the GET /v1/recognitions/{id} method to retrieve the results. failed: The job failed. + /// + public string status { get; set; } + } + #endregion + + #region Custom Models + /// + /// This data class contains information about the speech to text model customizations. + /// + public class Customizations + { + /// + /// Information about each available custom model. The array is empty if the user owns no custom models (if no language is specified) or owns no custom models for the specified language. + /// + public Customization[] customizations { get; set; } + } + + /// + /// This data class contains information about the Speech to Text model customizations. + /// + public class Customization + { + /// + /// The GUID of the custom language model. + /// + public string customization_id { get; set; } + /// + /// The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). + /// + public string created { get; set; } + /// + /// The language of the custom language model. Currently, only en-US is supported. + /// + public string language { get; set; } + /// + /// The GUID of the service credentials for the owner of the custom language model. + /// + public string owner { get; set; } + /// + /// The name of the custom language model. + /// + public string name { get; set; } + /// + /// The description of the custom language model. + /// + public string description { get; set; } + /// + /// The name of the base language model for which the custom language model was created. = ['en-US_BroadbandModel', 'en-US_NarrowbandModel']. + /// + public string base_model_name { get; set; } + /// + /// The current status of the custom language model: pending indicates that the model was created but is waiting either for training data to be added or for the service to finish analyzing added data. ready indicates that the model contains data and is ready to be trained. training indicates that the model is currently being trained. For this beta release, the status field continues to be ready while the model is being trained; the field does not currently report a status of training. available indicates that the model is trained and ready to use. failed indicates that training of the model failed. = ['pending', 'ready', 'training', 'available', 'failed']. + /// + public string status { get; set; } + /// + /// A percentage that indicates the progress of the model's current training. A value of 100 means that the model is fully trained. For this beta release, the progress field does not reflect the current progress of the training; the field changes from 0 to 100 when training is complete. + /// + public int progress { get; set; } + /// + /// If the request included unknown query parameters, the following message: Unexpected query parameter(s) ['parameters'] detected, where parameters is a list that includes a quoted string for each unknown parameter. + /// + public string warnings { get; set; } + } + + /// + /// This data class contains information about the language model customization identifier. + /// + public class CustomizationID + { + /// + /// The GUID of the new custom language model. + /// + public string customization_id { get; set; } + } + + /// + /// A data object that contains data to create a new empty custom language mode3l. + /// + [fsObject] + public class CustomLanguage + { + /// + /// Name of the new custom language model. + /// + public string name { get; set; } + /// + /// The base model name - Currently only en-US_BroadbandModel is supported. + /// + public string base_model_name { get; set; } + /// + /// Description of the new custom voice model. + /// + public string description { get; set; } + } + + /// + /// The type of words from the custom model's words resource on which to train the model: all (the default) trains the model on all new words, regardless of whether they were extracted from corpora or were added or modified by the user. user trains the model only on new words that were added or modified by the user; the model is not trained on new words extracted from corpora. + /// + public class WordTypeToAdd + { + /// + /// All word types. + /// + public const string ALL = "all"; + /// + /// User word types. + /// + public const string USER = "user"; + } + #endregion + + #region Custom Corpora + /// + /// This data class contains information about multiple custom corpora. + /// + public class Corpora + { + /// + /// Information about corpora of the custom model. The array is empty if the custom model has no corpora. + /// + public Corpus[] corpora { get; set; } + } + + /// + /// This data class contains information about the custom corpus. + /// + public class Corpus + { + /// + /// The name of the corpus. + /// + public string name { get; set; } + /// + /// The total number of words in the corpus. The value is 0 while the corpus is being processed. + /// + public int total_words { get; set; } + /// + /// The number of OOV words in the corpus. The value is 0 while the corpus is being processed. + /// + public int out_of_vocabulary_words { get; set; } + /// + /// The status of the corpus: analyzed indicates that the service has successfully analyzed the corpus; the custom model can be trained with data from the corpus. being_processed indicates that the service is still analyzing the corpus; the service cannot accept requests to add new corpora or words, or to train the custom model. undetermined indicates that the service encountered an error while processing the corpus. = ['analyzed', 'being_processed', 'undetermined'] + /// + public string status { get; set; } + /// + /// If the status of the corpus is undetermined, the following message: Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'. + /// + public string error { get; set; } + } + #endregion + + #region Custom Words + /// + /// This data class contains information about multiple custom words. + /// + [fsObject] + public class WordsList + { + /// + /// Information about each word in the custom model's words resource. The array is empty if the custom model has no words. + /// + public WordData[] words { get; set; } + } + + /// + /// This data class contains information about the custom word data. + /// + [fsObject] + public class WordData + { + /// + /// A custom word from the custom model. The spelling of the word is used to train the model. + /// + public string word { get; set; } + /// + /// An array of pronunciations for the custom word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes pre-processing the word. + /// + public string[] sounds_like { get; set; } + /// + /// The spelling of the custom word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. + /// + public string display_as { get; set; } + /// + /// An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string user. + /// + public string[] source { get; set; } + /// + /// If the service discovered a problem with the custom word's definition that you need to correct, a message that describes the problem, for example: Numbers are not allowed in sounds-like. You must correct the error before you can train the model. + /// + public string error { get; set; } + } + + /// + /// The type of words to be listed from the custom language model's words resource: all (the default) shows all words. user shows only custom words that were added or modified by the user. corpora shows only OOV that were extracted from corpora. + /// + public class WordType + { + /// + /// All words. + /// + public const string ALL = "all"; + /// + /// User words. + /// + public const string USER = "user"; + /// + /// Corpora words. + /// + public const string CORPORA = "corpora"; + } + + /// + /// Words object for adding words to a customization. + /// + [fsObject] + public class Words + { + /// + /// The words to add to a customization. + /// + public Word[] words { get; set; } + } + + /// + /// A word to add to a customization. + /// + [fsObject] + public class Word + { + /// + /// The word. + /// + public string word { get; set; } + /// + /// What the word sounds like. + /// + public string[] sounds_like { get; set; } + /// + /// How the word is displayed. + /// + public string display_as { get; set; } + } + #endregion } diff --git a/Scripts/Services/SpeechToText/SpeechToText.cs b/Scripts/Services/SpeechToText/SpeechToText.cs index 26100e048..0d68e539c 100755 --- a/Scripts/Services/SpeechToText/SpeechToText.cs +++ b/Scripts/Services/SpeechToText/SpeechToText.cs @@ -32,1833 +32,1833 @@ namespace IBM.Watson.DeveloperCloud.Services.SpeechToText.v1 { - /// - /// This class wraps the Watson Speech to Text service. - /// Speech to Text Service - /// - public class SpeechToText : IWatsonService - { - #region Constants - /// - /// This ID is used to match up a configuration record with this service. - /// - private const string SERVICE_ID = "SpeechToTextV1"; - /// - /// How often to send a message to the web socket to keep it alive. - /// - private const float WS_KEEP_ALIVE_TIME = 20.0f; - /// - /// If no listen state is received after start is sent within this time, we will timeout - /// and stop listening. - /// - private const float LISTEN_TIMEOUT = 10.0f; - /// - /// How many recording AudioClips will we queue before we enter a error state. - /// - private const int MAX_QUEUED_RECORDINGS = 30; - /// - /// Size of a clip in bytes that can be sent through the Recognize function. - /// - private const int MAX_RECOGNIZE_CLIP_SIZE = 4 * (1024 * 1024); - #endregion - - #region Public Types - /// - /// This callback is used to return errors through the OnError property. - /// - /// A string containing the error message. - public delegate void ErrorEvent(string error); - /// - /// The delegate for loading a file. - /// - /// The filename to load. - /// Should return a byte array of the file contents or null of failure. - public delegate byte[] LoadFileDelegate(string filename); - /// - /// Set this property to overload the internal file loading of this class. - /// - public LoadFileDelegate LoadFile { get; set; } - #endregion - - #region Private Data - private OnRecognize m_ListenCallback = null; // Callback is set by StartListening() - private WSConnector m_ListenSocket = null; // WebSocket object used when StartListening() is invoked - private bool m_ListenActive = false; - private bool m_AudioSent = false; - private bool m_IsListening = false; - private Queue m_ListenRecordings = new Queue(); - private int m_KeepAliveRoutine = 0; // ID of the keep alive co-routine - private DateTime m_LastKeepAlive = DateTime.Now; - private DateTime m_LastStartSent = DateTime.Now; - private string m_RecognizeModel = "en-US_BroadbandModel"; // ID of the model to use. - private int m_MaxAlternatives = 1; // maximum number of alternatives to return. - private bool m_Timestamps = false; - private bool m_WordConfidence = false; - private bool m_DetectSilence = true; // If true, then we will try not to record silence. - private float m_SilenceThreshold = 0.03f; // If the audio level is below this value, then it's considered silent. - private int m_RecordingHZ = -1; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Public Properties - /// - /// True if StartListening() has been called. - /// - public bool IsListening { get { return m_IsListening; } private set { m_IsListening = value; } } - /// - /// True if AudioData has been sent and we are recognizing speech. - /// - public bool AudioSent { get { return m_AudioSent; } } - /// - /// This delegate is invoked when an error occurs. - /// - public ErrorEvent OnError { get; set; } - /// - /// This property controls which recognize model we use when making recognize requests of the server. - /// - public string RecognizeModel + /// + /// This class wraps the Watson Speech to Text service. + /// Speech to Text Service + /// + public class SpeechToText : IWatsonService + { + #region Constants + /// + /// This ID is used to match up a configuration record with this service. + /// + private const string SERVICE_ID = "SpeechToTextV1"; + /// + /// How often to send a message to the web socket to keep it alive. + /// + private const float WS_KEEP_ALIVE_TIME = 20.0f; + /// + /// If no listen state is received after start is sent within this time, we will timeout + /// and stop listening. + /// + private const float LISTEN_TIMEOUT = 10.0f; + /// + /// How many recording AudioClips will we queue before we enter a error state. + /// + private const int MAX_QUEUED_RECORDINGS = 30; + /// + /// Size of a clip in bytes that can be sent through the Recognize function. + /// + private const int MAX_RECOGNIZE_CLIP_SIZE = 4 * (1024 * 1024); + #endregion + + #region Public Types + /// + /// This callback is used to return errors through the OnError property. + /// + /// A string containing the error message. + public delegate void ErrorEvent(string error); + /// + /// The delegate for loading a file. + /// + /// The filename to load. + /// Should return a byte array of the file contents or null of failure. + public delegate byte[] LoadFileDelegate(string filename); + /// + /// Set this property to overload the internal file loading of this class. + /// + public LoadFileDelegate LoadFile { get; set; } + #endregion + + #region Private Data + private OnRecognize m_ListenCallback = null; // Callback is set by StartListening() + private WSConnector m_ListenSocket = null; // WebSocket object used when StartListening() is invoked + private bool m_ListenActive = false; + private bool m_AudioSent = false; + private bool m_IsListening = false; + private Queue m_ListenRecordings = new Queue(); + private int m_KeepAliveRoutine = 0; // ID of the keep alive co-routine + private DateTime m_LastKeepAlive = DateTime.Now; + private DateTime m_LastStartSent = DateTime.Now; + private string m_RecognizeModel = "en-US_BroadbandModel"; // ID of the model to use. + private int m_MaxAlternatives = 1; // maximum number of alternatives to return. + private bool m_Timestamps = false; + private bool m_WordConfidence = false; + private bool m_DetectSilence = true; // If true, then we will try not to record silence. + private float m_SilenceThreshold = 0.03f; // If the audio level is below this value, then it's considered silent. + private int m_RecordingHZ = -1; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Public Properties + /// + /// True if StartListening() has been called. + /// + public bool IsListening { get { return m_IsListening; } private set { m_IsListening = value; } } + /// + /// True if AudioData has been sent and we are recognizing speech. + /// + public bool AudioSent { get { return m_AudioSent; } } + /// + /// This delegate is invoked when an error occurs. + /// + public ErrorEvent OnError { get; set; } + /// + /// This property controls which recognize model we use when making recognize requests of the server. + /// + public string RecognizeModel + { + get { return m_RecognizeModel; } + set + { + if (m_RecognizeModel != value) { - get { return m_RecognizeModel; } - set - { - if (m_RecognizeModel != value) - { - m_RecognizeModel = value; - StopListening(); // close any active connection when our model is changed. - } - } + m_RecognizeModel = value; + StopListening(); // close any active connection when our model is changed. } - /// - /// Returns the maximum number of alternatives returned by recognize. - /// - public int MaxAlternatives { get { return m_MaxAlternatives; } set { m_MaxAlternatives = value; } } - /// - /// True to return timestamps of words with results. - /// - public bool EnableTimestamps { get { return m_Timestamps; } set { m_Timestamps = value; } } - /// - /// True to return word confidence with results. - /// - public bool EnableWordConfidence { get { return m_WordConfidence; } set { m_WordConfidence = value; } } - /// - /// If true, then we will try to continuously recognize speech. - /// - public bool EnableContinousRecognition { get; set; } - /// - /// If true, then we will get interim results while recognizing. The user will then need to check - /// the Final flag on the results. - /// - public bool EnableInterimResults { get; set; } - /// - /// If true, then we will try not to send silent audio clips to the server. This can save bandwidth - /// when no sound is happening. - /// - public bool DetectSilence { get { return m_DetectSilence; } set { m_DetectSilence = value; } } - /// - /// A value from 1.0 to 0.0 that determines what is considered silence. If the audio level is below this value - /// then we consider it silence. - /// - public float SilenceThreshold { get { return m_SilenceThreshold; } set { m_SilenceThreshold = value; } } - #endregion - - #region Get Models - /// - /// This callback object is used by the GetModels() method. - /// - /// - public delegate void OnGetModels(Model[] models); - - /// - /// This function retrieves all the language models that the user may use by setting the RecognizeModel - /// public property. - /// - /// This callback is invoked with an array of all available models. The callback will - /// be invoked with null on error. - /// Returns true if request has been made. - public bool GetModels(OnGetModels callback) - { - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/models"); - if (connector == null) - return false; + } + } + /// + /// Returns the maximum number of alternatives returned by recognize. + /// + public int MaxAlternatives { get { return m_MaxAlternatives; } set { m_MaxAlternatives = value; } } + /// + /// True to return timestamps of words with results. + /// + public bool EnableTimestamps { get { return m_Timestamps; } set { m_Timestamps = value; } } + /// + /// True to return word confidence with results. + /// + public bool EnableWordConfidence { get { return m_WordConfidence; } set { m_WordConfidence = value; } } + /// + /// If true, then we will try to continuously recognize speech. + /// + public bool EnableContinousRecognition { get; set; } + /// + /// If true, then we will get interim results while recognizing. The user will then need to check + /// the Final flag on the results. + /// + public bool EnableInterimResults { get; set; } + /// + /// If true, then we will try not to send silent audio clips to the server. This can save bandwidth + /// when no sound is happening. + /// + public bool DetectSilence { get { return m_DetectSilence; } set { m_DetectSilence = value; } } + /// + /// A value from 1.0 to 0.0 that determines what is considered silence. If the audio level is below this value + /// then we consider it silence. + /// + public float SilenceThreshold { get { return m_SilenceThreshold; } set { m_SilenceThreshold = value; } } + #endregion + + #region Get Models + /// + /// This callback object is used by the GetModels() method. + /// + /// + public delegate void OnGetModels(Model[] models); + + /// + /// This function retrieves all the language models that the user may use by setting the RecognizeModel + /// public property. + /// + /// This callback is invoked with an array of all available models. The callback will + /// be invoked with null on error. + /// Returns true if request has been made. + public bool GetModels(OnGetModels callback) + { + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/models"); + if (connector == null) + return false; - GetModelsRequest req = new GetModelsRequest(); - req.Callback = callback; - req.OnResponse = OnGetModelsResponse; + GetModelsRequest req = new GetModelsRequest(); + req.Callback = callback; + req.OnResponse = OnGetModelsResponse; - return connector.Send(req); - } + return connector.Send(req); + } - private class GetModelsRequest : RESTConnector.Request - { - public OnGetModels Callback { get; set; } - }; + private class GetModelsRequest : RESTConnector.Request + { + public OnGetModels Callback { get; set; } + }; - private void OnGetModelsResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - GetModelsRequest gmr = req as GetModelsRequest; - if (gmr == null) - throw new WatsonException("Unexpected request type."); + private void OnGetModelsResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + GetModelsRequest gmr = req as GetModelsRequest; + if (gmr == null) + throw new WatsonException("Unexpected request type."); + + Model[] models = null; + if (resp.Success) + { + models = ParseGetModelsResponse(resp.Data); + if (models == null) + Log.Error("SpeechToText", "Failed to parse GetModels response."); + } + if (gmr.Callback != null) + gmr.Callback(models); + } - Model[] models = null; - if (resp.Success) - { - models = ParseGetModelsResponse(resp.Data); - if (models == null) - Log.Error("SpeechToText", "Failed to parse GetModels response."); - } - if (gmr.Callback != null) - gmr.Callback(models); + private Model[] ParseGetModelsResponse(byte[] data) + { + string jsonString = Encoding.UTF8.GetString(data); + if (jsonString == null) + { + Log.Error("SpeechToText", "Failed to get JSON string from response."); + return null; + } + + IDictionary json = (IDictionary)Json.Deserialize(jsonString); + if (json == null) + { + Log.Error("SpechToText", "Failed to parse JSON: {0}", jsonString); + return null; + } + + try + { + List models = new List(); + + IList imodels = json["models"] as IList; + if (imodels == null) + throw new Exception("Expected IList"); + + foreach (var m in imodels) + { + IDictionary imodel = m as IDictionary; + if (imodel == null) + throw new Exception("Expected IDictionary"); + + Model model = new Model(); + model.name = (string)imodel["name"]; + model.rate = (long)imodel["rate"]; + model.language = (string)imodel["language"]; + model.description = (string)imodel["description"]; + model.url = (string)imodel["url"]; + + models.Add(model); } - private Model[] ParseGetModelsResponse(byte[] data) - { - string jsonString = Encoding.UTF8.GetString(data); - if (jsonString == null) - { - Log.Error("SpeechToText", "Failed to get JSON string from response."); - return null; - } + return models.ToArray(); + } + catch (Exception e) + { + Log.Error("SpeechToText", "Caught exception {0} when parsing GetModels() response: {1}", e.ToString(), jsonString); + } - IDictionary json = (IDictionary)Json.Deserialize(jsonString); - if (json == null) - { - Log.Error("SpechToText", "Failed to parse JSON: {0}", jsonString); - return null; - } + return null; + } + #endregion + + #region Get Model + /// + /// This callback object is used by the GetModel() method. + /// + /// The resultant model. + public delegate void OnGetModel(Model model); + + /// + /// This function retrieves a specified languageModel. + /// + /// This callback is invoked with the requested model. The callback will + /// be invoked with null on error. + /// The name of the model to get. + /// Returns true if request has been made. + public bool GetModel(OnGetModel callback, string modelID) + { + if (string.IsNullOrEmpty(modelID)) + throw new ArgumentNullException("modelID"); - try - { - List models = new List(); + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/models/" + modelID); + if (connector == null) + return false; - IList imodels = json["models"] as IList; - if (imodels == null) - throw new Exception("Expected IList"); + GetModelRequest req = new GetModelRequest(); + req.Callback = callback; + req.ModelID = modelID; + req.OnResponse = OnGetModelResponse; - foreach (var m in imodels) - { - IDictionary imodel = m as IDictionary; - if (imodel == null) - throw new Exception("Expected IDictionary"); - - Model model = new Model(); - model.name = (string)imodel["name"]; - model.rate = (long)imodel["rate"]; - model.language = (string)imodel["language"]; - model.description = (string)imodel["description"]; - model.url = (string)imodel["url"]; - - models.Add(model); - } + return connector.Send(req); + } - return models.ToArray(); - } - catch (Exception e) - { - Log.Error("SpeechToText", "Caught exception {0} when parsing GetModels() response: {1}", e.ToString(), jsonString); - } + private class GetModelRequest : RESTConnector.Request + { + public OnGetModel Callback { get; set; } + public string ModelID { get; set; } + }; - return null; + private void OnGetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + Model response = new Model(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region Get Model - /// - /// This callback object is used by the GetModel() method. - /// - /// The resultant model. - public delegate void OnGetModel(Model model); - - /// - /// This function retrieves a specified languageModel. - /// - /// This callback is invoked with the requested model. The callback will - /// be invoked with null on error. - /// The name of the model to get. - /// Returns true if request has been made. - public bool GetModel(OnGetModel callback, string modelID) - { - if (string.IsNullOrEmpty(modelID)) - throw new ArgumentNullException("modelID"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/models/" + modelID); - if (connector == null) - return false; - - GetModelRequest req = new GetModelRequest(); - req.Callback = callback; - req.ModelID = modelID; - req.OnResponse = OnGetModelResponse; - - return connector.Send(req); - } - - private class GetModelRequest : RESTConnector.Request - { - public OnGetModel Callback { get; set; } - public string ModelID { get; set; } - }; - - private void OnGetModelResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - Model response = new Model(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch(Exception e) - { - Log.Error("SpeechToText", "Caught exception {0} when parsing GetModel() response: {1}", e.ToString(), Encoding.UTF8.GetString(resp.Data)); - } - - if (resp == null) - Log.Error("SpeechToText", "Failed to parse GetModel response."); - } - - if (((GetModelRequest)req).Callback != null) - ((GetModelRequest)req).Callback(resp.Success ? response :null); - } - #endregion - - #region Sessionless - Streaming - /// - /// This callback object is used by the Recognize() and StartListening() methods. - /// - /// The ResultList object containing the results. - public delegate void OnRecognize(SpeechRecognitionEvent results); - - /// - /// This starts the service listening and it will invoke the callback for any recognized speech. - /// OnListen() must be called by the user to queue audio data to send to the service. - /// StopListening() should be called when you want to stop listening. - /// - /// All recognize results are passed to this callback. - /// Returns true on success, false on failure. - public bool StartListening(OnRecognize callback) + catch (Exception e) { - if (callback == null) - throw new ArgumentNullException("callback"); - if (m_IsListening) - return false; - if (!CreateListenConnector()) - return false; - - m_IsListening = true; - m_ListenCallback = callback; - m_KeepAliveRoutine = Runnable.Run(KeepAlive()); - m_LastKeepAlive = DateTime.Now; - - return true; + Log.Error("SpeechToText", "Caught exception {0} when parsing GetModel() response: {1}", e.ToString(), Encoding.UTF8.GetString(resp.Data)); } - /// - /// This function should be invoked with the AudioData input after StartListening() method has been invoked. - /// The user should continue to invoke this function until they are ready to call StopListening(), typically - /// microphone input is sent to this function. - /// - /// A AudioData object containing the AudioClip and max level found in the clip. - public void OnListen(AudioData clip) - { - if (m_IsListening) - { - if (m_RecordingHZ < 0) - { - m_RecordingHZ = clip.Clip.frequency; - SendStart(); - } + if (resp == null) + Log.Error("SpeechToText", "Failed to parse GetModel response."); + } - if (!DetectSilence || clip.MaxLevel >= m_SilenceThreshold) - { - if (m_ListenActive) - { - m_ListenSocket.Send(new WSConnector.BinaryMessage(AudioClipUtil.GetL16(clip.Clip))); - m_AudioSent = true; - } - else - { - // we have not received the "listening" state yet from the server, so just queue - // the audio clips until that happens. - m_ListenRecordings.Enqueue(clip); - - // check the length of this queue and do something if it gets too full. - if (m_ListenRecordings.Count > MAX_QUEUED_RECORDINGS) - { - Log.Error("SpeechToText", "Recording queue is full."); - - StopListening(); - if (OnError != null) - OnError("Recording queue is full."); - } - } - } - else if (m_AudioSent) - { - SendStop(); - m_AudioSent = false; - } + if (((GetModelRequest)req).Callback != null) + ((GetModelRequest)req).Callback(resp.Success ? response : null); + } + #endregion + + #region Sessionless - Streaming + /// + /// This callback object is used by the Recognize() and StartListening() methods. + /// + /// The ResultList object containing the results. + public delegate void OnRecognize(SpeechRecognitionEvent results); + + /// + /// This starts the service listening and it will invoke the callback for any recognized speech. + /// OnListen() must be called by the user to queue audio data to send to the service. + /// StopListening() should be called when you want to stop listening. + /// + /// All recognize results are passed to this callback. + /// Returns true on success, false on failure. + public bool StartListening(OnRecognize callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (m_IsListening) + return false; + if (!CreateListenConnector()) + return false; + + m_IsListening = true; + m_ListenCallback = callback; + m_KeepAliveRoutine = Runnable.Run(KeepAlive()); + m_LastKeepAlive = DateTime.Now; + + return true; + } - // After sending start, we should get into the listening state within the amount of time specified - // by LISTEN_TIMEOUT. If not, then stop listening and record the error. - if (!m_ListenActive && (DateTime.Now - m_LastStartSent).TotalSeconds > LISTEN_TIMEOUT) - { - Log.Error("SpeechToText", "Failed to enter listening state."); + /// + /// This function should be invoked with the AudioData input after StartListening() method has been invoked. + /// The user should continue to invoke this function until they are ready to call StopListening(), typically + /// microphone input is sent to this function. + /// + /// A AudioData object containing the AudioClip and max level found in the clip. + public void OnListen(AudioData clip) + { + if (m_IsListening) + { + if (m_RecordingHZ < 0) + { + m_RecordingHZ = clip.Clip.frequency; + SendStart(); + } - StopListening(); - if (OnError != null) - OnError("Failed to enter listening state."); - } + if (!DetectSilence || clip.MaxLevel >= m_SilenceThreshold) + { + if (m_ListenActive) + { + m_ListenSocket.Send(new WSConnector.BinaryMessage(AudioClipUtil.GetL16(clip.Clip))); + m_AudioSent = true; + } + else + { + // we have not received the "listening" state yet from the server, so just queue + // the audio clips until that happens. + m_ListenRecordings.Enqueue(clip); + + // check the length of this queue and do something if it gets too full. + if (m_ListenRecordings.Count > MAX_QUEUED_RECORDINGS) + { + Log.Error("SpeechToText", "Recording queue is full."); + + StopListening(); + if (OnError != null) + OnError("Recording queue is full."); } + } + } + else if (m_AudioSent) + { + SendStop(); + m_AudioSent = false; } - /// - /// Invoke this function stop this service from listening. - /// - /// Returns true on success, false on failure. - public bool StopListening() + // After sending start, we should get into the listening state within the amount of time specified + // by LISTEN_TIMEOUT. If not, then stop listening and record the error. + if (!m_ListenActive && (DateTime.Now - m_LastStartSent).TotalSeconds > LISTEN_TIMEOUT) { - if (!m_IsListening) - return false; + Log.Error("SpeechToText", "Failed to enter listening state."); - m_IsListening = false; - CloseListenConnector(); + StopListening(); + if (OnError != null) + OnError("Failed to enter listening state."); + } + } + } - if (m_KeepAliveRoutine != 0) - { - Runnable.Stop(m_KeepAliveRoutine); - m_KeepAliveRoutine = 0; - } + /// + /// Invoke this function stop this service from listening. + /// + /// Returns true on success, false on failure. + public bool StopListening() + { + if (!m_IsListening) + return false; - m_ListenRecordings.Clear(); - m_ListenCallback = null; - m_RecordingHZ = -1; + m_IsListening = false; + CloseListenConnector(); - return true; - } + if (m_KeepAliveRoutine != 0) + { + Runnable.Stop(m_KeepAliveRoutine); + m_KeepAliveRoutine = 0; + } - private bool CreateListenConnector() - { - if (m_ListenSocket == null) - { - m_ListenSocket = WSConnector.CreateConnector(SERVICE_ID, "/v1/recognize", "?model=" + WWW.EscapeURL(m_RecognizeModel)); - if (m_ListenSocket == null) - return false; + m_ListenRecordings.Clear(); + m_ListenCallback = null; + m_RecordingHZ = -1; - m_ListenSocket.OnMessage = OnListenMessage; - m_ListenSocket.OnClose = OnListenClosed; - } + return true; + } - return true; - } + private bool CreateListenConnector() + { + if (m_ListenSocket == null) + { + m_ListenSocket = WSConnector.CreateConnector(SERVICE_ID, "/v1/recognize", "?model=" + WWW.EscapeURL(m_RecognizeModel)); + if (m_ListenSocket == null) + return false; - private void CloseListenConnector() - { - if (m_ListenSocket != null) - { - m_ListenSocket.Close(); - m_ListenSocket = null; - } - } + m_ListenSocket.OnMessage = OnListenMessage; + m_ListenSocket.OnClose = OnListenClosed; + } - private void SendStart() - { - if (m_ListenSocket == null) - throw new WatsonException("SendStart() called with null connector."); - - Dictionary start = new Dictionary(); - start["action"] = "start"; - start["content-type"] = "audio/l16;rate=" + m_RecordingHZ.ToString() + ";channels=1;"; - start["continuous"] = EnableContinousRecognition; - start["max_alternatives"] = m_MaxAlternatives; - start["interim_results"] = EnableInterimResults; - start["word_confidence"] = m_WordConfidence; - start["timestamps"] = m_Timestamps; - - m_ListenSocket.Send(new WSConnector.TextMessage(Json.Serialize(start))); - m_LastStartSent = DateTime.Now; - } + return true; + } - private void SendStop() - { - if (m_ListenSocket == null) - throw new WatsonException("SendStart() called with null connector."); + private void CloseListenConnector() + { + if (m_ListenSocket != null) + { + m_ListenSocket.Close(); + m_ListenSocket = null; + } + } - if (m_ListenActive) - { - Dictionary stop = new Dictionary(); - stop["action"] = "stop"; + private void SendStart() + { + if (m_ListenSocket == null) + throw new WatsonException("SendStart() called with null connector."); + + Dictionary start = new Dictionary(); + start["action"] = "start"; + start["content-type"] = "audio/l16;rate=" + m_RecordingHZ.ToString() + ";channels=1;"; + start["continuous"] = EnableContinousRecognition; + start["max_alternatives"] = m_MaxAlternatives; + start["interim_results"] = EnableInterimResults; + start["word_confidence"] = m_WordConfidence; + start["timestamps"] = m_Timestamps; + + m_ListenSocket.Send(new WSConnector.TextMessage(Json.Serialize(start))); + m_LastStartSent = DateTime.Now; + } - m_ListenSocket.Send(new WSConnector.TextMessage(Json.Serialize(stop))); - m_LastStartSent = DateTime.Now; // sending stop, will send the listening state again.. - m_ListenActive = false; - } - } + private void SendStop() + { + if (m_ListenSocket == null) + throw new WatsonException("SendStart() called with null connector."); + + if (m_ListenActive) + { + Dictionary stop = new Dictionary(); + stop["action"] = "stop"; + + m_ListenSocket.Send(new WSConnector.TextMessage(Json.Serialize(stop))); + m_LastStartSent = DateTime.Now; // sending stop, will send the listening state again.. + m_ListenActive = false; + } + } - // This keeps the WebSocket connected when we are not sending any data. - private IEnumerator KeepAlive() - { - while (m_ListenSocket != null) - { - yield return null; + // This keeps the WebSocket connected when we are not sending any data. + private IEnumerator KeepAlive() + { + while (m_ListenSocket != null) + { + yield return null; - if ((DateTime.Now - m_LastKeepAlive).TotalSeconds > WS_KEEP_ALIVE_TIME) - { - Dictionary nop = new Dictionary(); - nop["action"] = "no-op"; + if ((DateTime.Now - m_LastKeepAlive).TotalSeconds > WS_KEEP_ALIVE_TIME) + { + Dictionary nop = new Dictionary(); + nop["action"] = "no-op"; #if ENABLE_DEBUGGING - Log.Debug("SpeechToText", "Sending keep alive."); + Log.Debug("SpeechToText", "Sending keep alive."); #endif - m_ListenSocket.Send(new WSConnector.TextMessage(Json.Serialize(nop))); - m_LastKeepAlive = DateTime.Now; - } - } - Log.Debug("SpeechToText", "KeepAlive exited."); + m_ListenSocket.Send(new WSConnector.TextMessage(Json.Serialize(nop))); + m_LastKeepAlive = DateTime.Now; } + } + Log.Debug("SpeechToText", "KeepAlive exited."); + } + + private void OnListenMessage(WSConnector.Message msg) + { + if (msg is WSConnector.TextMessage) + { + WSConnector.TextMessage tm = (WSConnector.TextMessage)msg; - private void OnListenMessage(WSConnector.Message msg) + IDictionary json = Json.Deserialize(tm.Text) as IDictionary; + if (json != null) { - if (msg is WSConnector.TextMessage) + if (json.Contains("results")) + { + SpeechRecognitionEvent results = ParseRecognizeResponse(json); + if (results != null) { - WSConnector.TextMessage tm = (WSConnector.TextMessage)msg; - - IDictionary json = Json.Deserialize(tm.Text) as IDictionary; - if (json != null) - { - if (json.Contains("results")) - { - SpeechRecognitionEvent results = ParseRecognizeResponse(json); - if (results != null) - { - // when we get results, start listening for the next block .. - // if continuous is true, then we don't need to do this.. - if (!EnableContinousRecognition && results.HasFinalResult()) - SendStart(); - - if (m_ListenCallback != null) - m_ListenCallback(results); - else - StopListening(); // automatically stop listening if our callback is destroyed. - } - else - Log.Error("SpeechToText", "Failed to parse results: {0}", tm.Text); - } - else if (json.Contains("state")) - { - string state = (string)json["state"]; + // when we get results, start listening for the next block .. + // if continuous is true, then we don't need to do this.. + if (!EnableContinousRecognition && results.HasFinalResult()) + SendStart(); + + if (m_ListenCallback != null) + m_ListenCallback(results); + else + StopListening(); // automatically stop listening if our callback is destroyed. + } + else + Log.Error("SpeechToText", "Failed to parse results: {0}", tm.Text); + } + else if (json.Contains("state")) + { + string state = (string)json["state"]; #if ENABLE_DEBUGGING - Log.Debug("SpeechToText", "Server state is {0}", state); + Log.Debug("SpeechToText", "Server state is {0}", state); #endif - if (state == "listening") - { - if (m_IsListening) - { - if (!m_ListenActive) - { - m_ListenActive = true; - - // send all pending audio clips .. - while (m_ListenRecordings.Count > 0) - { - AudioData clip = m_ListenRecordings.Dequeue(); - m_ListenSocket.Send(new WSConnector.BinaryMessage(AudioClipUtil.GetL16(clip.Clip))); - m_AudioSent = true; - } - } - } - } - - } - else if (json.Contains("error")) - { - string error = (string)json["error"]; - Log.Error("SpeechToText", "Error: {0}", error); - - StopListening(); - if (OnError != null) - OnError(error); - } - else - { - Log.Warning("SpeechToText", "Unknown message: {0}", tm.Text); - } - } - else + if (state == "listening") + { + if (m_IsListening) + { + if (!m_ListenActive) { - Log.Error("SpeechToText", "Failed to parse JSON from server: {0}", tm.Text); + m_ListenActive = true; + + // send all pending audio clips .. + while (m_ListenRecordings.Count > 0) + { + AudioData clip = m_ListenRecordings.Dequeue(); + m_ListenSocket.Send(new WSConnector.BinaryMessage(AudioClipUtil.GetL16(clip.Clip))); + m_AudioSent = true; + } } + } } - } - private void OnListenClosed(WSConnector connector) + } + else if (json.Contains("error")) + { + string error = (string)json["error"]; + Log.Error("SpeechToText", "Error: {0}", error); + + StopListening(); + if (OnError != null) + OnError(error); + } + else + { + Log.Warning("SpeechToText", "Unknown message: {0}", tm.Text); + } + } + else { + Log.Error("SpeechToText", "Failed to parse JSON from server: {0}", tm.Text); + } + } + } + + private void OnListenClosed(WSConnector connector) + { #if ENABLE_DEBUGGING - Log.Debug("SpeechToText", "OnListenClosed(), State = {0}", connector.State.ToString()); + Log.Debug("SpeechToText", "OnListenClosed(), State = {0}", connector.State.ToString()); #endif - m_ListenActive = false; - StopListening(); + m_ListenActive = false; + StopListening(); - if (connector.State == WSConnector.ConnectionState.DISCONNECTED) - { - if (OnError != null) - OnError("Disconnected from server."); - } + if (connector.State == WSConnector.ConnectionState.DISCONNECTED) + { + if (OnError != null) + OnError("Disconnected from server."); + } + } + #endregion + + #region Sessionless Non-Streaming + /// + /// This function POSTs the given audio clip the recognize function and convert speech into text. This function should be used + /// only on AudioClips under 4MB once they have been converted into WAV format. Use the StartListening() for continuous + /// recognition of text. + /// + /// The AudioClip object. + /// A callback to invoke with the results. + /// + public bool Recognize(AudioClip clip, OnRecognize callback) + { + if (clip == null) + throw new ArgumentNullException("clip"); + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/recognize"); + if (connector == null) + return false; + + RecognizeRequest req = new RecognizeRequest(); + req.Clip = clip; + req.Callback = callback; + + req.Headers["Content-Type"] = "audio/wav"; + req.Send = WaveFile.CreateWAV(clip); + if (req.Send.Length > MAX_RECOGNIZE_CLIP_SIZE) + { + Log.Error("SpeechToText", "AudioClip is too large for Recognize()."); + return false; + } + req.Parameters["model"] = m_RecognizeModel; + req.Parameters["continuous"] = "false"; + req.Parameters["max_alternatives"] = m_MaxAlternatives.ToString(); + req.Parameters["timestamps"] = m_Timestamps ? "true" : "false"; + req.Parameters["word_confidence"] = m_WordConfidence ? "true" : "false"; + req.OnResponse = OnRecognizeResponse; + + return connector.Send(req); + } + + private class RecognizeRequest : RESTConnector.Request + { + public AudioClip Clip { get; set; } + public OnRecognize Callback { get; set; } + }; + + private void OnRecognizeResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + RecognizeRequest recognizeReq = req as RecognizeRequest; + if (recognizeReq == null) + throw new WatsonException("Unexpected request type."); + + SpeechRecognitionEvent result = null; + if (resp.Success) + { + result = ParseRecognizeResponse(resp.Data); + if (result == null) + { + Log.Error("SpeechToText", "Failed to parse json response: {0}", + resp.Data != null ? Encoding.UTF8.GetString(resp.Data) : ""); } - #endregion - - #region Sessionless Non-Streaming - /// - /// This function POSTs the given audio clip the recognize function and convert speech into text. This function should be used - /// only on AudioClips under 4MB once they have been converted into WAV format. Use the StartListening() for continuous - /// recognition of text. - /// - /// The AudioClip object. - /// A callback to invoke with the results. - /// - public bool Recognize(AudioClip clip, OnRecognize callback) + else { - if (clip == null) - throw new ArgumentNullException("clip"); - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/recognize"); - if (connector == null) - return false; - - RecognizeRequest req = new RecognizeRequest(); - req.Clip = clip; - req.Callback = callback; - - req.Headers["Content-Type"] = "audio/wav"; - req.Send = WaveFile.CreateWAV(clip); - if (req.Send.Length > MAX_RECOGNIZE_CLIP_SIZE) - { - Log.Error("SpeechToText", "AudioClip is too large for Recognize()."); - return false; - } - req.Parameters["model"] = m_RecognizeModel; - req.Parameters["continuous"] = "false"; - req.Parameters["max_alternatives"] = m_MaxAlternatives.ToString(); - req.Parameters["timestamps"] = m_Timestamps ? "true" : "false"; - req.Parameters["word_confidence"] = m_WordConfidence ? "true" : "false"; - req.OnResponse = OnRecognizeResponse; - - return connector.Send(req); + Log.Status("SpeechToText", "Received Recognize Response, Elapsed Time: {0}, Results: {1}", + resp.ElapsedTime, result.results.Length); } + } + else + { + Log.Error("SpeechToText", "Recognize Error: {0}", resp.Error); + } + + if (recognizeReq.Callback != null) + recognizeReq.Callback(result); + } - private class RecognizeRequest : RESTConnector.Request - { - public AudioClip Clip { get; set; } - public OnRecognize Callback { get; set; } - }; + private SpeechRecognitionEvent ParseRecognizeResponse(byte[] json) + { + string jsonString = Encoding.UTF8.GetString(json); + if (jsonString == null) + return null; - private void OnRecognizeResponse(RESTConnector.Request req, RESTConnector.Response resp) - { - RecognizeRequest recognizeReq = req as RecognizeRequest; - if (recognizeReq == null) - throw new WatsonException("Unexpected request type."); + IDictionary resp = (IDictionary)Json.Deserialize(jsonString); + if (resp == null) + return null; + + return ParseRecognizeResponse(resp); + } - SpeechRecognitionEvent result = null; - if (resp.Success) + private SpeechRecognitionEvent ParseRecognizeResponse(IDictionary resp) + { + if (resp == null) + return null; + + try + { + List results = new List(); + IList iresults = resp["results"] as IList; + if (iresults == null) + return null; + + foreach (var r in iresults) + { + IDictionary iresult = r as IDictionary; + if (iresults == null) + continue; + + SpeechRecognitionResult result = new SpeechRecognitionResult(); + result.final = (bool)iresult["final"]; + + IList ialternatives = iresult["alternatives"] as IList; + if (ialternatives == null) + continue; + + List alternatives = new List(); + foreach (var a in ialternatives) + { + IDictionary ialternative = a as IDictionary; + if (ialternative == null) + continue; + + SpeechRecognitionAlternative alternative = new SpeechRecognitionAlternative(); + alternative.transcript = (string)ialternative["transcript"]; + if (ialternative.Contains("confidence")) + alternative.confidence = (double)ialternative["confidence"]; + + if (ialternative.Contains("timestamps")) { - result = ParseRecognizeResponse(resp.Data); - if (result == null) - { - Log.Error("SpeechToText", "Failed to parse json response: {0}", - resp.Data != null ? Encoding.UTF8.GetString(resp.Data) : ""); - } - else - { - Log.Status("SpeechToText", "Received Recognize Response, Elapsed Time: {0}, Results: {1}", - resp.ElapsedTime, result.results.Length); - } + IList itimestamps = ialternative["timestamps"] as IList; + + TimeStamp[] timestamps = new TimeStamp[itimestamps.Count]; + for (int i = 0; i < itimestamps.Count; ++i) + { + IList itimestamp = itimestamps[i] as IList; + if (itimestamp == null) + continue; + + TimeStamp ts = new TimeStamp(); + ts.Word = (string)itimestamp[0]; + ts.Start = (double)itimestamp[1]; + ts.End = (double)itimestamp[2]; + timestamps[i] = ts; + } + + alternative.Timestamps = timestamps; } - else + if (ialternative.Contains("word_confidence")) { - Log.Error("SpeechToText", "Recognize Error: {0}", resp.Error); + IList iconfidence = ialternative["word_confidence"] as IList; + + WordConfidence[] confidence = new WordConfidence[iconfidence.Count]; + for (int i = 0; i < iconfidence.Count; ++i) + { + IList iwordconf = iconfidence[i] as IList; + if (iwordconf == null) + continue; + + WordConfidence wc = new WordConfidence(); + wc.Word = (string)iwordconf[0]; + wc.Confidence = (double)iwordconf[1]; + confidence[i] = wc; + } + + alternative.WordConfidence = confidence; } - if (recognizeReq.Callback != null) - recognizeReq.Callback(result); + alternatives.Add(alternative); + } + result.alternatives = alternatives.ToArray(); + results.Add(result); } - private SpeechRecognitionEvent ParseRecognizeResponse(byte[] json) + return new SpeechRecognitionEvent(results.ToArray()); + } + catch (Exception e) + { + Log.Error("SpeechToText", "ParseJsonResponse exception: {0}", e.ToString()); + return null; + } + } + #endregion + + #region Asynchronous + #endregion + + #region Get Custom Models + /// + /// This callback is used by the GetCustomizations() function. + /// + /// The customizations + /// Optional custom data. + public delegate void GetCustomizationsCallback(Customizations customizations, string data); + + /// + /// Lists information about all custom language models that are owned by the calling user. Use the language query parameter to see all custom models for the specified language; omit the parameter to see all custom models for all languages. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. + /// Optional custom data. + /// + public bool GetCustomizations(GetCustomizationsCallback callback, string language = "en-US", string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + + GetCustomizationsReq req = new GetCustomizationsReq(); + req.Callback = callback; + req.Data = customData; + req.Language = language; + req.Parameters["language"] = language; + req.OnResponse = OnGetCustomizationsResp; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomizationsReq : RESTConnector.Request + { + public GetCustomizationsCallback Callback { get; set; } + public string Language { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomizationsResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Customizations customizations = new Customizations(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = customizations; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) { - string jsonString = Encoding.UTF8.GetString(json); - if (jsonString == null) - return null; + Log.Error("Speech To Text", "GetCustomizations Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetCustomizationsReq)req).Callback != null) + ((GetCustomizationsReq)req).Callback(resp.Success ? customizations : null, ((GetCustomizationsReq)req).Data); + } + #endregion + + #region Create Custom Model + /// + /// Thid callback is used by the CreateCustomization() function. + /// + /// The customizationID. + /// Optional custom data. + public delegate void CreateCustomizationCallback(CustomizationID customizationID, string data); + + /// + /// Creates a new custom language model for a specified base language model. The custom language model can be used only with the base language model for which it is created. The new model is owned by the individual whose service credentials are used to create it. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The custom model name. + /// The base model name - only en-US_BroadbandModel is currently supported. + /// Descripotion of the custom model. + /// Optional custom data. + /// + public bool CreateCustomization(CreateCustomizationCallback callback, string name, string base_model_name = "en-US_BroadbandModel", string description = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(name)) + throw new ArgumentNullException("A name is required to create a custom language model."); + + CustomLanguage customLanguage = new CustomLanguage(); + customLanguage.name = name; + customLanguage.base_model_name = base_model_name; + customLanguage.description = string.IsNullOrEmpty(description) ? name : description; + + fsData data; + sm_Serializer.TrySerialize(customLanguage.GetType(), customLanguage, out data).AssertSuccessWithoutWarnings(); + string customizationJson = fsJsonPrinter.CompressedJson(data); + + CreateCustomizationRequest req = new CreateCustomizationRequest(); + req.Callback = callback; + req.CustomLanguage = customLanguage; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes(customizationJson); + req.OnResponse = OnCreateCustomizationResp; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); + if (connector == null) + return false; + + return connector.Send(req); + } - IDictionary resp = (IDictionary)Json.Deserialize(jsonString); - if (resp == null) - return null; + private class CreateCustomizationRequest : RESTConnector.Request + { + public CreateCustomizationCallback Callback { get; set; } + public CustomLanguage CustomLanguage { get; set; } + public string Data { get; set; } + } - return ParseRecognizeResponse(resp); + private void OnCreateCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + CustomizationID customizationID = new CustomizationID(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = customizationID; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } + catch (Exception e) + { + Log.Error("Speech To Text", "CreateCustomization Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((CreateCustomizationRequest)req).Callback != null) + ((CreateCustomizationRequest)req).Callback(resp.Success ? customizationID : null, ((CreateCustomizationRequest)req).Data); + } + #endregion + + #region Delete Custom Model + /// + /// This callback is used by the DeleteCustomization() function. + /// + /// + /// + public delegate void OnDeleteCustomizationCallback(bool success, string data); + /// + /// Deletes an existing custom language model. Only the owner of a custom model can use this method to delete the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The customization ID to be deleted. + /// Optional customization data. + /// + public bool DeleteCustomization(OnDeleteCustomizationCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to delete is required for DeleteCustomization"); + + DeleteCustomizationRequest req = new DeleteCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.Delete = true; + req.OnResponse = OnDeleteCustomizationResp; + + string service = "/v1/customizations/{0}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class DeleteCustomizationRequest : RESTConnector.Request + { + public OnDeleteCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } + + private void OnDeleteCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteCustomizationRequest)req).Callback != null) + ((DeleteCustomizationRequest)req).Callback(resp.Success, ((DeleteCustomizationRequest)req).Data); + } + #endregion + + #region Get Custom Model + /// + /// This callback is used by the GetCusomization() function. + /// + /// + /// + public delegate void GetCustomizationCallback(Customization customization, string data); + /// + /// Lists information about a custom language model. Only the owner of a custom model can use this method to query information about the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The requested custom language model's identifier. + /// Optional custom data. + /// + public bool GetCustomization(GetCustomizationCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to get a custom language model."); + + GetCustomizationRequest req = new GetCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.OnResponse = OnGetCustomizationResp; + + string service = "/v1/customizations/{0}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomizationRequest : RESTConnector.Request + { + public GetCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } - private SpeechRecognitionEvent ParseRecognizeResponse(IDictionary resp) + private void OnGetCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Customization customization = new Customization(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = customization; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) { - if (resp == null) - return null; + Log.Error("Speech To Text", "GetCustomization Exception: {0}", e.ToString()); + resp.Success = false; + } + } - try - { - List results = new List(); - IList iresults = resp["results"] as IList; - if (iresults == null) - return null; + if (((GetCustomizationRequest)req).Callback != null) + ((GetCustomizationRequest)req).Callback(resp.Success ? customization : null, ((GetCustomizationRequest)req).Data); + } + #endregion + + #region Train Custom Model + /// + /// This callback is used by the TrainCustomization() function. + /// + /// The success of the call. + /// Optional custom data. + public delegate void TrainCustomizationCallback(bool success, string data); + /// + /// Initiates the training of a custom language model with new corpora, words, or both.After adding training data to the custom model with the corpora or words methods, use this method to begin the actual training of the model on the new data.You can specify whether the custom model is to be trained with all words from its words resources or only with words that were added or modified by the user.Only the owner of a custom model can use this method to train the model. + /// This method is asynchronous and can take on the order of minutes to complete depending on the amount of data on which the service is being trained and the current load on the service.The method returns an HTTP 200 response code to indicate that the training process has begun. + /// You can monitor the status of the training by using the GET /v1/customizations/{customization_id} method to poll the model's status. Use a loop to check the status every 10 seconds. The method returns a Customization object that includes status and progress fields. A status of available means that the custom model is trained and ready to use. If training is in progress, the progress field indicates the progress of the training as a percentage complete. + /// Note: For this beta release, the progress field does not reflect the current progress of the training. The field changes from 0 to 100 when training is complete. + /// Training can fail to start for the following reasons: + /// No training data (corpora or words) have been added to the custom model. + /// Pre-processing of corpora to generate a list of out-of-vocabulary (OOV) words is not complete. + /// Pre-processing of words to validate or auto-generate sounds-like pronunciations is not complete. + /// One or more words that were added to the custom model have invalid sounds-like pronunciations that you must fix. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The requested custom language model's identifier. + /// Optional custom data. + /// + public bool TrainCustomization(TrainCustomizationCallback callback, string customizationID, string wordTypeToAdd = WordTypeToAdd.ALL, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to train a custom language model."); + + TrainCustomizationRequest req = new TrainCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.Parameters["word_type_to_add"] = wordTypeToAdd; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes("{}"); + req.OnResponse = OnTrainCustomizationResp; + + string service = "/v1/customizations/{0}/train"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } - foreach (var r in iresults) - { - IDictionary iresult = r as IDictionary; - if (iresults == null) - continue; - - SpeechRecognitionResult result = new SpeechRecognitionResult(); - result.final = (bool)iresult["final"]; - - IList ialternatives = iresult["alternatives"] as IList; - if (ialternatives == null) - continue; - - List alternatives = new List(); - foreach (var a in ialternatives) - { - IDictionary ialternative = a as IDictionary; - if (ialternative == null) - continue; - - SpeechRecognitionAlternative alternative = new SpeechRecognitionAlternative(); - alternative.transcript = (string)ialternative["transcript"]; - if (ialternative.Contains("confidence")) - alternative.confidence = (double)ialternative["confidence"]; - - if (ialternative.Contains("timestamps")) - { - IList itimestamps = ialternative["timestamps"] as IList; - - TimeStamp[] timestamps = new TimeStamp[itimestamps.Count]; - for (int i = 0; i < itimestamps.Count; ++i) - { - IList itimestamp = itimestamps[i] as IList; - if (itimestamp == null) - continue; - - TimeStamp ts = new TimeStamp(); - ts.Word = (string)itimestamp[0]; - ts.Start = (double)itimestamp[1]; - ts.End = (double)itimestamp[2]; - timestamps[i] = ts; - } - - alternative.Timestamps = timestamps; - } - if (ialternative.Contains("word_confidence")) - { - IList iconfidence = ialternative["word_confidence"] as IList; - - WordConfidence[] confidence = new WordConfidence[iconfidence.Count]; - for (int i = 0; i < iconfidence.Count; ++i) - { - IList iwordconf = iconfidence[i] as IList; - if (iwordconf == null) - continue; - - WordConfidence wc = new WordConfidence(); - wc.Word = (string)iwordconf[0]; - wc.Confidence = (double)iwordconf[1]; - confidence[i] = wc; - } - - alternative.WordConfidence = confidence; - } - - alternatives.Add(alternative); - } - result.alternatives = alternatives.ToArray(); - results.Add(result); - } + private class TrainCustomizationRequest : RESTConnector.Request + { + public TrainCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } - return new SpeechRecognitionEvent(results.ToArray()); - } - catch (Exception e) - { - Log.Error("SpeechToText", "ParseJsonResponse exception: {0}", e.ToString()); - return null; - } + private void OnTrainCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((TrainCustomizationRequest)req).Callback != null) + ((TrainCustomizationRequest)req).Callback(resp.Success, ((TrainCustomizationRequest)req).Data); + } + #endregion + + #region Reset Custom Model + /// + /// This callback is used by the ResetCustomization() function. + /// + /// The success of the call. + /// Optional custom data. + public delegate void ResetCustomizationCallback(bool success, string data); + /// + /// Resets a custom language model by removing all corpora and words from the model.Resetting a custom model initializes the model to its state when it was first created. Metadata such as the name and language of the model are preserved.Only the owner of a custom model can use this method to reset the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The requested custom language model's identifier. + /// Optional custom data. + /// + public bool ResetCustomization(ResetCustomizationCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to train a reset language model."); + + ResetCustomizationRequest req = new ResetCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes("{}"); + req.OnResponse = OnResetCustomizationResp; + + string service = "/v1/customizations/{0}/reset"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class ResetCustomizationRequest : RESTConnector.Request + { + public ResetCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } + + private void OnResetCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((ResetCustomizationRequest)req).Callback != null) + ((ResetCustomizationRequest)req).Callback(resp.Success, ((ResetCustomizationRequest)req).Data); + } + #endregion + + #region Upgrade Custom Model + /// + /// This callback is used by the UpgradeCustomization() function. + /// + /// The success of the call. + /// Optional custom data. + public delegate void UpgradeCustomizationCallback(bool success, string data); + /// + /// Upgrades a custom language model to the latest release level of the Speech to Text service. The method bases the upgrade on the latest trained data stored for the custom model. If the corpora or words for the model have changed since the model was last trained, you must use the POST /v1/customizations/{customization_id}/train method to train the model on the new data. Only the owner of a custom model can use this method to upgrade the model. + /// Note: This method is not currently implemented.It will be added for a future release of the API. + /// + /// The callback. + /// The requested custom language model's identifier. + /// Optional custom data. + /// + public bool UpgradeCustomization(UpgradeCustomizationCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to upgrade a custom language model."); + + UpgradeCustomizationRequest req = new UpgradeCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes("{}"); + req.OnResponse = OnResetCustomizationResp; + + string service = "/v1/customizations/{0}/upgrade"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class UpgradeCustomizationRequest : RESTConnector.Request + { + public UpgradeCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } + + private void OnUpgradeCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((UpgradeCustomizationRequest)req).Callback != null) + ((UpgradeCustomizationRequest)req).Callback(resp.Success, ((UpgradeCustomizationRequest)req).Data); + } + #endregion + + #region Get Custom Corpora + /// + /// This callback is used by the GetCustomCorpora() function. + /// + /// The corpora + /// Optional custom data. + public delegate void GetCustomCorporaCallback(Corpora corpora, string data); + + /// + /// Lists information about all corpora that have been added to the specified custom language model. The information includes the total number of words and out-of-vocabulary (OOV) words, name, and status of each corpus. Only the owner of a custom model can use this method to list the model's corpora. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. + /// Optional custom data. + /// + public bool GetCustomCorpora(GetCustomCorporaCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required to GetCustomCorpora"); + + GetCustomCorporaReq req = new GetCustomCorporaReq(); + req.Callback = callback; + req.Data = customData; + req.CustomizationID = customizationID; + req.OnResponse = OnGetCustomCorporaResp; + + string service = "/v1/customizations/{0}/corpora"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomCorporaReq : RESTConnector.Request + { + public GetCustomCorporaCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomCorporaResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Corpora corpora = new Corpora(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = corpora; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Speech To Text", "OnGetCustomCorporaResp Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetCustomCorporaReq)req).Callback != null) + ((GetCustomCorporaReq)req).Callback(resp.Success ? corpora : null, ((GetCustomCorporaReq)req).Data); + } + #endregion + + #region Delete Custom Corpus + /// + /// This callback is used by the DeleteCustomCorpus() function. + /// + /// + /// + public delegate void OnDeleteCustomCorpusCallback(bool success, string data); + /// + /// Deletes an existing corpus from a custom language model. The service removes any out-of-vocabulary (OOV) words associated with the corpus from the custom model's words resource unless they were also added by another corpus or they have been modified in some way with the POST /v1/customizations/{customization_id}/words or PUT /v1/customizations/{customization_id}/words/{word_name} method. Removing a corpus does not affect the custom model until you train the model with the POST /v1/customizations/{customization_id}/train method. Only the owner of a custom model can use this method to delete a corpus from the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The customization ID with the corpus to be deleted. + /// The corpus name to be deleted. + /// Optional customization data. + /// + public bool DeleteCustomCorpus(OnDeleteCustomCorpusCallback callback, string customizationID, string corpusName, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required for DeleteCustomCorpora."); + if (string.IsNullOrEmpty(corpusName)) + throw new ArgumentNullException("A corpusName to delete is required to DeleteCustomCorpora."); + + DeleteCustomCorpusRequest req = new DeleteCustomCorpusRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.CorpusName = corpusName; + req.Data = customData; + req.Delete = true; + req.OnResponse = OnDeleteCustomCorpusResp; + + string service = "/v1/customizations/{0}/corpora/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, corpusName)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class DeleteCustomCorpusRequest : RESTConnector.Request + { + public OnDeleteCustomCorpusCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string CorpusName { get; set; } + public string Data { get; set; } + } + + private void OnDeleteCustomCorpusResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteCustomCorpusRequest)req).Callback != null) + ((DeleteCustomCorpusRequest)req).Callback(resp.Success, ((DeleteCustomCorpusRequest)req).Data); + } + #endregion + + #region Add Custom Coprpus + /// + /// This callback is used by the AddCustomCorpus() function. + /// + /// + /// + public delegate void OnAddCustomCorpusCallback(bool success, string data); + /// + /// Adds a single corpus text file of new training data to the custom language model. Use multiple requests to submit multiple corpus text files. Only the owner of a custom model can use this method to add a corpus to the model. + /// Submit a plain text file that contains sample sentences from the domain of interest to enable the service to extract words in context.The more sentences you add that represent the context in which speakers use words from the domain, the better the service's recognition accuracy. Adding a corpus does not affect the custom model until you train the model for the new data by using the POST /v1/customizations/{customization_id}/train method. + /// Use the following guidelines to prepare a corpus text file: + /// - Provide a plain text file that is encoded in UTF-8 if it contains non-ASCII characters.The service assumes UTF-8 encoding if it encounters such characters. + /// - Include each sentence of the corpus on its own line, terminating each line with a carriage return. Including multiple sentences on the same line can degrade accuracy. + /// - Use consistent capitalization for words in the corpus. The words resource is case-sensitive; mix upper- and lowercase letters and use capitalization only when intended. + /// - Beware of typographical errors.The service assumes that typos are new words; unless you correct them before training the model, the service adds them to the model's vocabulary. + /// The service automatically does the following: + /// - Converts numbers to their equivalent words.For example: + /// 500 becomes five hundred + /// and + /// 0.15 becomes zero point fifteen + /// - Removes the following punctuation and special characters: + /// ! @ # $ % ^ & * - + = ~ _ . , ; : ( ) < > [ ] { } + /// - Ignores phrases enclosed in ( ) (parentheses), < > (angle brackets), [] (square brackets), and { } (curly braces). + /// - Converts tokens that include certain symbols to meaningful strings.For example, the service converts a $ (dollar sign) followed by a number to its string representation: + /// $100 becomes one hundred dollars + /// and it converts a % (percent sign) preceded by a number to its string representation: + /// 100% becomes one hundred percent + /// This list is not exhaustive; the service makes similar adjustments for other characters as needed. + /// + /// The call returns an HTTP 201 response code if the corpus is valid.It then asynchronously pre-processes the contents of the corpus and automatically extracts new words that it finds.This can take on the order of a minute or two to complete depending on the total number of words and the number of new words in the corpus, as well as the current load on the service.You cannot submit requests to add additional corpora or words to the custom model, or to train the model, until the service's analysis of the corpus for the current request completes. Use the GET /v1/customizations/{customization_id}/corpora method to check the status of the analysis. + /// + /// The service auto-populates the model's words resource with any word that is not found in its base vocabulary; these are referred to as out-of-vocabulary (OOV) words. You can use the GET /v1/customizations/{customization_id}/words method to examine the words resource, using other words method to eliminate typos and modify how words are pronounced as needed. + /// + /// To add a corpus file that has the same name as an existing corpus, set the allow_overwrite query parameter to true; otherwise, the request fails.Overwriting an existing corpus causes the service to process the corpus text file and extract OOV words anew.Before doing so, it removes any OOV words associated with the existing corpus from the model's words resource unless they were also added by another corpus or they have been modified in some way with the POST /v1/customizations/{customization_id}/words or PUT /v1/customizations/{customization_id}/words/{word_name} method. + /// + /// The service limits the overall amount of data that you can add to a custom model to a maximum of 10 million total words from all corpora combined.Also, you can add no more than 30 thousand new words to a model; this includes words that the service extracts from corpora and words that you add directly. + /// Note: This method is currently a beta release that is available for US English only + /// + /// The callback. + /// The customization ID with the corpus to be deleted. + /// The corpus name to be deleted. + /// Allow overwriting of corpus data. + /// A file path to plain text training data. + /// Optional customization data. + /// + public bool AddCustomCorpus(OnAddCustomCorpusCallback callback, string customizationID, string corpusName, bool allowOverwrite, string trainingPath, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required for AddCustomCorpus."); + if (string.IsNullOrEmpty(corpusName)) + throw new ArgumentNullException("A corpusName is required to AddCustomCorpus."); + if (string.IsNullOrEmpty(trainingPath)) + throw new ArgumentNullException("A path to training data is required to AddCustomCorpus"); + + byte[] trainingDataBytes = null; + + if (!string.IsNullOrEmpty(trainingPath)) + { + if (LoadFile != null) + { + trainingDataBytes = LoadFile(trainingPath); } - #endregion - - #region Asynchronous - #endregion - - #region Get Custom Models - /// - /// This callback is used by the GetCustomizations() function. - /// - /// The customizations - /// Optional custom data. - public delegate void GetCustomizationsCallback(Customizations customizations, string data); - - /// - /// Lists information about all custom language models that are owned by the calling user. Use the language query parameter to see all custom models for the specified language; omit the parameter to see all custom models for all languages. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. - /// Optional custom data. - /// - public bool GetCustomizations(GetCustomizationsCallback callback, string language = "en-US", string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - - GetCustomizationsReq req = new GetCustomizationsReq(); - req.Callback = callback; - req.Data = customData; - req.Language = language; - req.Parameters["language"] = language; - req.OnResponse = OnGetCustomizationsResp; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomizationsReq : RESTConnector.Request - { - public GetCustomizationsCallback Callback { get; set; } - public string Language { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomizationsResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Customizations customizations = new Customizations(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = customizations; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Speech To Text", "GetCustomizations Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomizationsReq)req).Callback != null) - ((GetCustomizationsReq)req).Callback(resp.Success ? customizations : null, ((GetCustomizationsReq)req).Data); - } - #endregion - - #region Create Custom Model - /// - /// Thid callback is used by the CreateCustomization() function. - /// - /// The customizationID. - /// Optional custom data. - public delegate void CreateCustomizationCallback(CustomizationID customizationID, string data); - - /// - /// Creates a new custom language model for a specified base language model. The custom language model can be used only with the base language model for which it is created. The new model is owned by the individual whose service credentials are used to create it. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The custom model name. - /// The base model name - only en-US_BroadbandModel is currently supported. - /// Descripotion of the custom model. - /// Optional custom data. - /// - public bool CreateCustomization(CreateCustomizationCallback callback, string name, string base_model_name = "en-US_BroadbandModel", string description = default(string), string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(name)) - throw new ArgumentNullException("A name is required to create a custom language model."); - - CustomLanguage customLanguage = new CustomLanguage(); - customLanguage.name = name; - customLanguage.base_model_name = base_model_name; - customLanguage.description = string.IsNullOrEmpty(description) ? name : description; - - fsData data; - sm_Serializer.TrySerialize(customLanguage.GetType(), customLanguage, out data).AssertSuccessWithoutWarnings(); - string customizationJson = fsJsonPrinter.CompressedJson(data); - - CreateCustomizationRequest req = new CreateCustomizationRequest(); - req.Callback = callback; - req.CustomLanguage = customLanguage; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(customizationJson); - req.OnResponse = OnCreateCustomizationResp; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class CreateCustomizationRequest : RESTConnector.Request - { - public CreateCustomizationCallback Callback { get; set; } - public CustomLanguage CustomLanguage { get; set; } - public string Data { get; set; } - } - - private void OnCreateCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - CustomizationID customizationID = new CustomizationID(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = customizationID; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Speech To Text", "CreateCustomization Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((CreateCustomizationRequest)req).Callback != null) - ((CreateCustomizationRequest)req).Callback(resp.Success ? customizationID : null, ((CreateCustomizationRequest)req).Data); - } - #endregion - - #region Delete Custom Model - /// - /// This callback is used by the DeleteCustomization() function. - /// - /// - /// - public delegate void OnDeleteCustomizationCallback(bool success, string data); - /// - /// Deletes an existing custom language model. Only the owner of a custom model can use this method to delete the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The customization ID to be deleted. - /// Optional customization data. - /// - public bool DeleteCustomization(OnDeleteCustomizationCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to delete is required for DeleteCustomization"); - - DeleteCustomizationRequest req = new DeleteCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.Delete = true; - req.OnResponse = OnDeleteCustomizationResp; - - string service = "/v1/customizations/{0}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class DeleteCustomizationRequest : RESTConnector.Request - { - public OnDeleteCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnDeleteCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteCustomizationRequest)req).Callback != null) - ((DeleteCustomizationRequest)req).Callback(resp.Success, ((DeleteCustomizationRequest)req).Data); - } - #endregion - - #region Get Custom Model - /// - /// This callback is used by the GetCusomization() function. - /// - /// - /// - public delegate void GetCustomizationCallback(Customization customization, string data); - /// - /// Lists information about a custom language model. Only the owner of a custom model can use this method to query information about the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The requested custom language model's identifier. - /// Optional custom data. - /// - public bool GetCustomization(GetCustomizationCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to get a custom language model."); - - GetCustomizationRequest req = new GetCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.OnResponse = OnGetCustomizationResp; - - string service = "/v1/customizations/{0}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomizationRequest : RESTConnector.Request - { - public GetCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Customization customization = new Customization(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = customization; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Speech To Text", "GetCustomization Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomizationRequest)req).Callback != null) - ((GetCustomizationRequest)req).Callback(resp.Success ? customization : null, ((GetCustomizationRequest)req).Data); - } - #endregion - - #region Train Custom Model - /// - /// This callback is used by the TrainCustomization() function. - /// - /// The success of the call. - /// Optional custom data. - public delegate void TrainCustomizationCallback(bool success, string data); - /// - /// Initiates the training of a custom language model with new corpora, words, or both.After adding training data to the custom model with the corpora or words methods, use this method to begin the actual training of the model on the new data.You can specify whether the custom model is to be trained with all words from its words resources or only with words that were added or modified by the user.Only the owner of a custom model can use this method to train the model. - /// This method is asynchronous and can take on the order of minutes to complete depending on the amount of data on which the service is being trained and the current load on the service.The method returns an HTTP 200 response code to indicate that the training process has begun. - /// You can monitor the status of the training by using the GET /v1/customizations/{customization_id} method to poll the model's status. Use a loop to check the status every 10 seconds. The method returns a Customization object that includes status and progress fields. A status of available means that the custom model is trained and ready to use. If training is in progress, the progress field indicates the progress of the training as a percentage complete. - /// Note: For this beta release, the progress field does not reflect the current progress of the training. The field changes from 0 to 100 when training is complete. - /// Training can fail to start for the following reasons: - /// No training data (corpora or words) have been added to the custom model. - /// Pre-processing of corpora to generate a list of out-of-vocabulary (OOV) words is not complete. - /// Pre-processing of words to validate or auto-generate sounds-like pronunciations is not complete. - /// One or more words that were added to the custom model have invalid sounds-like pronunciations that you must fix. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The requested custom language model's identifier. - /// Optional custom data. - /// - public bool TrainCustomization(TrainCustomizationCallback callback, string customizationID, string wordTypeToAdd = WordTypeToAdd.ALL, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to train a custom language model."); - - TrainCustomizationRequest req = new TrainCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.Parameters["word_type_to_add"] = wordTypeToAdd; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes("{}"); - req.OnResponse = OnTrainCustomizationResp; - - string service = "/v1/customizations/{0}/train"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class TrainCustomizationRequest : RESTConnector.Request - { - public TrainCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnTrainCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((TrainCustomizationRequest)req).Callback != null) - ((TrainCustomizationRequest)req).Callback(resp.Success, ((TrainCustomizationRequest)req).Data); - } - #endregion - - #region Reset Custom Model - /// - /// This callback is used by the ResetCustomization() function. - /// - /// The success of the call. - /// Optional custom data. - public delegate void ResetCustomizationCallback(bool success, string data); - /// - /// Resets a custom language model by removing all corpora and words from the model.Resetting a custom model initializes the model to its state when it was first created. Metadata such as the name and language of the model are preserved.Only the owner of a custom model can use this method to reset the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The requested custom language model's identifier. - /// Optional custom data. - /// - public bool ResetCustomization(ResetCustomizationCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to train a reset language model."); - - ResetCustomizationRequest req = new ResetCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes("{}"); - req.OnResponse = OnResetCustomizationResp; - - string service = "/v1/customizations/{0}/reset"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class ResetCustomizationRequest : RESTConnector.Request - { - public ResetCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnResetCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((ResetCustomizationRequest)req).Callback != null) - ((ResetCustomizationRequest)req).Callback(resp.Success, ((ResetCustomizationRequest)req).Data); - } - #endregion - - #region Upgrade Custom Model - /// - /// This callback is used by the UpgradeCustomization() function. - /// - /// The success of the call. - /// Optional custom data. - public delegate void UpgradeCustomizationCallback(bool success, string data); - /// - /// Upgrades a custom language model to the latest release level of the Speech to Text service. The method bases the upgrade on the latest trained data stored for the custom model. If the corpora or words for the model have changed since the model was last trained, you must use the POST /v1/customizations/{customization_id}/train method to train the model on the new data. Only the owner of a custom model can use this method to upgrade the model. - /// Note: This method is not currently implemented.It will be added for a future release of the API. - /// - /// The callback. - /// The requested custom language model's identifier. - /// Optional custom data. - /// - public bool UpgradeCustomization(UpgradeCustomizationCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to upgrade a custom language model."); - - UpgradeCustomizationRequest req = new UpgradeCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes("{}"); - req.OnResponse = OnResetCustomizationResp; - - string service = "/v1/customizations/{0}/upgrade"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class UpgradeCustomizationRequest : RESTConnector.Request - { - public UpgradeCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnUpgradeCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((UpgradeCustomizationRequest)req).Callback != null) - ((UpgradeCustomizationRequest)req).Callback(resp.Success, ((UpgradeCustomizationRequest)req).Data); - } - #endregion - - #region Get Custom Corpora - /// - /// This callback is used by the GetCustomCorpora() function. - /// - /// The corpora - /// Optional custom data. - public delegate void GetCustomCorporaCallback(Corpora corpora, string data); - - /// - /// Lists information about all corpora that have been added to the specified custom language model. The information includes the total number of words and out-of-vocabulary (OOV) words, name, and status of each corpus. Only the owner of a custom model can use this method to list the model's corpora. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. - /// Optional custom data. - /// - public bool GetCustomCorpora(GetCustomCorporaCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required to GetCustomCorpora"); - - GetCustomCorporaReq req = new GetCustomCorporaReq(); - req.Callback = callback; - req.Data = customData; - req.CustomizationID = customizationID; - req.OnResponse = OnGetCustomCorporaResp; - - string service = "/v1/customizations/{0}/corpora"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomCorporaReq : RESTConnector.Request - { - public GetCustomCorporaCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomCorporaResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Corpora corpora = new Corpora(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = corpora; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Speech To Text", "OnGetCustomCorporaResp Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomCorporaReq)req).Callback != null) - ((GetCustomCorporaReq)req).Callback(resp.Success ? corpora : null, ((GetCustomCorporaReq)req).Data); - } - #endregion - - #region Delete Custom Corpus - /// - /// This callback is used by the DeleteCustomCorpus() function. - /// - /// - /// - public delegate void OnDeleteCustomCorpusCallback(bool success, string data); - /// - /// Deletes an existing corpus from a custom language model. The service removes any out-of-vocabulary (OOV) words associated with the corpus from the custom model's words resource unless they were also added by another corpus or they have been modified in some way with the POST /v1/customizations/{customization_id}/words or PUT /v1/customizations/{customization_id}/words/{word_name} method. Removing a corpus does not affect the custom model until you train the model with the POST /v1/customizations/{customization_id}/train method. Only the owner of a custom model can use this method to delete a corpus from the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The customization ID with the corpus to be deleted. - /// The corpus name to be deleted. - /// Optional customization data. - /// - public bool DeleteCustomCorpus(OnDeleteCustomCorpusCallback callback, string customizationID, string corpusName, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required for DeleteCustomCorpora."); - if (string.IsNullOrEmpty(corpusName)) - throw new ArgumentNullException("A corpusName to delete is required to DeleteCustomCorpora."); - - DeleteCustomCorpusRequest req = new DeleteCustomCorpusRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.CorpusName = corpusName; - req.Data = customData; - req.Delete = true; - req.OnResponse = OnDeleteCustomCorpusResp; - - string service = "/v1/customizations/{0}/corpora/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, corpusName)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class DeleteCustomCorpusRequest : RESTConnector.Request - { - public OnDeleteCustomCorpusCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string CorpusName { get; set; } - public string Data { get; set; } - } - - private void OnDeleteCustomCorpusResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteCustomCorpusRequest)req).Callback != null) - ((DeleteCustomCorpusRequest)req).Callback(resp.Success, ((DeleteCustomCorpusRequest)req).Data); - } - #endregion - - #region Add Custom Coprpus - /// - /// This callback is used by the AddCustomCorpus() function. - /// - /// - /// - public delegate void OnAddCustomCorpusCallback(bool success, string data); - /// - /// Adds a single corpus text file of new training data to the custom language model. Use multiple requests to submit multiple corpus text files. Only the owner of a custom model can use this method to add a corpus to the model. - /// Submit a plain text file that contains sample sentences from the domain of interest to enable the service to extract words in context.The more sentences you add that represent the context in which speakers use words from the domain, the better the service's recognition accuracy. Adding a corpus does not affect the custom model until you train the model for the new data by using the POST /v1/customizations/{customization_id}/train method. - /// Use the following guidelines to prepare a corpus text file: - /// - Provide a plain text file that is encoded in UTF-8 if it contains non-ASCII characters.The service assumes UTF-8 encoding if it encounters such characters. - /// - Include each sentence of the corpus on its own line, terminating each line with a carriage return. Including multiple sentences on the same line can degrade accuracy. - /// - Use consistent capitalization for words in the corpus. The words resource is case-sensitive; mix upper- and lowercase letters and use capitalization only when intended. - /// - Beware of typographical errors.The service assumes that typos are new words; unless you correct them before training the model, the service adds them to the model's vocabulary. - /// The service automatically does the following: - /// - Converts numbers to their equivalent words.For example: - /// 500 becomes five hundred - /// and - /// 0.15 becomes zero point fifteen - /// - Removes the following punctuation and special characters: - /// ! @ # $ % ^ & * - + = ~ _ . , ; : ( ) < > [ ] { } - /// - Ignores phrases enclosed in ( ) (parentheses), < > (angle brackets), [] (square brackets), and { } (curly braces). - /// - Converts tokens that include certain symbols to meaningful strings.For example, the service converts a $ (dollar sign) followed by a number to its string representation: - /// $100 becomes one hundred dollars - /// and it converts a % (percent sign) preceded by a number to its string representation: - /// 100% becomes one hundred percent - /// This list is not exhaustive; the service makes similar adjustments for other characters as needed. - /// - /// The call returns an HTTP 201 response code if the corpus is valid.It then asynchronously pre-processes the contents of the corpus and automatically extracts new words that it finds.This can take on the order of a minute or two to complete depending on the total number of words and the number of new words in the corpus, as well as the current load on the service.You cannot submit requests to add additional corpora or words to the custom model, or to train the model, until the service's analysis of the corpus for the current request completes. Use the GET /v1/customizations/{customization_id}/corpora method to check the status of the analysis. - /// - /// The service auto-populates the model's words resource with any word that is not found in its base vocabulary; these are referred to as out-of-vocabulary (OOV) words. You can use the GET /v1/customizations/{customization_id}/words method to examine the words resource, using other words method to eliminate typos and modify how words are pronounced as needed. - /// - /// To add a corpus file that has the same name as an existing corpus, set the allow_overwrite query parameter to true; otherwise, the request fails.Overwriting an existing corpus causes the service to process the corpus text file and extract OOV words anew.Before doing so, it removes any OOV words associated with the existing corpus from the model's words resource unless they were also added by another corpus or they have been modified in some way with the POST /v1/customizations/{customization_id}/words or PUT /v1/customizations/{customization_id}/words/{word_name} method. - /// - /// The service limits the overall amount of data that you can add to a custom model to a maximum of 10 million total words from all corpora combined.Also, you can add no more than 30 thousand new words to a model; this includes words that the service extracts from corpora and words that you add directly. - /// Note: This method is currently a beta release that is available for US English only - /// - /// The callback. - /// The customization ID with the corpus to be deleted. - /// The corpus name to be deleted. - /// Allow overwriting of corpus data. - /// A file path to plain text training data. - /// Optional customization data. - /// - public bool AddCustomCorpus(OnAddCustomCorpusCallback callback, string customizationID, string corpusName, bool allowOverwrite, string trainingPath, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required for AddCustomCorpus."); - if (string.IsNullOrEmpty(corpusName)) - throw new ArgumentNullException("A corpusName is required to AddCustomCorpus."); - if (string.IsNullOrEmpty(trainingPath)) - throw new ArgumentNullException("A path to training data is required to AddCustomCorpus"); - - byte[] trainingDataBytes = null; - - if (!string.IsNullOrEmpty(trainingPath)) - { - if (LoadFile != null) - { - trainingDataBytes = LoadFile(trainingPath); - } - else - { + else + { #if !UNITY_WEBPLAYER - trainingDataBytes = File.ReadAllBytes(trainingPath); + trainingDataBytes = File.ReadAllBytes(trainingPath); #endif - } - - if (trainingDataBytes == null) - Log.Error("SpeechToText", "Failed to upload {0}!", trainingPath); - } - - return AddCustomCorpus(callback, customizationID, corpusName, allowOverwrite, trainingDataBytes); - } - - /// - /// Overload method for AddCustomCorpus that takes byteArray training data. - /// - /// The callback. - /// The customization ID with the corpus to be deleted. - /// The corpus name to be deleted. - /// Allow overwriting of corpus data. - /// ByteArray data for training data. - /// Optional customization data. - public bool AddCustomCorpus(OnAddCustomCorpusCallback callback, string customizationID, string corpusName, bool allowOverwrite, byte[] trainingData, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required for AddCustomCorpus."); - if (string.IsNullOrEmpty(corpusName)) - throw new ArgumentNullException("A corpusName is requried for AddCustomCorpus."); - if (trainingData == default(byte[])) - throw new ArgumentNullException("Training data is required for AddCustomCorpus."); - - AddCustomCorpusRequest req = new AddCustomCorpusRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.CorpusName = corpusName; - req.Data = customData; - req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; - req.Headers["Accept"] = "application/json"; - req.Parameters["allow_overwrite"] = allowOverwrite.ToString(); - req.Forms = new Dictionary(); - req.Forms["body"] = new RESTConnector.Form(trainingData, "trainingData.txt", "text/plain"); - req.OnResponse = OnAddCustomCorpusResp; - - string service = "/v1/customizations/{0}/corpora/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, corpusName)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class AddCustomCorpusRequest : RESTConnector.Request - { - public OnAddCustomCorpusCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string CorpusName { get; set; } - public bool AllowOverwrite { get; set; } - public byte[] TrainingData { get; set; } - public string Data { get; set; } - } - - private void OnAddCustomCorpusResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((AddCustomCorpusRequest)req).Callback != null) - ((AddCustomCorpusRequest)req).Callback(resp.Success, ((AddCustomCorpusRequest)req).Data); - } - #endregion - - #region Get Custom Words - /// - /// This callback is used by the GetCustomWords() function. - /// - /// The custom words - /// Optional custom data. - public delegate void GetCustomWordsCallback(WordsList wordList, string data); - - /// - /// Lists information about all custom words from a custom language model. You can list all words from the custom model's words resource, only custom words that were added or modified by the user, or only OOV words that were extracted from corpora. Only the owner of a custom model can use this method to query the words from the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. - /// Optional custom data. - /// - public bool GetCustomWords(GetCustomWordsCallback callback, string customizationID, string wordType = WordType.ALL, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("customizationID"); - - GetCustomWordsReq req = new GetCustomWordsReq(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.WordType = wordType; - req.Data = customData; - req.Parameters["word_type"] = wordType.ToString(); - req.OnResponse = OnGetCustomWordsResp; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format("/v1/customizations/{0}/words", customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomWordsReq : RESTConnector.Request - { - public GetCustomWordsCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string WordType { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomWordsResp(RESTConnector.Request req, RESTConnector.Response resp) - { - WordsList wordsList = new WordsList(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = wordsList; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Speech To Text", "OnGetCustomWordsResp Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomWordsReq)req).Callback != null) - ((GetCustomWordsReq)req).Callback(resp.Success ? wordsList : null, ((GetCustomWordsReq)req).Data); - } - #endregion - - #region Add Custom Words - /// - /// This callback is used by the AddCustomWords() function. - /// - /// The success of the call. - /// Optional custom data. - public delegate void AddCustomWordsCallback(bool success, string data); - /// - /// Adds one or more custom words to a custom language model.The service populates the words resource for a custom model with out-of-vocabulary(OOV) words found in each corpus added to the model.You can use this method to add additional words or to modify existing words in the words resource.Only the owner of a custom model can use this method to add or modify custom words associated with the model.Adding or modifying custom words does not affect the custom model until you train the model for the new data by using the POST /v1/customizations/{customization_id}/train method. - /// You add custom words by providing a Words object, which is an array of Word objects, one per word.You must use the object's word parameter to identify the word that is to be added. You can also provide one or both of the optional sounds_like and display_as fields for each word. - /// The sounds_like field provides an array of one or more pronunciations for the word. Use the parameter to specify how the word can be pronounced by users.Use the parameter for words that are difficult to pronounce, foreign words, acronyms, and so on.For example, you might specify that the word IEEE can sound like i triple e.You can specify a maximum of five sounds-like pronunciations for a word, and each pronunciation must adhere to the following rules: - /// Use English alphabetic characters: a-z and A-Z. - /// To pronounce a single letter, use the letter followed by a period, for example, N.C.A.A. for the word NCAA. - /// Use real or made-up words that are pronounceable in the native language, for example, shuchensnie for the word Sczcesny. - /// Substitute equivalent English letters for non-English letters, for example, s for ç or ny for ñ. - /// Substitute non-accented letters for accented letters, for example a for à or e for è. - /// Use the spelling of numbers, for example, seventy-five for 75. - /// You can include multiple words separated by spaces, but the service enforces a maximum of 40 total characters not including spaces. - /// The display_as field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in corpora training data.For example, you might indicate that the word IBM(trademark) is to be displayed as IBM™. - /// If you add a custom word that already exists in the words resource for the custom model, the new definition overrides the existing data for the word.If the service encounters an error with the input data, it returns a failure code and does not add any of the words to the words resource. - /// The call returns an HTTP 201 response code if the input data is valid.It then asynchronously pre-processes the words to add them to the model's words resource. The time that it takes for the analysis to complete depends on the number of new words that you add but is generally faster than adding a corpus or training a model. - /// You can use the GET /v1/customizations/{ customization_id}/words or GET /v1/customizations/{customization_id}/words/{word_name} method to review the words that you add.Words with an invalid sounds_like field include an error field that describes the problem.You can use other words methods to correct errors, eliminate typos, and modify how words are pronounced as needed. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The requested custom language model's identifier. - /// A boolean used to differentiate overloads with identical input types.. - /// A path to a json file to train. - /// Optional custom data. - /// - public bool AddCustomWords(AddCustomWordsCallback callback, string customizationID, bool useDataPath, string wordsJsonPath, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to add words to a custom language model."); - if (string.IsNullOrEmpty(wordsJsonPath)) - throw new ArgumentNullException("A wordsJsonPath is required to add words to a custom language model."); - - string wordsJson = File.ReadAllText(wordsJsonPath); - - return AddCustomWords(callback, customizationID, wordsJson); - } - - public bool AddCustomWords(AddCustomWordsCallback callback, string customizationID, Words words, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to add words to a custom language model."); - if (words == null || words.words == null || words.words.Length == 0) - throw new WatsonException("Custom words are required to add words to a custom language model."); - - fsData data; - sm_Serializer.TrySerialize(words.GetType(), words, out data).AssertSuccessWithoutWarnings(); - string wordsJson = fsJsonPrinter.CompressedJson(data); - - return AddCustomWords(callback, customizationID, wordsJson, customData); - } - - public bool AddCustomWords(AddCustomWordsCallback callback, string customizationID, string wordsJson, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to add words to a custom language model."); - if (string.IsNullOrEmpty(wordsJson)) - throw new ArgumentNullException("A wordsJsonPath is required to add words to a custom language model."); - - AddCustomWordsRequest req = new AddCustomWordsRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.WordsJson = wordsJson; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(wordsJson); - req.OnResponse = OnAddCustomWordsResp; - - string service = "/v1/customizations/{0}/words"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class AddCustomWordsRequest : RESTConnector.Request - { - public AddCustomWordsCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string WordsJson { get; set; } - public string Data { get; set; } - } - - private void OnAddCustomWordsResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((AddCustomWordsRequest)req).Callback != null) - ((AddCustomWordsRequest)req).Callback(resp.Success, ((AddCustomWordsRequest)req).Data); - } - #endregion - - #region Delete Custom Word - /// - /// This callback is used by the DeleteCustomWord() function. - /// - /// - /// - public delegate void OnDeleteCustomWordCallback(bool success, string data); - /// - /// Deletes a custom word from a custom language model. You can remove any word that you added to the custom model's words resource via any means. However, if the word also exists in the service's base vocabulary, the service removes only the custom pronunciation for the word; the word remains in the base vocabulary. - /// Removing a custom word does not affect the custom model until you train the model with the POST /v1/customizations/{customization_id}/train method.Only the owner of a custom model can use this method to delete a word from the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The customization ID to be deleted. - /// Optional customization data. - /// - public bool DeleteCustomWord(OnDeleteCustomWordCallback callback, string customizationID, string word, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required for DeleteCustomWord"); - if (string.IsNullOrEmpty(word)) - throw new ArgumentNullException("A word to delete is requried for DeleteCustomWord"); - - DeleteCustomWordRequest req = new DeleteCustomWordRequest();req.Callback = callback; - req.CustomizationID = customizationID; - req.Word = word; - req.Data = customData; - req.Delete = true; - req.OnResponse = OnDeleteCustomWordResp; - - string service = "/v1/customizations/{0}/words/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class DeleteCustomWordRequest : RESTConnector.Request - { - public OnDeleteCustomWordCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Word { get; set; } - public string Data { get; set; } - } - - private void OnDeleteCustomWordResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteCustomWordRequest)req).Callback != null) - ((DeleteCustomWordRequest)req).Callback(resp.Success, ((DeleteCustomWordRequest)req).Data); - } - #endregion - - #region Get Custom Word - /// - /// This callback is used by the GetCustomWord() function. - /// - /// The word - /// Optional custom data. - public delegate void GetCustomWordCallback(WordData word, string data); - - /// - /// Lists information about a custom word from a custom language model. Only the owner of a custom model can use this method to query a word from the model. - /// Note: This method is currently a beta release that is available for US English only. - /// - /// The callback. - /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. - /// Optional custom data. - /// - public bool GetCustomWord(GetCustomWordCallback callback, string customizationID, string word, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required to GetCustomWord"); - if (string.IsNullOrEmpty(word)) - throw new ArgumentNullException("A word is required to GetCustomWord"); - - GetCustomWordReq req = new GetCustomWordReq(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Word = word; - req.Data = customData; - req.OnResponse = OnGetCustomWordResp; - - string service = "/v1/customizations/{0}/words/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomWordReq : RESTConnector.Request - { - public GetCustomWordCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Word { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomWordResp(RESTConnector.Request req, RESTConnector.Response resp) - { - WordData word = new WordData(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = word; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Speech To Text", "OnGetCustomWordResp Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomWordReq)req).Callback != null) - ((GetCustomWordReq)req).Callback(resp.Success ? word : null, ((GetCustomWordReq)req).Data); - } - #endregion - - #region IWatsonService interface - /// - public string GetServiceID() - { - return SERVICE_ID; } - /// - public void GetServiceStatus(ServiceStatus callback) + if (trainingDataBytes == null) + Log.Error("SpeechToText", "Failed to upload {0}!", trainingPath); + } + + return AddCustomCorpus(callback, customizationID, corpusName, allowOverwrite, trainingDataBytes); + } + + /// + /// Overload method for AddCustomCorpus that takes byteArray training data. + /// + /// The callback. + /// The customization ID with the corpus to be deleted. + /// The corpus name to be deleted. + /// Allow overwriting of corpus data. + /// ByteArray data for training data. + /// Optional customization data. + public bool AddCustomCorpus(OnAddCustomCorpusCallback callback, string customizationID, string corpusName, bool allowOverwrite, byte[] trainingData, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required for AddCustomCorpus."); + if (string.IsNullOrEmpty(corpusName)) + throw new ArgumentNullException("A corpusName is requried for AddCustomCorpus."); + if (trainingData == default(byte[])) + throw new ArgumentNullException("Training data is required for AddCustomCorpus."); + + AddCustomCorpusRequest req = new AddCustomCorpusRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.CorpusName = corpusName; + req.Data = customData; + req.Headers["Content-Type"] = "application/x-www-form-urlencoded"; + req.Headers["Accept"] = "application/json"; + req.Parameters["allow_overwrite"] = allowOverwrite.ToString(); + req.Forms = new Dictionary(); + req.Forms["body"] = new RESTConnector.Form(trainingData, "trainingData.txt", "text/plain"); + req.OnResponse = OnAddCustomCorpusResp; + + string service = "/v1/customizations/{0}/corpora/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, corpusName)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class AddCustomCorpusRequest : RESTConnector.Request + { + public OnAddCustomCorpusCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string CorpusName { get; set; } + public bool AllowOverwrite { get; set; } + public byte[] TrainingData { get; set; } + public string Data { get; set; } + } + + private void OnAddCustomCorpusResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((AddCustomCorpusRequest)req).Callback != null) + ((AddCustomCorpusRequest)req).Callback(resp.Success, ((AddCustomCorpusRequest)req).Data); + } + #endregion + + #region Get Custom Words + /// + /// This callback is used by the GetCustomWords() function. + /// + /// The custom words + /// Optional custom data. + public delegate void GetCustomWordsCallback(WordsList wordList, string data); + + /// + /// Lists information about all custom words from a custom language model. You can list all words from the custom model's words resource, only custom words that were added or modified by the user, or only OOV words that were extracted from corpora. Only the owner of a custom model can use this method to query the words from the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. + /// Optional custom data. + /// + public bool GetCustomWords(GetCustomWordsCallback callback, string customizationID, string wordType = WordType.ALL, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("customizationID"); + + GetCustomWordsReq req = new GetCustomWordsReq(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.WordType = wordType; + req.Data = customData; + req.Parameters["word_type"] = wordType.ToString(); + req.OnResponse = OnGetCustomWordsResp; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format("/v1/customizations/{0}/words", customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomWordsReq : RESTConnector.Request + { + public GetCustomWordsCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string WordType { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomWordsResp(RESTConnector.Request req, RESTConnector.Response resp) + { + WordsList wordsList = new WordsList(); + if (resp.Success) + { + try { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = wordsList; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } + catch (Exception e) + { + Log.Error("Speech To Text", "OnGetCustomWordsResp Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetCustomWordsReq)req).Callback != null) + ((GetCustomWordsReq)req).Callback(resp.Success ? wordsList : null, ((GetCustomWordsReq)req).Data); + } + #endregion + + #region Add Custom Words + /// + /// This callback is used by the AddCustomWords() function. + /// + /// The success of the call. + /// Optional custom data. + public delegate void AddCustomWordsCallback(bool success, string data); + /// + /// Adds one or more custom words to a custom language model.The service populates the words resource for a custom model with out-of-vocabulary(OOV) words found in each corpus added to the model.You can use this method to add additional words or to modify existing words in the words resource.Only the owner of a custom model can use this method to add or modify custom words associated with the model.Adding or modifying custom words does not affect the custom model until you train the model for the new data by using the POST /v1/customizations/{customization_id}/train method. + /// You add custom words by providing a Words object, which is an array of Word objects, one per word.You must use the object's word parameter to identify the word that is to be added. You can also provide one or both of the optional sounds_like and display_as fields for each word. + /// The sounds_like field provides an array of one or more pronunciations for the word. Use the parameter to specify how the word can be pronounced by users.Use the parameter for words that are difficult to pronounce, foreign words, acronyms, and so on.For example, you might specify that the word IEEE can sound like i triple e.You can specify a maximum of five sounds-like pronunciations for a word, and each pronunciation must adhere to the following rules: + /// Use English alphabetic characters: a-z and A-Z. + /// To pronounce a single letter, use the letter followed by a period, for example, N.C.A.A. for the word NCAA. + /// Use real or made-up words that are pronounceable in the native language, for example, shuchensnie for the word Sczcesny. + /// Substitute equivalent English letters for non-English letters, for example, s for ç or ny for ñ. + /// Substitute non-accented letters for accented letters, for example a for à or e for è. + /// Use the spelling of numbers, for example, seventy-five for 75. + /// You can include multiple words separated by spaces, but the service enforces a maximum of 40 total characters not including spaces. + /// The display_as field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in corpora training data.For example, you might indicate that the word IBM(trademark) is to be displayed as IBM™. + /// If you add a custom word that already exists in the words resource for the custom model, the new definition overrides the existing data for the word.If the service encounters an error with the input data, it returns a failure code and does not add any of the words to the words resource. + /// The call returns an HTTP 201 response code if the input data is valid.It then asynchronously pre-processes the words to add them to the model's words resource. The time that it takes for the analysis to complete depends on the number of new words that you add but is generally faster than adding a corpus or training a model. + /// You can use the GET /v1/customizations/{ customization_id}/words or GET /v1/customizations/{customization_id}/words/{word_name} method to review the words that you add.Words with an invalid sounds_like field include an error field that describes the problem.You can use other words methods to correct errors, eliminate typos, and modify how words are pronounced as needed. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The requested custom language model's identifier. + /// A boolean used to differentiate overloads with identical input types.. + /// A path to a json file to train. + /// Optional custom data. + /// + public bool AddCustomWords(AddCustomWordsCallback callback, string customizationID, bool useDataPath, string wordsJsonPath, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to add words to a custom language model."); + if (string.IsNullOrEmpty(wordsJsonPath)) + throw new ArgumentNullException("A wordsJsonPath is required to add words to a custom language model."); + + string wordsJson = File.ReadAllText(wordsJsonPath); - private class CheckServiceStatus + return AddCustomWords(callback, customizationID, wordsJson); + } + + public bool AddCustomWords(AddCustomWordsCallback callback, string customizationID, Words words, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to add words to a custom language model."); + if (words == null || words.words == null || words.words.Length == 0) + throw new WatsonException("Custom words are required to add words to a custom language model."); + + fsData data; + sm_Serializer.TrySerialize(words.GetType(), words, out data).AssertSuccessWithoutWarnings(); + string wordsJson = fsJsonPrinter.CompressedJson(data); + + return AddCustomWords(callback, customizationID, wordsJson, customData); + } + + public bool AddCustomWords(AddCustomWordsCallback callback, string customizationID, string wordsJson, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to add words to a custom language model."); + if (string.IsNullOrEmpty(wordsJson)) + throw new ArgumentNullException("A wordsJsonPath is required to add words to a custom language model."); + + AddCustomWordsRequest req = new AddCustomWordsRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.WordsJson = wordsJson; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes(wordsJson); + req.OnResponse = OnAddCustomWordsResp; + + string service = "/v1/customizations/{0}/words"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class AddCustomWordsRequest : RESTConnector.Request + { + public AddCustomWordsCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string WordsJson { get; set; } + public string Data { get; set; } + } + + private void OnAddCustomWordsResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((AddCustomWordsRequest)req).Callback != null) + ((AddCustomWordsRequest)req).Callback(resp.Success, ((AddCustomWordsRequest)req).Data); + } + #endregion + + #region Delete Custom Word + /// + /// This callback is used by the DeleteCustomWord() function. + /// + /// + /// + public delegate void OnDeleteCustomWordCallback(bool success, string data); + /// + /// Deletes a custom word from a custom language model. You can remove any word that you added to the custom model's words resource via any means. However, if the word also exists in the service's base vocabulary, the service removes only the custom pronunciation for the word; the word remains in the base vocabulary. + /// Removing a custom word does not affect the custom model until you train the model with the POST /v1/customizations/{customization_id}/train method.Only the owner of a custom model can use this method to delete a word from the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The customization ID to be deleted. + /// Optional customization data. + /// + public bool DeleteCustomWord(OnDeleteCustomWordCallback callback, string customizationID, string word, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required for DeleteCustomWord"); + if (string.IsNullOrEmpty(word)) + throw new ArgumentNullException("A word to delete is requried for DeleteCustomWord"); + + DeleteCustomWordRequest req = new DeleteCustomWordRequest(); req.Callback = callback; + req.CustomizationID = customizationID; + req.Word = word; + req.Data = customData; + req.Delete = true; + req.OnResponse = OnDeleteCustomWordResp; + + string service = "/v1/customizations/{0}/words/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class DeleteCustomWordRequest : RESTConnector.Request + { + public OnDeleteCustomWordCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Word { get; set; } + public string Data { get; set; } + } + + private void OnDeleteCustomWordResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteCustomWordRequest)req).Callback != null) + ((DeleteCustomWordRequest)req).Callback(resp.Success, ((DeleteCustomWordRequest)req).Data); + } + #endregion + + #region Get Custom Word + /// + /// This callback is used by the GetCustomWord() function. + /// + /// The word + /// Optional custom data. + public delegate void GetCustomWordCallback(WordData word, string data); + + /// + /// Lists information about a custom word from a custom language model. Only the owner of a custom model can use this method to query a word from the model. + /// Note: This method is currently a beta release that is available for US English only. + /// + /// The callback. + /// The language for which custom models are to be returned. Currently, only en-US (the default) is supported. + /// Optional custom data. + /// + public bool GetCustomWord(GetCustomWordCallback callback, string customizationID, string word, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required to GetCustomWord"); + if (string.IsNullOrEmpty(word)) + throw new ArgumentNullException("A word is required to GetCustomWord"); + + GetCustomWordReq req = new GetCustomWordReq(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Word = word; + req.Data = customData; + req.OnResponse = OnGetCustomWordResp; + + string service = "/v1/customizations/{0}/words/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomWordReq : RESTConnector.Request + { + public GetCustomWordCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Word { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomWordResp(RESTConnector.Request req, RESTConnector.Response resp) + { + WordData word = new WordData(); + if (resp.Success) + { + try { - private SpeechToText m_Service = null; - private ServiceStatus m_Callback = null; + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = word; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Speech To Text", "OnGetCustomWordResp Exception: {0}", e.ToString()); + resp.Success = false; + } + } - public CheckServiceStatus(SpeechToText service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; + if (((GetCustomWordReq)req).Callback != null) + ((GetCustomWordReq)req).Callback(resp.Success ? word : null, ((GetCustomWordReq)req).Data); + } + #endregion - if (!m_Service.GetModels(OnCheckService)) - m_Callback(SERVICE_ID, false); - } + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - private void OnCheckService(Model[] models) - { - if (m_Callback != null && m_Callback.Target != null) - m_Callback(SERVICE_ID, models != null); - } - }; - #endregion + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); } + + private class CheckServiceStatus + { + private SpeechToText m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(SpeechToText service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.GetModels(OnCheckService)) + m_Callback(SERVICE_ID, false); + } + + private void OnCheckService(Model[] models) + { + if (m_Callback != null && m_Callback.Target != null) + m_Callback(SERVICE_ID, models != null); + } + }; + #endregion + } } diff --git a/Scripts/Services/TextToSpeech/DataModels.cs b/Scripts/Services/TextToSpeech/DataModels.cs index 83becc2a0..ed90c9238 100755 --- a/Scripts/Services/TextToSpeech/DataModels.cs +++ b/Scripts/Services/TextToSpeech/DataModels.cs @@ -19,379 +19,379 @@ namespace IBM.Watson.DeveloperCloud.Services.TextToSpeech.v1 { + /// + /// Audio format types that can be requested from the service. + /// + public enum AudioFormatType + { /// - /// Audio format types that can be requested from the service. + /// OGG Vorbis format /// - public enum AudioFormatType - { - /// - /// OGG Vorbis format - /// - OGG = 0, - /// - /// Linear PCM format. - /// - WAV, //Currently used - /// - /// FLAC audio format. - /// - FLAC - }; + OGG = 0, + /// + /// Linear PCM format. + /// + WAV, //Currently used + /// + /// FLAC audio format. + /// + FLAC + }; - #region Voices - /// - /// The available voices for synthesized speech. - /// - public enum VoiceType - { - /// - /// US male voice. - /// - en_US_Michael = 0, - /// - /// US female voice. - /// - en_US_Lisa, - /// - /// US female voice. - /// - en_US_Allison, - /// - /// Great Britan female voice. - /// - en_GB_Kate, - /// - /// Spanish male voice. - /// - es_ES_Enrique, - /// - /// Spanish female voice. - /// - es_ES_Laura, - /// - /// US female voice. - /// - es_US_Sofia, - /// - /// German male voice. - /// - de_DE_Dieter, - /// - /// German female voice. - /// - de_DE_Birgit, - /// - /// French female voice. - /// - fr_FR_Renee, - /// - /// Italian female voice. - /// - it_IT_Francesca, - /// - /// Japanese female voice. - /// - ja_JP_Emi, - /// - /// Brazilian Portugese female voice. - /// - pt_BR_Isabela, - }; - - /// - /// A voice model object for TextToSpeech. - /// - [fsObject] - public class Voice - { - /// - /// The name of the voice model. - /// - public string name { get; set; } - /// - /// The language ID of this voice model. - /// - public string language { get; set; } - /// - /// The gender of the voice model. - /// - public string gender { get; set; } - /// - /// The URL of the voice model. - /// - public string url { get; set; } - /// - /// Textual description of the voice. - /// - public string description { get; set; } - /// - /// If true, the voice can be customized; if false, the voice cannot be customized. - /// - public bool customizable { get; set; } - }; + #region Voices + /// + /// The available voices for synthesized speech. + /// + public enum VoiceType + { + /// + /// US male voice. + /// + en_US_Michael = 0, + /// + /// US female voice. + /// + en_US_Lisa, + /// + /// US female voice. + /// + en_US_Allison, + /// + /// Great Britan female voice. + /// + en_GB_Kate, + /// + /// Spanish male voice. + /// + es_ES_Enrique, + /// + /// Spanish female voice. + /// + es_ES_Laura, + /// + /// US female voice. + /// + es_US_Sofia, + /// + /// German male voice. + /// + de_DE_Dieter, + /// + /// German female voice. + /// + de_DE_Birgit, + /// + /// French female voice. + /// + fr_FR_Renee, + /// + /// Italian female voice. + /// + it_IT_Francesca, + /// + /// Japanese female voice. + /// + ja_JP_Emi, + /// + /// Brazilian Portugese female voice. + /// + pt_BR_Isabela, + }; + /// + /// A voice model object for TextToSpeech. + /// + [fsObject] + public class Voice + { + /// + /// The name of the voice model. + /// + public string name { get; set; } + /// + /// The language ID of this voice model. + /// + public string language { get; set; } + /// + /// The gender of the voice model. + /// + public string gender { get; set; } /// - /// This object contains a list of voices. + /// The URL of the voice model. /// - [fsObject] - public class Voices + public string url { get; set; } + /// + /// Textual description of the voice. + /// + public string description { get; set; } + /// + /// If true, the voice can be customized; if false, the voice cannot be customized. + /// + public bool customizable { get; set; } + }; + + /// + /// This object contains a list of voices. + /// + [fsObject] + public class Voices + { + /// + /// The array of Voice objects. + /// + public Voice[] voices { get; set; } + + /// + /// Check to see if object has data. + /// + /// True if has voices, False if no voices. + public bool HasData() { - /// - /// The array of Voice objects. - /// - public Voice[] voices { get; set; } + return voices != null && voices.Length > 0; + } + }; + #endregion - /// - /// Check to see if object has data. - /// - /// True if has voices, False if no voices. - public bool HasData() - { - return voices != null && voices.Length > 0; - } - }; - #endregion + #region Pronunciation + /// + /// This object contains the pronunciation. + /// + [fsObject] + public class Pronunciation + { + /// + /// The pronunciation. + /// + public string pronunciation { get; set; } + } + #endregion - #region Pronunciation - /// - /// This object contains the pronunciation. - /// - [fsObject] - public class Pronunciation - { - /// - /// The pronunciation. - /// - public string pronunciation { get; set; } - } - #endregion + #region Customization + /// + /// Customizations for voice models. + /// + [fsObject] + public class Customizations + { + /// + /// A list of voice model customizations. + /// + public Customization[] customizations { get; set; } - #region Customization - /// - /// Customizations for voice models. - /// - [fsObject] - public class Customizations - { - /// - /// A list of voice model customizations. - /// - public Customization[] customizations { get; set; } + public bool HasData() + { + return customizations != null && customizations.Length > 0; + } + } - public bool HasData() - { - return customizations != null && customizations.Length > 0; - } - } + /// + /// A single voice model customization. + /// + [fsObject] + public class Customization + { + /// + /// GUID of the custom voice model + /// + public string customization_id { get; set; } + /// + /// Name of the custom voice model + /// + public string name { get; set; } + /// + /// Language of the custom voice model. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. + /// + public string language { get; set; } + /// + /// GUID of the service credentials for the owner of the custom voice model. + /// + public string owner { get; set; } + /// + /// UNIX timestamp that indicates when the custom voice model was created. The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970 Coordinated Universal Time (UTC). + /// + public double created { get; set; } + /// + /// UNIX timestamp that indicates when the custom voice model was last modified. Equals `created` when a new voice model is first added but has yet to be changed. + /// + public double last_modified { get; set; } + /// + /// Description of the custom voice model. + /// + public string description { get; set; } - /// - /// A single voice model customization. - /// - [fsObject] - public class Customization - { - /// - /// GUID of the custom voice model - /// - public string customization_id { get; set; } - /// - /// Name of the custom voice model - /// - public string name { get; set; } - /// - /// Language of the custom voice model. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. - /// - public string language { get; set; } - /// - /// GUID of the service credentials for the owner of the custom voice model. - /// - public string owner { get; set; } - /// - /// UNIX timestamp that indicates when the custom voice model was created. The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970 Coordinated Universal Time (UTC). - /// - public double created { get; set; } - /// - /// UNIX timestamp that indicates when the custom voice model was last modified. Equals `created` when a new voice model is first added but has yet to be changed. - /// - public double last_modified { get; set; } - /// - /// Description of the custom voice model. - /// - public string description { get; set; } + public bool HasData() + { + return !string.IsNullOrEmpty(customization_id); + } + } - public bool HasData() - { - return !string.IsNullOrEmpty(customization_id); - } - } + /// + /// A data object containing a customization ID when creating a new voice model. + /// + [fsObject] + public class CustomizationID + { + /// + /// GUID of the new custom voice model. + /// + public string customization_id { get; set; } + } - /// - /// A data object containing a customization ID when creating a new voice model. - /// - [fsObject] - public class CustomizationID - { - /// - /// GUID of the new custom voice model. - /// - public string customization_id { get; set; } - } + /// + /// A data object that contains data to create a new empty custom voice mode3l. + /// + [fsObject] + public class CustomVoice + { + /// + /// Name of the new custom voice model. + /// + public string name { get; set; } + /// + /// Language of the new custom voice model. Omit the parameter to use the default language, en-US. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. + /// + public string language { get; set; } + /// + /// Description of the new custom voice model. + /// + public string description { get; set; } + } - /// - /// A data object that contains data to create a new empty custom voice mode3l. - /// - [fsObject] - public class CustomVoice - { - /// - /// Name of the new custom voice model. - /// - public string name { get; set; } - /// - /// Language of the new custom voice model. Omit the parameter to use the default language, en-US. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. - /// - public string language { get; set; } - /// - /// Description of the new custom voice model. - /// - public string description { get; set; } - } + [fsObject] + public class CustomizationWords + { + /// + /// GUID of the custom voice model. + /// + public string customization_id { get; set; } + /// + /// Name of the custom voice model + /// + public string name { get; set; } + /// + /// Language of the custom voice model. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. + /// + public string language { get; set; } + /// + /// GUID of the service credentials for the owner of the custom voice model. + /// + public string owner { get; set; } + /// + /// UNIX timestamp that indicates when the custom voice model was created. The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970 Coordinated Universal Time (UTC). + /// + public double created { get; set; } + /// + /// UNIX timestamp that indicates when the custom voice model was last modified. Equals created when the new voice model is first added but has yet to be changed. + /// + public double last_modified { get; set; } + /// + /// Description of the custom voice model. + /// + public string description { get; set; } + /// + /// List of words and their translations from the custom voice model. + /// + public Word[] words { get; set; } + } - [fsObject] - public class CustomizationWords - { - /// - /// GUID of the custom voice model. - /// - public string customization_id { get; set; } - /// - /// Name of the custom voice model - /// - public string name { get; set; } - /// - /// Language of the custom voice model. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. - /// - public string language { get; set; } - /// - /// GUID of the service credentials for the owner of the custom voice model. - /// - public string owner { get; set; } - /// - /// UNIX timestamp that indicates when the custom voice model was created. The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970 Coordinated Universal Time (UTC). - /// - public double created { get; set; } - /// - /// UNIX timestamp that indicates when the custom voice model was last modified. Equals created when the new voice model is first added but has yet to be changed. - /// - public double last_modified { get; set; } - /// - /// Description of the custom voice model. - /// - public string description { get; set; } - /// - /// List of words and their translations from the custom voice model. - /// - public Word[] words { get; set; } - } + /// + /// Words object. + /// + [fsObject] + public class Words + { + /// + /// An array of Words. + /// + public Word[] words { get; set; } - /// - /// Words object. - /// - [fsObject] - public class Words - { - /// - /// An array of Words. - /// - public Word[] words { get; set; } + /// + /// Check to see if there are any words. + /// + /// True if there are words, false if there ar no words. + public bool HasData() + { + return words != null && words.Length > 0; + } + } - /// - /// Check to see if there are any words. - /// - /// True if there are words, false if there ar no words. - public bool HasData() - { - return words != null && words.Length > 0; - } - } - - /// - /// The Word object. - /// - [fsObject] - public class Word - { - /// - /// Word from the custom voice model. - /// - public string word { get; set; } - /// - /// Phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. - /// - public string translation { get; set; } - } + /// + /// The Word object. + /// + [fsObject] + public class Word + { + /// + /// Word from the custom voice model. + /// + public string word { get; set; } + /// + /// Phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. + /// + public string translation { get; set; } + } - /// - /// Update information for a custom voice model. - /// - [fsObject] - public class CustomVoiceUpdate - { - /// - /// Name of the new custom voice model. - /// - public string name { get; set; } - /// - /// Description of the new custom voice model. - /// - public string description { get; set; } - /// - /// List of words and their translations to be added to or updated in the custom voice model. Send an empty array to make no additions or updates. - /// - public Word[] words { get; set; } + /// + /// Update information for a custom voice model. + /// + [fsObject] + public class CustomVoiceUpdate + { + /// + /// Name of the new custom voice model. + /// + public string name { get; set; } + /// + /// Description of the new custom voice model. + /// + public string description { get; set; } + /// + /// List of words and their translations to be added to or updated in the custom voice model. Send an empty array to make no additions or updates. + /// + public Word[] words { get; set; } - /// - /// Check to see if there are any words to update. - /// - /// True if there are words, false if there are none. - public bool HasData() - { - return words != null && words.Length > 0; - } - } + /// + /// Check to see if there are any words to update. + /// + /// True if there are words, false if there are none. + public bool HasData() + { + return words != null && words.Length > 0; + } + } - /// - /// Single word translation for a custom voice model. - /// - [fsObject] - public class Translation - { - /// - /// Phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. A sounds-like is one or more words that, when combined, sound like the word. - /// - public string translation { get; set; } - } - #endregion + /// + /// Single word translation for a custom voice model. + /// + [fsObject] + public class Translation + { + /// + /// Phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. A sounds-like is one or more words that, when combined, sound like the word. + /// + public string translation { get; set; } + } + #endregion - #region Errors - /// - /// The error response. - /// - [fsObject] - public class ErrorModel - { - /// - /// Description of the problem. - /// - public string error { get; set; } - /// - /// HTTP response code. - /// - public int code { get; set; } - /// - /// The response message. - /// - public string code_description { get; set; } - } - #endregion + #region Errors + /// + /// The error response. + /// + [fsObject] + public class ErrorModel + { + /// + /// Description of the problem. + /// + public string error { get; set; } + /// + /// HTTP response code. + /// + public int code { get; set; } + /// + /// The response message. + /// + public string code_description { get; set; } + } + #endregion } diff --git a/Scripts/Services/TextToSpeech/TextToSpeech.cs b/Scripts/Services/TextToSpeech/TextToSpeech.cs index 72548baf2..96c0ba0c0 100755 --- a/Scripts/Services/TextToSpeech/TextToSpeech.cs +++ b/Scripts/Services/TextToSpeech/TextToSpeech.cs @@ -27,17 +27,17 @@ namespace IBM.Watson.DeveloperCloud.Services.TextToSpeech.v1 { - /// - /// This class wraps the Text to Speech service. - /// Text to Speech Service - /// - public class TextToSpeech : IWatsonService - { - #region Private Data - private DataCache m_SpeechCache = null; - private VoiceType m_Voice = VoiceType.en_US_Michael; - private AudioFormatType m_AudioFormat = AudioFormatType.WAV; - private Dictionary m_VoiceTypes = new Dictionary() + /// + /// This class wraps the Text to Speech service. + /// Text to Speech Service + /// + public class TextToSpeech : IWatsonService + { + #region Private Data + private DataCache m_SpeechCache = null; + private VoiceType m_Voice = VoiceType.en_US_Michael; + private AudioFormatType m_AudioFormat = AudioFormatType.WAV; + private Dictionary m_VoiceTypes = new Dictionary() { { VoiceType.en_US_Michael, "en-US_MichaelVoice" }, { VoiceType.en_US_Lisa, "en-US_LisaVoice" }, @@ -51,1107 +51,1107 @@ public class TextToSpeech : IWatsonService { VoiceType.fr_FR_Renee, "fr-FR_ReneeVoice" }, { VoiceType.it_IT_Francesca, "it-IT_FrancescaVoice" }, { VoiceType.ja_JP_Emi, "ja-JP_EmiVoice" }, - { VoiceType.pt_BR_Isabela, "pt-BR_IsabelaVoice"}, + { VoiceType.pt_BR_Isabela, "pt-BR_IsabelaVoice"}, }; - private Dictionary m_AudioFormats = new Dictionary() + private Dictionary m_AudioFormats = new Dictionary() { { AudioFormatType.OGG, "audio/ogg;codecs=opus" }, { AudioFormatType.WAV, "audio/wav" }, { AudioFormatType.FLAC, "audio/flac" }, }; - private const string SERVICE_ID = "TextToSpeechV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - private const float REQUEST_TIMEOUT = 10.0f * 60.0f; - #endregion - - #region Public Properties - /// - /// Disable the local cache. - /// - public bool DisableCache { get; set; } - /// - /// This property allows the user to set the AudioFormat to use. Currently, only WAV is supported. - /// - public AudioFormatType AudioFormat { get { return m_AudioFormat; } set { m_AudioFormat = value; } } - /// - /// This property allows the user to specify the voice to use. - /// - public VoiceType Voice + private const string SERVICE_ID = "TextToSpeechV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + private const float REQUEST_TIMEOUT = 10.0f * 60.0f; + #endregion + + #region Public Properties + /// + /// Disable the local cache. + /// + public bool DisableCache { get; set; } + /// + /// This property allows the user to set the AudioFormat to use. Currently, only WAV is supported. + /// + public AudioFormatType AudioFormat { get { return m_AudioFormat; } set { m_AudioFormat = value; } } + /// + /// This property allows the user to specify the voice to use. + /// + public VoiceType Voice + { + get { return m_Voice; } + set + { + if (m_Voice != value) { - get { return m_Voice; } - set - { - if (m_Voice != value) - { - m_Voice = value; - m_SpeechCache = null; - } - } + m_Voice = value; + m_SpeechCache = null; } - #endregion - - #region GetVoiceType - private string GetVoiceType(VoiceType voiceType) - { - if (m_VoiceTypes.ContainsKey(voiceType)) - { - string voiceName = ""; - m_VoiceTypes.TryGetValue(voiceType, out voiceName); - return voiceName; - } - else - { - Log.Warning("TextToSpeech", "There is no voicetype for {0}!", voiceType); - return null; - } - } - #endregion - - #region GetVoices - /// - /// This callback is used by the GetVoices() function. - /// - /// The Voices object. - public delegate void GetVoicesCallback(Voices voices); - /// - /// Returns all available voices that can be used. - /// - /// The callback to invoke with the list of available voices. - /// Returns ture if the request was submitted. - public bool GetVoices(GetVoicesCallback callback) - { - if (callback == null) - throw new ArgumentNullException("callback"); + } + } + #endregion + + #region GetVoiceType + private string GetVoiceType(VoiceType voiceType) + { + if (m_VoiceTypes.ContainsKey(voiceType)) + { + string voiceName = ""; + m_VoiceTypes.TryGetValue(voiceType, out voiceName); + return voiceName; + } + else + { + Log.Warning("TextToSpeech", "There is no voicetype for {0}!", voiceType); + return null; + } + } + #endregion + + #region GetVoices + /// + /// This callback is used by the GetVoices() function. + /// + /// The Voices object. + public delegate void GetVoicesCallback(Voices voices); + /// + /// Returns all available voices that can be used. + /// + /// The callback to invoke with the list of available voices. + /// Returns ture if the request was submitted. + public bool GetVoices(GetVoicesCallback callback) + { + if (callback == null) + throw new ArgumentNullException("callback"); - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/voices"); - if (connector == null) - return false; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/voices"); + if (connector == null) + return false; - GetVoicesReq req = new GetVoicesReq(); - req.Callback = callback; - req.OnResponse = OnGetVoicesResp; + GetVoicesReq req = new GetVoicesReq(); + req.Callback = callback; + req.OnResponse = OnGetVoicesResp; - return connector.Send(req); + return connector.Send(req); + } + private class GetVoicesReq : RESTConnector.Request + { + public GetVoicesCallback Callback { get; set; } + }; + private void OnGetVoicesResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Voices voices = new Voices(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = voices; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - private class GetVoicesReq : RESTConnector.Request + catch (Exception e) { - public GetVoicesCallback Callback { get; set; } - }; - private void OnGetVoicesResp(RESTConnector.Request req, RESTConnector.Response resp) + Log.Error("Natural Language Classifier", "GetVoices Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetVoicesReq)req).Callback != null) + ((GetVoicesReq)req).Callback(resp.Success ? voices : null); + } + #endregion + + #region GetVoice + /// + /// This callback is used by the GetVoice() function. + /// + /// The Voice object. + public delegate void GetVoiceCallback(Voice voice); + /// + /// Return specific voice. + /// + /// The callback to invoke with the voice. + /// The name of the voice you would like to get. If this is null, TextToSpeech will default to the set voice. + /// Returns ture if the request was submitted. + public bool GetVoice(GetVoiceCallback callback, VoiceType? voice = null) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (voice == null) + voice = m_Voice; + + string service = "/v1/voices/{0}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, GetVoiceType((VoiceType)voice))); + if (connector == null) + return false; + + GetVoiceReq req = new GetVoiceReq(); + req.Callback = callback; + req.OnResponse = OnGetVoiceResp; + + return connector.Send(req); + } + private class GetVoiceReq : RESTConnector.Request + { + public GetVoiceCallback Callback { get; set; } + }; + private void OnGetVoiceResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Voice voice = new Voice(); + if (resp.Success) + { + try { - Voices voices = new Voices(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = voices; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Natural Language Classifier", "GetVoices Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetVoicesReq)req).Callback != null) - ((GetVoicesReq)req).Callback(resp.Success ? voices : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = voice; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetVoice - /// - /// This callback is used by the GetVoice() function. - /// - /// The Voice object. - public delegate void GetVoiceCallback(Voice voice); - /// - /// Return specific voice. - /// - /// The callback to invoke with the voice. - /// The name of the voice you would like to get. If this is null, TextToSpeech will default to the set voice. - /// Returns ture if the request was submitted. - public bool GetVoice(GetVoiceCallback callback, VoiceType? voice = null) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (voice == null) - voice = m_Voice; - - string service = "/v1/voices/{0}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, GetVoiceType((VoiceType)voice))); - if (connector == null) - return false; - - GetVoiceReq req = new GetVoiceReq(); - req.Callback = callback; - req.OnResponse = OnGetVoiceResp; - - return connector.Send(req); - } - private class GetVoiceReq : RESTConnector.Request - { - public GetVoiceCallback Callback { get; set; } - }; - private void OnGetVoiceResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Voice voice = new Voice(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = voice; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("TextToSpeech", "GetVoice Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetVoiceReq)req).Callback != null) - ((GetVoiceReq)req).Callback(resp.Success ? voice : null); - } - #endregion - - #region Synthesize Functions - /// - /// This callback is passed into the ToSpeech() method. - /// - /// The AudioClip containing the audio to play. - public delegate void ToSpeechCallback(AudioClip clip); - /// - /// Private Request object that holds data specific to the ToSpeech request. - /// - private class ToSpeechRequest : RESTConnector.Request + catch (Exception e) { - public string TextId { get; set; } - public string Text { get; set; } - public ToSpeechCallback Callback { get; set; } + Log.Error("TextToSpeech", "GetVoice Exception: {0}", e.ToString()); + resp.Success = false; } + } + + if (((GetVoiceReq)req).Callback != null) + ((GetVoiceReq)req).Callback(resp.Success ? voice : null); + } + #endregion + + #region Synthesize Functions + /// + /// This callback is passed into the ToSpeech() method. + /// + /// The AudioClip containing the audio to play. + public delegate void ToSpeechCallback(AudioClip clip); + /// + /// Private Request object that holds data specific to the ToSpeech request. + /// + private class ToSpeechRequest : RESTConnector.Request + { + public string TextId { get; set; } + public string Text { get; set; } + public ToSpeechCallback Callback { get; set; } + } - /// - /// Converts the given text into an AudioClip that can be played. - /// - /// The text to synthesis into speech. - /// The callback to invoke with the AudioClip. - /// If true, then we use post instead of get, this allows for text that exceeds the 5k limit. - /// Returns true if the request is sent. - public bool ToSpeech(string text, ToSpeechCallback callback, bool usePost = false) + /// + /// Converts the given text into an AudioClip that can be played. + /// + /// The text to synthesis into speech. + /// The callback to invoke with the AudioClip. + /// If true, then we use post instead of get, this allows for text that exceeds the 5k limit. + /// Returns true if the request is sent. + public bool ToSpeech(string text, ToSpeechCallback callback, bool usePost = false) + { + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (callback == null) + throw new ArgumentNullException("callback"); + + if (!m_AudioFormats.ContainsKey(m_AudioFormat)) + { + Log.Error("TextToSpeech", "Unsupported audio format: {0}", m_AudioFormat.ToString()); + return false; + } + if (!m_VoiceTypes.ContainsKey(m_Voice)) + { + Log.Error("TextToSpeech", "Unsupported voice: {0}", m_Voice.ToString()); + return false; + } + + string textId = Utility.GetMD5(text); + if (!DisableCache) + { + if (m_SpeechCache == null) + m_SpeechCache = new DataCache("TextToSpeech_" + m_VoiceTypes[m_Voice]); + + byte[] data = m_SpeechCache.Find(textId); + if (data != null) { - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (callback == null) - throw new ArgumentNullException("callback"); - - if (!m_AudioFormats.ContainsKey(m_AudioFormat)) - { - Log.Error("TextToSpeech", "Unsupported audio format: {0}", m_AudioFormat.ToString()); - return false; - } - if (!m_VoiceTypes.ContainsKey(m_Voice)) - { - Log.Error("TextToSpeech", "Unsupported voice: {0}", m_Voice.ToString()); - return false; - } - - string textId = Utility.GetMD5(text); - if (!DisableCache) - { - if (m_SpeechCache == null) - m_SpeechCache = new DataCache("TextToSpeech_" + m_VoiceTypes[m_Voice]); - - byte[] data = m_SpeechCache.Find(textId); - if (data != null) - { - AudioClip clip = ProcessResponse(textId, data); - callback(clip); - return true; - } - } - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/synthesize"); - if (connector == null) - { - Log.Error("TextToSpeech", "Failed to get connector."); - return false; - } - - ToSpeechRequest req = new ToSpeechRequest(); - req.TextId = textId; - req.Text = text; - req.Callback = callback; - req.Parameters["accept"] = m_AudioFormats[m_AudioFormat]; - req.Parameters["voice"] = m_VoiceTypes[m_Voice]; - req.OnResponse = ToSpeechResponse; - - if (usePost) - { - Dictionary upload = new Dictionary(); - upload["text"] = text; - - req.Send = Encoding.UTF8.GetBytes(Json.Serialize(upload)); - req.Headers["Content-Type"] = "application/json"; - } - else - { - req.Parameters["text"] = text; - } - - return connector.Send(req); + AudioClip clip = ProcessResponse(textId, data); + callback(clip); + return true; } + } + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/synthesize"); + if (connector == null) + { + Log.Error("TextToSpeech", "Failed to get connector."); + return false; + } + + ToSpeechRequest req = new ToSpeechRequest(); + req.TextId = textId; + req.Text = text; + req.Callback = callback; + req.Parameters["accept"] = m_AudioFormats[m_AudioFormat]; + req.Parameters["voice"] = m_VoiceTypes[m_Voice]; + req.OnResponse = ToSpeechResponse; + + if (usePost) + { + Dictionary upload = new Dictionary(); + upload["text"] = text; + + req.Send = Encoding.UTF8.GetBytes(Json.Serialize(upload)); + req.Headers["Content-Type"] = "application/json"; + } + else + { + req.Parameters["text"] = text; + } + + return connector.Send(req); + } - private void ToSpeechResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void ToSpeechResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + ToSpeechRequest speechReq = req as ToSpeechRequest; + if (speechReq == null) + throw new WatsonException("Wrong type of request object."); + + //Log.Debug( "TextToSpeech", "Request completed in {0} seconds.", resp.ElapsedTime ); + + AudioClip clip = resp.Success ? ProcessResponse(speechReq.TextId, resp.Data) : null; + if (clip == null) + Log.Error("TextToSpeech", "Request Failed: {0}", resp.Error); + if (m_SpeechCache != null && clip != null) + m_SpeechCache.Save(speechReq.TextId, resp.Data); + + if (speechReq.Callback != null) + speechReq.Callback(clip); + } + + private AudioClip ProcessResponse(string textId, byte[] data) + { + switch (m_AudioFormat) + { + case AudioFormatType.WAV: + return WaveFile.ParseWAV(textId, data); + default: + break; + } + + Log.Error("TextToSpeech", "Unsupported audio format: {0}", m_AudioFormat.ToString()); + return null; + } + #endregion + + #region GetPronunciation + /// + /// This callback is used by the GetPronunciation() function. + /// + /// The pronunciation strting. + public delegate void GetPronunciationCallback(Pronunciation pronunciation); + /// + /// Returns the phonetic pronunciation for the word specified by the text parameter. You can request + /// the pronunciation for a specific format. You can also request the pronunciation for a specific + /// voice to see the default translation for the language of that voice or for a specific custom voice + /// model to see the translation for that voice model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The GetPronunciationCallback + /// The text string to pronounce. + /// Specify a voice to obtain the pronunciation for the specified word in the language of that voice. All voices for the same language (for example, en-US) return the same translation. Do not specify both a voice and a customization_id. Retrieve available voices with the GET /v1/voices method. If this is null, TextToSpeech will default to the set voice. + /// Specify the phoneme set in which to return the pronunciation. Omit the parameter to obtain the pronunciation in the default format. Either ipa or spr. + /// GUID of a custom voice model for which the pronunciation is to be returned. You must make the request with the service credentials of the model's owner. If the word is not defined in the specified voice model, the service returns the default translation for the model's language. Omit the parameter to see the translation for the specified voice with no customization. Do not specify both a voice and a customization_id. + /// + public bool GetPronunciation(GetPronunciationCallback callback, string text, VoiceType? voice = null, string format = "ipa", string customization_id = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(text)) + throw new ArgumentNullException("text"); + if (voice == null) + voice = m_Voice; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/pronunciation"); + if (connector == null) + return false; + + GetPronunciationReq req = new GetPronunciationReq(); + req.Callback = callback; + req.Text = text; + req.Voice = (VoiceType)voice; + req.Format = format; + req.Customization_ID = customization_id; + req.Parameters["text"] = text; + req.Parameters["voice"] = GetVoiceType((VoiceType)voice); + req.Parameters["format"] = format; + if (!string.IsNullOrEmpty(customization_id)) + req.Parameters["customization_id"] = customization_id; + req.OnResponse = OnGetPronunciationResp; + + return connector.Send(req); + } + + private class GetPronunciationReq : RESTConnector.Request + { + public GetPronunciationCallback Callback { get; set; } + public string Text { get; set; } + public VoiceType Voice { get; set; } + public string Format { get; set; } + public string Customization_ID { get; set; } + } + + private void OnGetPronunciationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Pronunciation pronunciation = new Pronunciation(); + if (resp.Success) + { + try { - ToSpeechRequest speechReq = req as ToSpeechRequest; - if (speechReq == null) - throw new WatsonException("Wrong type of request object."); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = pronunciation; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Text To Speech", "GetPronunciation Exception: {0}", e.ToString()); + resp.Success = false; + } + } - //Log.Debug( "TextToSpeech", "Request completed in {0} seconds.", resp.ElapsedTime ); + if (((GetPronunciationReq)req).Callback != null) + ((GetPronunciationReq)req).Callback(resp.Success ? pronunciation : null); + } + #endregion + + #region Get Customizations + /// + /// This callback is used by the GetCustomizations() function. + /// + /// The customizations + /// Optional custom data. + public delegate void GetCustomizationsCallback(Customizations customizations, string data); + + /// + /// Lists metadata such as the name and description for the custom voice models that you own. Use the language query parameter to list the voice models that you own for the specified language only. Omit the parameter to see all voice models that you own for all languages. To see the words in addition to the metadata for a specific voice model, use the GET /v1/customizations/{customization_id} method. Only the owner of a custom voice model can use this method to list information about the model. + /// Note: This method is currently a beta release that supports US English only + /// + /// The callback. + /// Optional custom data. + /// + public bool GetCustomizations(GetCustomizationsCallback callback, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); - AudioClip clip = resp.Success ? ProcessResponse(speechReq.TextId, resp.Data) : null; - if (clip == null) - Log.Error("TextToSpeech", "Request Failed: {0}", resp.Error); - if (m_SpeechCache != null && clip != null) - m_SpeechCache.Save(speechReq.TextId, resp.Data); + GetCustomizationsReq req = new GetCustomizationsReq(); + req.Callback = callback; + req.Data = customData; + req.OnResponse = OnGetCustomizationsResp; - if (speechReq.Callback != null) - speechReq.Callback(clip); + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomizationsReq : RESTConnector.Request + { + public GetCustomizationsCallback Callback { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomizationsResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Customizations customizations = new Customizations(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = customizations; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Text To Speech", "GetCustomizations Exception: {0}", e.ToString()); + resp.Success = false; } + } + + if (((GetCustomizationsReq)req).Callback != null) + ((GetCustomizationsReq)req).Callback(resp.Success ? customizations : null, ((GetCustomizationsReq)req).Data); + } + #endregion + + #region Create Customization + /// + /// Thid callback is used by the CreateCustomization() function. + /// + /// The customizationID. + /// Optional custom data. + public delegate void CreateCustomizationCallback(CustomizationID customizationID, string data); + + /// + /// Creates a new empty custom voice model that is owned by the requesting user. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// Name of the new custom voice model. + /// Language of the new custom voice model. Omit the parameter to use the default language, en-US. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. + /// Description of the new custom voice model. + /// Optional custom data. + /// + public bool CreateCustomization(CreateCustomizationCallback callback, string name, string language = default(string), string description = default(string), string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(name)) + throw new ArgumentNullException("A name is required to create a custom voice model."); + + CustomVoice customVoice = new CustomVoice(); + customVoice.name = name; + customVoice.language = language; + customVoice.description = description; + + fsData data; + sm_Serializer.TrySerialize(customVoice.GetType(), customVoice, out data).AssertSuccessWithoutWarnings(); + string customizationJson = fsJsonPrinter.CompressedJson(data); + + CreateCustomizationRequest req = new CreateCustomizationRequest(); + req.Callback = callback; + req.CustomVoice = customVoice; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes(customizationJson); + req.OnResponse = OnCreateCustomizationResp; + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); + if (connector == null) + return false; + + return connector.Send(req); + } - private AudioClip ProcessResponse(string textId, byte[] data) + private class CreateCustomizationRequest : RESTConnector.Request + { + public CreateCustomizationCallback Callback { get; set; } + public CustomVoice CustomVoice { get; set; } + public string Data { get; set; } + } + + private void OnCreateCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + CustomizationID customizationID = new CustomizationID(); + if (resp.Success) + { + try { - switch (m_AudioFormat) - { - case AudioFormatType.WAV: - return WaveFile.ParseWAV(textId, data); - default: - break; - } - - Log.Error("TextToSpeech", "Unsupported audio format: {0}", m_AudioFormat.ToString()); - return null; + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = customizationID; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - #endregion - - #region GetPronunciation - /// - /// This callback is used by the GetPronunciation() function. - /// - /// The pronunciation strting. - public delegate void GetPronunciationCallback(Pronunciation pronunciation); - /// - /// Returns the phonetic pronunciation for the word specified by the text parameter. You can request - /// the pronunciation for a specific format. You can also request the pronunciation for a specific - /// voice to see the default translation for the language of that voice or for a specific custom voice - /// model to see the translation for that voice model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The GetPronunciationCallback - /// The text string to pronounce. - /// Specify a voice to obtain the pronunciation for the specified word in the language of that voice. All voices for the same language (for example, en-US) return the same translation. Do not specify both a voice and a customization_id. Retrieve available voices with the GET /v1/voices method. If this is null, TextToSpeech will default to the set voice. - /// Specify the phoneme set in which to return the pronunciation. Omit the parameter to obtain the pronunciation in the default format. Either ipa or spr. - /// GUID of a custom voice model for which the pronunciation is to be returned. You must make the request with the service credentials of the model's owner. If the word is not defined in the specified voice model, the service returns the default translation for the model's language. Omit the parameter to see the translation for the specified voice with no customization. Do not specify both a voice and a customization_id. - /// - public bool GetPronunciation(GetPronunciationCallback callback, string text, VoiceType? voice = null, string format = "ipa", string customization_id = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(text)) - throw new ArgumentNullException("text"); - if (voice == null) - voice = m_Voice; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/pronunciation"); - if (connector == null) - return false; - - GetPronunciationReq req = new GetPronunciationReq(); - req.Callback = callback; - req.Text = text; - req.Voice = (VoiceType)voice; - req.Format = format; - req.Customization_ID = customization_id; - req.Parameters["text"] = text; - req.Parameters["voice"] = GetVoiceType((VoiceType)voice); - req.Parameters["format"] = format; - if(!string.IsNullOrEmpty(customization_id)) - req.Parameters["customization_id"] = customization_id; - req.OnResponse = OnGetPronunciationResp; - - return connector.Send(req); - } - - private class GetPronunciationReq:RESTConnector.Request - { - public GetPronunciationCallback Callback { get; set; } - public string Text { get; set; } - public VoiceType Voice { get; set; } - public string Format { get; set; } - public string Customization_ID { get; set; } - } - - private void OnGetPronunciationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Pronunciation pronunciation = new Pronunciation(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = pronunciation; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Text To Speech", "GetPronunciation Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetPronunciationReq)req).Callback != null) - ((GetPronunciationReq)req).Callback(resp.Success ? pronunciation : null); - } - #endregion - - #region Get Customizations - /// - /// This callback is used by the GetCustomizations() function. - /// - /// The customizations - /// Optional custom data. - public delegate void GetCustomizationsCallback(Customizations customizations, string data); - - /// - /// Lists metadata such as the name and description for the custom voice models that you own. Use the language query parameter to list the voice models that you own for the specified language only. Omit the parameter to see all voice models that you own for all languages. To see the words in addition to the metadata for a specific voice model, use the GET /v1/customizations/{customization_id} method. Only the owner of a custom voice model can use this method to list information about the model. - /// Note: This method is currently a beta release that supports US English only - /// - /// The callback. - /// Optional custom data. - /// - public bool GetCustomizations(GetCustomizationsCallback callback, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - - GetCustomizationsReq req = new GetCustomizationsReq(); - req.Callback = callback; - req.Data = customData; - req.OnResponse = OnGetCustomizationsResp; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomizationsReq : RESTConnector.Request - { - public GetCustomizationsCallback Callback { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomizationsResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Customizations customizations = new Customizations(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = customizations; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Text To Speech", "GetCustomizations Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomizationsReq)req).Callback != null) - ((GetCustomizationsReq)req).Callback(resp.Success ? customizations : null, ((GetCustomizationsReq)req).Data); - } - #endregion - - #region Create Customization - /// - /// Thid callback is used by the CreateCustomization() function. - /// - /// The customizationID. - /// Optional custom data. - public delegate void CreateCustomizationCallback(CustomizationID customizationID, string data); - - /// - /// Creates a new empty custom voice model that is owned by the requesting user. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// Name of the new custom voice model. - /// Language of the new custom voice model. Omit the parameter to use the default language, en-US. = ['de-DE', 'en-US', 'en-GB', 'es-ES', 'es-US', 'fr-FR', 'it-IT', 'ja-JP', 'pt-BR']. - /// Description of the new custom voice model. - /// Optional custom data. - /// - public bool CreateCustomization(CreateCustomizationCallback callback, string name, string language = default(string), string description = default(string), string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(name)) - throw new ArgumentNullException("A name is required to create a custom voice model."); - - CustomVoice customVoice = new CustomVoice(); - customVoice.name = name; - customVoice.language = language; - customVoice.description = description; - - fsData data; - sm_Serializer.TrySerialize(customVoice.GetType(), customVoice, out data).AssertSuccessWithoutWarnings(); - string customizationJson = fsJsonPrinter.CompressedJson(data); - - CreateCustomizationRequest req = new CreateCustomizationRequest(); - req.Callback = callback; - req.CustomVoice = customVoice; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(customizationJson); - req.OnResponse = OnCreateCustomizationResp; - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v1/customizations"); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class CreateCustomizationRequest : RESTConnector.Request - { - public CreateCustomizationCallback Callback { get; set; } - public CustomVoice CustomVoice { get; set; } - public string Data { get; set; } - } - - private void OnCreateCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - CustomizationID customizationID = new CustomizationID(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = customizationID; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Text To Speech", "CreateCustomization Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((CreateCustomizationRequest)req).Callback != null) - ((CreateCustomizationRequest)req).Callback(resp.Success ? customizationID : null, ((CreateCustomizationRequest)req).Data); - } - #endregion - - #region Delete Customization - /// - /// This callback is used by the DeleteCustomization() function. - /// - /// - /// - public delegate void OnDeleteCustomizationCallback(bool success, string data); - /// - /// Deletes the custom voice model with the specified `customization_id`. Only the owner of a custom voice model can use this method to delete the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The voice model to be deleted's identifier. - /// Optional custom data. - /// - public bool DeleteCustomization(OnDeleteCustomizationCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to delete is required for DeleteCustomization"); - - DeleteCustomizationRequest req = new DeleteCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - req.Delete = true; - req.OnResponse = OnDeleteCustomizationResp; - - string service = "/v1/customizations/{0}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class DeleteCustomizationRequest : RESTConnector.Request - { - public OnDeleteCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnDeleteCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteCustomizationRequest)req).Callback != null) - ((DeleteCustomizationRequest)req).Callback(resp.Success, ((DeleteCustomizationRequest)req).Data); - } - #endregion - - #region Get Customization - /// - /// This callback is used by the GetCusomization() function. - /// - /// - /// - public delegate void GetCustomizationCallback(Customization customization, string data); - /// - /// Lists all information about the custom voice model with the specified `customization_id`. In addition to metadata such as the name and description of the voice model, the output includes the words in the model and their translations as defined in the model. To see just the metadata for a voice model, use the GET `/v1/customizations` method. Only the owner of a custom voice model can use this method to query information about the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The requested custom voice model's identifier. - /// Optional custom data. - /// - public bool GetCustomization(GetCustomizationCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID to get a custom voice model."); - - GetCustomizationRequest req = new GetCustomizationRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.OnResponse = OnGetCustomizationResp; - - string service = "/v1/customizations/{0}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomizationRequest : RESTConnector.Request - { - public GetCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Customization customization = new Customization(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = customization; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Text To Speech", "GetCustomization Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomizationRequest)req).Callback != null) - ((GetCustomizationRequest)req).Callback(resp.Success ? customization : null, ((GetCustomizationRequest)req).Data); - } - #endregion - - #region Update Customization - /// - /// This callback is used by the UpdateCustomization() function. - /// - /// Success - /// Optional custom data. - public delegate void UpdateCustomizationCallback(bool success, string data); - - /// - /// Updates information for the custom voice model with the specified `customization_id`. You can update the metadata such as the name and description of the voice model. You can also update the words in the model and their translations. A custom model can contain no more than 20,000 entries. Only the owner of a custom voice model can use this method to update the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The identifier of the custom voice model to be updated. - /// Custom voice model update data. - /// Optional custom data. - /// - public bool UpdateCustomization(UpdateCustomizationCallback callback, string customizationID, CustomVoiceUpdate customVoiceUpdate, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("customizationID"); - if (!customVoiceUpdate.HasData()) - throw new ArgumentNullException("Custom voice update data is required to update a custom voice model."); - - fsData data; - sm_Serializer.TrySerialize(customVoiceUpdate.GetType(), customVoiceUpdate, out data).AssertSuccessWithoutWarnings(); - string customizationJson = fsJsonPrinter.CompressedJson(data); - - UpdateCustomizationRequest req = new UpdateCustomizationRequest(); - req.Callback = callback; - req.CustomVoiceUpdate = customVoiceUpdate; - req.CustomizationID = customizationID; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(customizationJson); - req.OnResponse = OnUpdateCustomizationResp; - - string service = "/v1/customizations/{0}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - // TODO add UpdateCustomization overload using path to json file. - - private class UpdateCustomizationRequest : RESTConnector.Request - { - public UpdateCustomizationCallback Callback { get; set; } - public string CustomizationID { get; set; } - public CustomVoiceUpdate CustomVoiceUpdate { get; set; } - public string Data { get; set; } - } - - private void OnUpdateCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((UpdateCustomizationRequest)req).Callback != null) - ((UpdateCustomizationRequest)req).Callback(resp.Success, ((UpdateCustomizationRequest)req).Data); - } - #endregion - - #region Get Customization Words - /// - /// This callback is used by the GetCusomizationWords() function. - /// - /// - /// - public delegate void GetCustomizationWordsCallback(Words words, string data); - /// - /// Lists all of the words and their translations for the custom voice model with the specified `customization_id`. The output shows the translations as they are defined in the model. Only the owner of a custom voice model can use this method to query information about the model's words. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The requested custom voice model's identifier. - /// Optional custom data. - /// - public bool GetCustomizationWords(GetCustomizationWordsCallback callback, string customizationID, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required to get a custom voice model's words."); - - GetCustomizationWordsRequest req = new GetCustomizationWordsRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Data = customData; - req.OnResponse = OnGetCustomizationWordsResp; - - string service = "/v1/customizations/{0}/words"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomizationWordsRequest : RESTConnector.Request - { - public GetCustomizationWordsCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomizationWordsResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Words words = new Words(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = words; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Text To Speech", "GetCustomizationWords Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomizationWordsRequest)req).Callback != null) - ((GetCustomizationWordsRequest)req).Callback(resp.Success ? words : null, ((GetCustomizationWordsRequest)req).Data); - } - #endregion - - #region Add Customization Words - /// - /// This callback is used by the AddCustomizationWords() function. - /// - /// Success - /// Optional custom data. - public delegate void AddCustomizationWordsCallback(bool success, string data); - - /// - /// Adds one or more words and their translations to the custom voice model with the specified `customization_id`. A custom model can contain no more than 20,000 entries. Only the owner of a custom voice model can use this method to add words to the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The identifier of the custom voice model to be updated. - /// Words object to add to custom voice model. - /// Optional custom data. - /// - public bool AddCustomizationWords(AddCustomizationWordsCallback callback, string customizationID, Words words, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("customizationID"); - if (!words.HasData()) - throw new ArgumentNullException("Words data is required to add words to a custom voice model."); - - fsData data; - sm_Serializer.TrySerialize(words.GetType(), words, out data).AssertSuccessWithoutWarnings(); - string customizationJson = fsJsonPrinter.CompressedJson(data); - - AddCustomizationWordsRequest req = new AddCustomizationWordsRequest(); - req.Callback = callback; - req.Words = words; - req.CustomizationID = customizationID; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(customizationJson); - req.OnResponse = OnAddCustomizationWordsResp; - - string service = "/v1/customizations/{0}/words"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); - if (connector == null) - return false; - - return connector.Send(req); - } - - // TODO add AddCustomizationWords overload using path to json file. - - private class AddCustomizationWordsRequest : RESTConnector.Request - { - public AddCustomizationWordsCallback Callback { get; set; } - public string CustomizationID { get; set; } - public Words Words { get; set; } - public string Data { get; set; } - } - - private void OnAddCustomizationWordsResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((AddCustomizationWordsRequest)req).Callback != null) - ((AddCustomizationWordsRequest)req).Callback(resp.Success, ((AddCustomizationWordsRequest)req).Data); - } - #endregion - - #region Delete Customization Word - /// - /// This callback is used by the DeleteCustomizationWord() function. - /// - /// - /// - public delegate void OnDeleteCustomizationWordCallback(bool success, string data); - /// - /// Deletes a single word from the custom voice model with the specified customization_id. Only the owner of a custom voice model can use this method to delete a word from the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The voice model's identifier. - /// The word to be deleted. - /// Optional custom data. - /// - public bool DeleteCustomizationWord(OnDeleteCustomizationWordCallback callback, string customizationID, string word, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required for DeleteCustomizationWord"); - if (string.IsNullOrEmpty(word)) - throw new ArgumentNullException("A word to delete is required for DeleteCustomizationWord"); - - DeleteCustomizationWordRequest req = new DeleteCustomizationWordRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Word = word; - req.Data = customData; - req.Timeout = REQUEST_TIMEOUT; - req.Delete = true; - req.OnResponse = OnDeleteCustomizationWordResp; - - string service = "/v1/customizations/{0}/words/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class DeleteCustomizationWordRequest : RESTConnector.Request - { - public OnDeleteCustomizationWordCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Word { get; set; } - public string Data { get; set; } - } - - private void OnDeleteCustomizationWordResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((DeleteCustomizationWordRequest)req).Callback != null) - ((DeleteCustomizationWordRequest)req).Callback(resp.Success, ((DeleteCustomizationWordRequest)req).Data); - } - #endregion - - #region Get Customization Word - /// - /// This callback is used by the GetCusomizationWord() function. - /// - /// Translation of the requested word. - /// optional custom data. - public delegate void GetCustomizationWordCallback(Translation translation, string data); - /// - /// Returns the translation for a single word from the custom model with the specified `customization_id`. The output shows the translation as it is defined in the model. Only the owner of a custom voice model can use this method to query information about a word from the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The requested custom voice model's identifier. - /// The requested word. - /// Optional custom data. - /// - public bool GetCustomizationWord(GetCustomizationWordCallback callback, string customizationID, string word, string customData = default(string)) - { - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("A customizationID is required to get a custom voice model's words."); - if (string.IsNullOrEmpty(word)) - throw new ArgumentNullException("A word is requrred to get a translation."); - - GetCustomizationWordRequest req = new GetCustomizationWordRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Word = word; - req.Data = customData; - req.OnResponse = OnGetCustomizationWordResp; - - string service = "/v1/customizations/{0}/words/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class GetCustomizationWordRequest : RESTConnector.Request - { - public GetCustomizationWordCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Word { get; set; } - public string Data { get; set; } - } - - private void OnGetCustomizationWordResp(RESTConnector.Request req, RESTConnector.Response resp) - { - Translation translation = new Translation(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = translation; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("Text To Speech", "GetCustomizationWord Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetCustomizationWordRequest)req).Callback != null) - ((GetCustomizationWordRequest)req).Callback(resp.Success ? translation : null, ((GetCustomizationWordRequest)req).Data); - } - #endregion - - #region Add Customization Word - /// - /// This callback is used by the AddCustomizationWord() function. - /// - /// Success - /// Optional custom data. - public delegate void AddCustomizationWordCallback(bool success, string data); - - /// - /// Adds a single word and its translation to the custom voice model with the specified `customization_id`. A custom model can contain no more than 20,000 entries. Only the owner of a custom voice model can use this method to add a word to the model. - /// Note: This method is currently a beta release that supports US English only. - /// - /// The callback. - /// The identifier of the custom voice model to be updated. - /// Words object to add to custom voice model. - /// Optional custom data. - /// - public bool AddCustomizationWord(AddCustomizationWordCallback callback, string customizationID, string word, string translation, string customData = default(string)) - { - Log.Error("TextToSpeech", "AddCustomizationWord is not supported. Unity WWW does not support PUT method! Use AddCustomizationWords() instead!"); - if (callback == null) - throw new ArgumentNullException("callback"); - if (string.IsNullOrEmpty(customizationID)) - throw new ArgumentNullException("customizationID"); - if (string.IsNullOrEmpty(word)) - throw new ArgumentNullException("word"); - if (string.IsNullOrEmpty(translation)) - throw new ArgumentNullException("translation"); - - string json = "{\n\t\"translation\":\"" + translation + "\"\n}"; - - AddCustomizationWordRequest req = new AddCustomizationWordRequest(); - req.Callback = callback; - req.CustomizationID = customizationID; - req.Word = word; - req.Translation = translation; - req.Data = customData; - req.Headers["Content-Type"] = "application/json"; - req.Headers["Accept"] = "application/json"; - req.Headers["X-HTTP-Method-Override"] = "PUT"; - req.Send = Encoding.UTF8.GetBytes(json); - req.OnResponse = OnAddCustomizationWordResp; - - string service = "/v1/customizations/{0}/words/{1}"; - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); - if (connector == null) - return false; - - return connector.Send(req); - } - - private class AddCustomizationWordRequest : RESTConnector.Request - { - public AddCustomizationWordCallback Callback { get; set; } - public string CustomizationID { get; set; } - public string Word { get; set; } - public string Translation { get; set; } - public string Data { get; set; } - } - - private void OnAddCustomizationWordResp(RESTConnector.Request req, RESTConnector.Response resp) - { - if (((AddCustomizationWordRequest)req).Callback != null) - ((AddCustomizationWordRequest)req).Callback(resp.Success, ((AddCustomizationWordRequest)req).Data); - } - #endregion - - #region IWatsonService interface - /// - public string GetServiceID() + catch (Exception e) { - return SERVICE_ID; + Log.Error("Text To Speech", "CreateCustomization Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - public void GetServiceStatus(ServiceStatus callback) + if (((CreateCustomizationRequest)req).Callback != null) + ((CreateCustomizationRequest)req).Callback(resp.Success ? customizationID : null, ((CreateCustomizationRequest)req).Data); + } + #endregion + + #region Delete Customization + /// + /// This callback is used by the DeleteCustomization() function. + /// + /// + /// + public delegate void OnDeleteCustomizationCallback(bool success, string data); + /// + /// Deletes the custom voice model with the specified `customization_id`. Only the owner of a custom voice model can use this method to delete the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The voice model to be deleted's identifier. + /// Optional custom data. + /// + public bool DeleteCustomization(OnDeleteCustomizationCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to delete is required for DeleteCustomization"); + + DeleteCustomizationRequest req = new DeleteCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + req.Delete = true; + req.OnResponse = OnDeleteCustomizationResp; + + string service = "/v1/customizations/{0}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class DeleteCustomizationRequest : RESTConnector.Request + { + public OnDeleteCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } + + private void OnDeleteCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteCustomizationRequest)req).Callback != null) + ((DeleteCustomizationRequest)req).Callback(resp.Success, ((DeleteCustomizationRequest)req).Data); + } + #endregion + + #region Get Customization + /// + /// This callback is used by the GetCusomization() function. + /// + /// + /// + public delegate void GetCustomizationCallback(Customization customization, string data); + /// + /// Lists all information about the custom voice model with the specified `customization_id`. In addition to metadata such as the name and description of the voice model, the output includes the words in the model and their translations as defined in the model. To see just the metadata for a voice model, use the GET `/v1/customizations` method. Only the owner of a custom voice model can use this method to query information about the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The requested custom voice model's identifier. + /// Optional custom data. + /// + public bool GetCustomization(GetCustomizationCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID to get a custom voice model."); + + GetCustomizationRequest req = new GetCustomizationRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.OnResponse = OnGetCustomizationResp; + + string service = "/v1/customizations/{0}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomizationRequest : RESTConnector.Request + { + public GetCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Customization customization = new Customization(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = customization; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) { - if (Config.Instance.FindCredentials(SERVICE_ID) != null) - new CheckServiceStatus(this, callback); - else - callback(SERVICE_ID, false); + Log.Error("Text To Speech", "GetCustomization Exception: {0}", e.ToString()); + resp.Success = false; } + } + + if (((GetCustomizationRequest)req).Callback != null) + ((GetCustomizationRequest)req).Callback(resp.Success ? customization : null, ((GetCustomizationRequest)req).Data); + } + #endregion + + #region Update Customization + /// + /// This callback is used by the UpdateCustomization() function. + /// + /// Success + /// Optional custom data. + public delegate void UpdateCustomizationCallback(bool success, string data); + + /// + /// Updates information for the custom voice model with the specified `customization_id`. You can update the metadata such as the name and description of the voice model. You can also update the words in the model and their translations. A custom model can contain no more than 20,000 entries. Only the owner of a custom voice model can use this method to update the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The identifier of the custom voice model to be updated. + /// Custom voice model update data. + /// Optional custom data. + /// + public bool UpdateCustomization(UpdateCustomizationCallback callback, string customizationID, CustomVoiceUpdate customVoiceUpdate, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("customizationID"); + if (!customVoiceUpdate.HasData()) + throw new ArgumentNullException("Custom voice update data is required to update a custom voice model."); + + fsData data; + sm_Serializer.TrySerialize(customVoiceUpdate.GetType(), customVoiceUpdate, out data).AssertSuccessWithoutWarnings(); + string customizationJson = fsJsonPrinter.CompressedJson(data); + + UpdateCustomizationRequest req = new UpdateCustomizationRequest(); + req.Callback = callback; + req.CustomVoiceUpdate = customVoiceUpdate; + req.CustomizationID = customizationID; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes(customizationJson); + req.OnResponse = OnUpdateCustomizationResp; + + string service = "/v1/customizations/{0}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + // TODO add UpdateCustomization overload using path to json file. + + private class UpdateCustomizationRequest : RESTConnector.Request + { + public UpdateCustomizationCallback Callback { get; set; } + public string CustomizationID { get; set; } + public CustomVoiceUpdate CustomVoiceUpdate { get; set; } + public string Data { get; set; } + } + + private void OnUpdateCustomizationResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((UpdateCustomizationRequest)req).Callback != null) + ((UpdateCustomizationRequest)req).Callback(resp.Success, ((UpdateCustomizationRequest)req).Data); + } + #endregion + + #region Get Customization Words + /// + /// This callback is used by the GetCusomizationWords() function. + /// + /// + /// + public delegate void GetCustomizationWordsCallback(Words words, string data); + /// + /// Lists all of the words and their translations for the custom voice model with the specified `customization_id`. The output shows the translations as they are defined in the model. Only the owner of a custom voice model can use this method to query information about the model's words. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The requested custom voice model's identifier. + /// Optional custom data. + /// + public bool GetCustomizationWords(GetCustomizationWordsCallback callback, string customizationID, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required to get a custom voice model's words."); + + GetCustomizationWordsRequest req = new GetCustomizationWordsRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Data = customData; + req.OnResponse = OnGetCustomizationWordsResp; + + string service = "/v1/customizations/{0}/words"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomizationWordsRequest : RESTConnector.Request + { + public GetCustomizationWordsCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Data { get; set; } + } - private class CheckServiceStatus + private void OnGetCustomizationWordsResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Words words = new Words(); + if (resp.Success) + { + try { - private TextToSpeech m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus(TextToSpeech service, ServiceStatus callback) - { - m_Service = service; - m_Callback = callback; - - if (!m_Service.GetVoices(OnCheckService)) - m_Callback(SERVICE_ID, false); - } - - private void OnCheckService(Voices voices) - { - if (m_Callback != null && m_Callback.Target != null) - m_Callback(SERVICE_ID, voices != null); - } - }; - #endregion + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = words; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Text To Speech", "GetCustomizationWords Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetCustomizationWordsRequest)req).Callback != null) + ((GetCustomizationWordsRequest)req).Callback(resp.Success ? words : null, ((GetCustomizationWordsRequest)req).Data); + } + #endregion + + #region Add Customization Words + /// + /// This callback is used by the AddCustomizationWords() function. + /// + /// Success + /// Optional custom data. + public delegate void AddCustomizationWordsCallback(bool success, string data); + + /// + /// Adds one or more words and their translations to the custom voice model with the specified `customization_id`. A custom model can contain no more than 20,000 entries. Only the owner of a custom voice model can use this method to add words to the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The identifier of the custom voice model to be updated. + /// Words object to add to custom voice model. + /// Optional custom data. + /// + public bool AddCustomizationWords(AddCustomizationWordsCallback callback, string customizationID, Words words, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("customizationID"); + if (!words.HasData()) + throw new ArgumentNullException("Words data is required to add words to a custom voice model."); + + fsData data; + sm_Serializer.TrySerialize(words.GetType(), words, out data).AssertSuccessWithoutWarnings(); + string customizationJson = fsJsonPrinter.CompressedJson(data); + + AddCustomizationWordsRequest req = new AddCustomizationWordsRequest(); + req.Callback = callback; + req.Words = words; + req.CustomizationID = customizationID; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Send = Encoding.UTF8.GetBytes(customizationJson); + req.OnResponse = OnAddCustomizationWordsResp; + + string service = "/v1/customizations/{0}/words"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID)); + if (connector == null) + return false; + + return connector.Send(req); + } + + // TODO add AddCustomizationWords overload using path to json file. + + private class AddCustomizationWordsRequest : RESTConnector.Request + { + public AddCustomizationWordsCallback Callback { get; set; } + public string CustomizationID { get; set; } + public Words Words { get; set; } + public string Data { get; set; } + } + + private void OnAddCustomizationWordsResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((AddCustomizationWordsRequest)req).Callback != null) + ((AddCustomizationWordsRequest)req).Callback(resp.Success, ((AddCustomizationWordsRequest)req).Data); + } + #endregion + + #region Delete Customization Word + /// + /// This callback is used by the DeleteCustomizationWord() function. + /// + /// + /// + public delegate void OnDeleteCustomizationWordCallback(bool success, string data); + /// + /// Deletes a single word from the custom voice model with the specified customization_id. Only the owner of a custom voice model can use this method to delete a word from the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The voice model's identifier. + /// The word to be deleted. + /// Optional custom data. + /// + public bool DeleteCustomizationWord(OnDeleteCustomizationWordCallback callback, string customizationID, string word, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required for DeleteCustomizationWord"); + if (string.IsNullOrEmpty(word)) + throw new ArgumentNullException("A word to delete is required for DeleteCustomizationWord"); + + DeleteCustomizationWordRequest req = new DeleteCustomizationWordRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Word = word; + req.Data = customData; + req.Timeout = REQUEST_TIMEOUT; + req.Delete = true; + req.OnResponse = OnDeleteCustomizationWordResp; + + string service = "/v1/customizations/{0}/words/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class DeleteCustomizationWordRequest : RESTConnector.Request + { + public OnDeleteCustomizationWordCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Word { get; set; } + public string Data { get; set; } + } + + private void OnDeleteCustomizationWordResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((DeleteCustomizationWordRequest)req).Callback != null) + ((DeleteCustomizationWordRequest)req).Callback(resp.Success, ((DeleteCustomizationWordRequest)req).Data); + } + #endregion + + #region Get Customization Word + /// + /// This callback is used by the GetCusomizationWord() function. + /// + /// Translation of the requested word. + /// optional custom data. + public delegate void GetCustomizationWordCallback(Translation translation, string data); + /// + /// Returns the translation for a single word from the custom model with the specified `customization_id`. The output shows the translation as it is defined in the model. Only the owner of a custom voice model can use this method to query information about a word from the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The requested custom voice model's identifier. + /// The requested word. + /// Optional custom data. + /// + public bool GetCustomizationWord(GetCustomizationWordCallback callback, string customizationID, string word, string customData = default(string)) + { + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("A customizationID is required to get a custom voice model's words."); + if (string.IsNullOrEmpty(word)) + throw new ArgumentNullException("A word is requrred to get a translation."); + + GetCustomizationWordRequest req = new GetCustomizationWordRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Word = word; + req.Data = customData; + req.OnResponse = OnGetCustomizationWordResp; + + string service = "/v1/customizations/{0}/words/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); + if (connector == null) + return false; + + return connector.Send(req); + } + + private class GetCustomizationWordRequest : RESTConnector.Request + { + public GetCustomizationWordCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Word { get; set; } + public string Data { get; set; } + } + + private void OnGetCustomizationWordResp(RESTConnector.Request req, RESTConnector.Response resp) + { + Translation translation = new Translation(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = translation; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) + { + Log.Error("Text To Speech", "GetCustomizationWord Exception: {0}", e.ToString()); + resp.Success = false; + } + } + + if (((GetCustomizationWordRequest)req).Callback != null) + ((GetCustomizationWordRequest)req).Callback(resp.Success ? translation : null, ((GetCustomizationWordRequest)req).Data); + } + #endregion + + #region Add Customization Word + /// + /// This callback is used by the AddCustomizationWord() function. + /// + /// Success + /// Optional custom data. + public delegate void AddCustomizationWordCallback(bool success, string data); + + /// + /// Adds a single word and its translation to the custom voice model with the specified `customization_id`. A custom model can contain no more than 20,000 entries. Only the owner of a custom voice model can use this method to add a word to the model. + /// Note: This method is currently a beta release that supports US English only. + /// + /// The callback. + /// The identifier of the custom voice model to be updated. + /// Words object to add to custom voice model. + /// Optional custom data. + /// + public bool AddCustomizationWord(AddCustomizationWordCallback callback, string customizationID, string word, string translation, string customData = default(string)) + { + Log.Error("TextToSpeech", "AddCustomizationWord is not supported. Unity WWW does not support PUT method! Use AddCustomizationWords() instead!"); + if (callback == null) + throw new ArgumentNullException("callback"); + if (string.IsNullOrEmpty(customizationID)) + throw new ArgumentNullException("customizationID"); + if (string.IsNullOrEmpty(word)) + throw new ArgumentNullException("word"); + if (string.IsNullOrEmpty(translation)) + throw new ArgumentNullException("translation"); + + string json = "{\n\t\"translation\":\"" + translation + "\"\n}"; + + AddCustomizationWordRequest req = new AddCustomizationWordRequest(); + req.Callback = callback; + req.CustomizationID = customizationID; + req.Word = word; + req.Translation = translation; + req.Data = customData; + req.Headers["Content-Type"] = "application/json"; + req.Headers["Accept"] = "application/json"; + req.Headers["X-HTTP-Method-Override"] = "PUT"; + req.Send = Encoding.UTF8.GetBytes(json); + req.OnResponse = OnAddCustomizationWordResp; + + string service = "/v1/customizations/{0}/words/{1}"; + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, string.Format(service, customizationID, word)); + if (connector == null) + return false; + + return connector.Send(req); } + private class AddCustomizationWordRequest : RESTConnector.Request + { + public AddCustomizationWordCallback Callback { get; set; } + public string CustomizationID { get; set; } + public string Word { get; set; } + public string Translation { get; set; } + public string Data { get; set; } + } + + private void OnAddCustomizationWordResp(RESTConnector.Request req, RESTConnector.Response resp) + { + if (((AddCustomizationWordRequest)req).Callback != null) + ((AddCustomizationWordRequest)req).Callback(resp.Success, ((AddCustomizationWordRequest)req).Data); + } + #endregion + + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } + + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + private class CheckServiceStatus + { + private TextToSpeech m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(TextToSpeech service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.GetVoices(OnCheckService)) + m_Callback(SERVICE_ID, false); + } + + private void OnCheckService(Voices voices) + { + if (m_Callback != null && m_Callback.Target != null) + m_Callback(SERVICE_ID, voices != null); + } + }; + #endregion + } + } diff --git a/Scripts/Services/ToneAnalyzer/DataModels.cs b/Scripts/Services/ToneAnalyzer/DataModels.cs old mode 100644 new mode 100755 index 01c9e7337..07ab39731 --- a/Scripts/Services/ToneAnalyzer/DataModels.cs +++ b/Scripts/Services/ToneAnalyzer/DataModels.cs @@ -19,240 +19,242 @@ namespace IBM.Watson.DeveloperCloud.Services.ToneAnalyzer.v3 { + /// + /// Tone analyzer response. + /// + [fsObject] + public class ToneAnalyzerResponse + { /// - /// Tone analyzer response. + /// Gets or sets the document tone. /// - [fsObject] - public class ToneAnalyzerResponse - { - /// - /// Gets or sets the document tone. - /// - /// The document tone. - public DocumentTone document_tone { get; set;} - /// - /// Gets or sets the sentences tone. - /// - /// The sentences tone. - public SentenceTone[] sentences_tone { get; set;} + /// The document tone. + public DocumentTone document_tone { get; set; } + /// + /// Gets or sets the sentences tone. + /// + /// The sentences tone. + public SentenceTone[] sentences_tone { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - string sentenceTone = ( sentences_tone != null && sentences_tone.Length > 0 )? sentences_tone[0].ToString() : "No Sentence Tone"; - return string.Format("[ToneAnalyzerResponse: document_tone={0}, sentenceTone={1}]", document_tone, sentenceTone); - } + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + string sentenceTone = (sentences_tone != null && sentences_tone.Length > 0) ? sentences_tone[0].ToString() : "No Sentence Tone"; + return string.Format("[ToneAnalyzerResponse: document_tone={0}, sentenceTone={1}]", document_tone, sentenceTone); } + } + /// + /// Document tone. + /// + [fsObject] + public class DocumentTone + { /// - /// Document tone. + /// Gets or sets the tone categories. /// - [fsObject] - public class DocumentTone - { - /// - /// Gets or sets the tone categories. - /// - /// The tone categories. - public ToneCategory[] tone_categories { get; set;} + /// The tone categories. + public ToneCategory[] tone_categories { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - string toneCategoryString = ""; - for (int i = 0; tone_categories != null && i < tone_categories.Length; i++) - { - toneCategoryString += tone_categories[i].ToString(); - } + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + string toneCategoryString = ""; + for (int i = 0; tone_categories != null && i < tone_categories.Length; i++) + { + toneCategoryString += tone_categories[i].ToString(); + } - return string.Format("[DocumentTone: tone_categories={0}]", toneCategoryString); - } + return string.Format("[DocumentTone: tone_categories={0}]", toneCategoryString); } + } + /// + /// Tone category. + /// + [fsObject] + public class ToneCategory + { /// - /// Tone category. + /// Gets or sets the category identifier. /// - [fsObject] - public class ToneCategory - { - /// - /// Gets or sets the category identifier. - /// - /// The category identifier. - public string category_id { get; set;} - /// - /// Gets or sets the name of the category. - /// - /// The name of the category. - public string category_name { get; set;} - /// - /// Gets or sets the tones. - /// - /// The tones. - public Tone[] tones { get; set;} + /// The category identifier. + public string category_id { get; set; } + /// + /// Gets or sets the name of the category. + /// + /// The name of the category. + public string category_name { get; set; } + /// + /// Gets or sets the tones. + /// + /// The tones. + public Tone[] tones { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - string tonesString = ""; - for (int i = 0; tones != null && i < tones.Length; i++) - { - tonesString += tones[i].ToString(); - } + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + string tonesString = ""; + for (int i = 0; tones != null && i < tones.Length; i++) + { + tonesString += tones[i].ToString(); + } - return string.Format("[ToneCategory: category_id={0}, category_name={1}, tones={2}]", category_id, category_name, tonesString); - } + return string.Format("[ToneCategory: category_id={0}, category_name={1}, tones={2}]", category_id, category_name, tonesString); } + } + /// + /// Tone. + /// + [fsObject] + public class Tone + { /// - /// Tone. + /// Gets or sets the score. /// - [fsObject] - public class Tone - { - /// - /// Gets or sets the score. - /// - /// The score. - public double score { get; set;} - /// - /// Gets or sets the tone identifier. - /// - /// The tone identifier. - public string tone_id { get; set;} - /// - /// Gets or sets the name of the tone. - /// - /// The name of the tone. - public string tone_name { get; set;} + /// The score. + public double score { get; set; } + /// + /// Gets or sets the tone identifier. + /// + /// The tone identifier. + public string tone_id { get; set; } + /// + /// Gets or sets the name of the tone. + /// + /// The name of the tone. + public string tone_name { get; set; } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - return string.Format("[Tone: score={0}, tone_id={1}, tone_name={2}]", score, tone_id, tone_name); - } + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + return string.Format("[Tone: score={0}, tone_id={1}, tone_name={2}]", score, tone_id, tone_name); } + } + /// + /// Sentence tone. + /// + [fsObject] + public class SentenceTone + { /// - /// Sentence tone. + /// Gets or sets the sentence identifier. /// - [fsObject] - public class SentenceTone - { - /// - /// Gets or sets the sentence identifier. - /// - /// The sentence identifier. - public int sentence_id { get; set;} - /// - /// Gets or sets the input from. - /// - /// The input from. - public int input_from { get; set;} - /// - /// Gets or sets the input to. - /// - /// The input to. - public int input_to { get; set;} - /// - /// Gets or sets the text. - /// - /// The text. - public string text { get; set;} - /// - /// Gets or sets the tone categories. - /// - /// The tone categories. - public ToneCategory[] tone_categories { get; set;} + /// The sentence identifier. + public int sentence_id { get; set; } + /// + /// Gets or sets the input from. + /// + /// The input from. + public int input_from { get; set; } + /// + /// Gets or sets the input to. + /// + /// The input to. + public int input_to { get; set; } + /// + /// Gets or sets the text. + /// + /// The text. + public string text { get; set; } + /// + /// Gets or sets the tone categories. + /// + /// The tone categories. + public ToneCategory[] tone_categories { get; set; } - /// - /// Gets the highest score. - /// - /// The highest score. - private double m_HighestScore = -1; - /// - /// Returns the highest score. - /// - public double HighestScore + /// + /// Gets the highest score. + /// + /// The highest score. + private double m_HighestScore = -1; + /// + /// Returns the highest score. + /// + public double HighestScore + { + get + { + if (m_HighestScore < 0) { - get + for (int i = 0; tone_categories != null && i < tone_categories.Length; i++) + { + for (int j = 0; tone_categories[i].tones != null && j < tone_categories[i].tones.Length; j++) { - if(m_HighestScore < 0){ - for (int i = 0; tone_categories != null && i < tone_categories.Length; i++) - { - for (int j = 0; tone_categories[i].tones != null && j < tone_categories[i].tones.Length; j++) { - if (m_HighestScore < tone_categories[i].tones[j].score) - { - m_HighestScore = tone_categories[i].tones[j].score; - m_HighestScoreToneName = tone_categories[i].tones[j].tone_name; - m_HighestScoreToneCategoryName = tone_categories[i].category_name; - } - } - - } - } - return m_HighestScore; + if (m_HighestScore < tone_categories[i].tones[j].score) + { + m_HighestScore = tone_categories[i].tones[j].score; + m_HighestScoreToneName = tone_categories[i].tones[j].tone_name; + m_HighestScoreToneCategoryName = tone_categories[i].category_name; + } } - } - - /// - /// Gets the name of the highest score tone. - /// - /// The name of the highest score tone. - private string m_HighestScoreToneName = null; - /// - /// The highest score tone name. - /// - public string HighestScoreToneName - { - get - { - return m_HighestScoreToneName; - } - } - /// - /// Gets the name of the highest score tone category. - /// - /// The name of the highest score tone category. - private string m_HighestScoreToneCategoryName = null; - /// - /// The highest score category name. - /// - public string HighestScoreToneCategoryName - { - get - { - return m_HighestScoreToneCategoryName; - } + } } + return m_HighestScore; + } + } - /// - /// Returns a that represents the current . - /// - /// A that represents the current . - public override string ToString() - { - string toneCategoryString = ""; - for (int i = 0; tone_categories != null && i < tone_categories.Length; i++) - { - toneCategoryString += tone_categories[i].ToString(); - } + /// + /// Gets the name of the highest score tone. + /// + /// The name of the highest score tone. + private string m_HighestScoreToneName = null; + /// + /// The highest score tone name. + /// + public string HighestScoreToneName + { + get + { + return m_HighestScoreToneName; + } + } - return string.Format("[SentenceTone: sentence_id={0}, input_from={1}, input_to={2}, text={3}, tone_categories={4}]", sentence_id, input_from, input_to, text, toneCategoryString); - } + /// + /// Gets the name of the highest score tone category. + /// + /// The name of the highest score tone category. + private string m_HighestScoreToneCategoryName = null; + /// + /// The highest score category name. + /// + public string HighestScoreToneCategoryName + { + get + { + return m_HighestScoreToneCategoryName; + } + } + + /// + /// Returns a that represents the current . + /// + /// A that represents the current . + public override string ToString() + { + string toneCategoryString = ""; + for (int i = 0; tone_categories != null && i < tone_categories.Length; i++) + { + toneCategoryString += tone_categories[i].ToString(); + } + + return string.Format("[SentenceTone: sentence_id={0}, input_from={1}, input_to={2}, text={3}, tone_categories={4}]", sentence_id, input_from, input_to, text, toneCategoryString); } + } } diff --git a/Scripts/Services/ToneAnalyzer/ToneAnalyzer.cs b/Scripts/Services/ToneAnalyzer/ToneAnalyzer.cs old mode 100644 new mode 100755 index 2db0ffff2..2a644b3d6 --- a/Scripts/Services/ToneAnalyzer/ToneAnalyzer.cs +++ b/Scripts/Services/ToneAnalyzer/ToneAnalyzer.cs @@ -27,131 +27,131 @@ namespace IBM.Watson.DeveloperCloud.Services.ToneAnalyzer.v3 { - /// - /// This class wraps the Tone Analyzer service. - /// Tone Analyzer Service - /// - public class ToneAnalyzer : IWatsonService + /// + /// This class wraps the Tone Analyzer service. + /// Tone Analyzer Service + /// + public class ToneAnalyzer : IWatsonService + { + #region Private Data + private const string SERVICE_ID = "ToneAnalyzerV3"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Get Tone + private const string FUNCTION_TONE = "/v3/tone"; + + /// + /// The Get Tone Analyzed callback delegate. + /// + /// + /// + public delegate void OnGetToneAnalyzed(ToneAnalyzerResponse resp, string data); + + /// + /// Gets the tone analyze. + /// + /// true, if tone analyze was gotten, false otherwise. + /// Callback. + /// Text. + /// Data. + public bool GetToneAnalyze(OnGetToneAnalyzed callback, string text, string data = null) { - #region Private Data - private const string SERVICE_ID = "ToneAnalyzerV3"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion - - #region Get Tone - private const string FUNCTION_TONE = "/v3/tone"; - - /// - /// The Get Tone Analyzed callback delegate. - /// - /// - /// - public delegate void OnGetToneAnalyzed( ToneAnalyzerResponse resp, string data ); - - /// - /// Gets the tone analyze. - /// - /// true, if tone analyze was gotten, false otherwise. - /// Callback. - /// Text. - /// Data. - public bool GetToneAnalyze(OnGetToneAnalyzed callback, string text, string data = null) - { - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_TONE); - if (connector == null) - return false; - - GetToneAnalyzerRequest req = new GetToneAnalyzerRequest(); - req.Callback = callback; - req.OnResponse = GetToneAnalyzerResponse; - - Dictionary upload = new Dictionary(); - upload["text"] = "\"" + text + "\""; - req.Send = Encoding.UTF8.GetBytes( Json.Serialize( upload ) ); - req.Data = data; - req.Headers["Content-Type"] = "application/json"; - req.Parameters["version"] = "2016-02-11"; - req.Parameters["sentences"] = "true"; - return connector.Send(req); - } + if (callback == null) + throw new ArgumentNullException("callback"); + + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_TONE); + if (connector == null) + return false; + + GetToneAnalyzerRequest req = new GetToneAnalyzerRequest(); + req.Callback = callback; + req.OnResponse = GetToneAnalyzerResponse; + + Dictionary upload = new Dictionary(); + upload["text"] = "\"" + text + "\""; + req.Send = Encoding.UTF8.GetBytes(Json.Serialize(upload)); + req.Data = data; + req.Headers["Content-Type"] = "application/json"; + req.Parameters["version"] = "2016-02-11"; + req.Parameters["sentences"] = "true"; + return connector.Send(req); + } - private class GetToneAnalyzerRequest : RESTConnector.Request - { - public string Data {get;set;} - public OnGetToneAnalyzed Callback { get; set; } - }; + private class GetToneAnalyzerRequest : RESTConnector.Request + { + public string Data { get; set; } + public OnGetToneAnalyzed Callback { get; set; } + }; - private void GetToneAnalyzerResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void GetToneAnalyzerResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + ToneAnalyzerResponse response = new ToneAnalyzerResponse(); + if (resp.Success) + { + try + { + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + } + catch (Exception e) { - ToneAnalyzerResponse response = new ToneAnalyzerResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("ToneAnalyzer", "GetToneAnalyzerResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetToneAnalyzerRequest)req).Callback != null) - ((GetToneAnalyzerRequest)req).Callback(resp.Success ? response : null, ((GetToneAnalyzerRequest)req).Data); + Log.Error("ToneAnalyzer", "GetToneAnalyzerResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } + if (((GetToneAnalyzerRequest)req).Callback != null) + ((GetToneAnalyzerRequest)req).Callback(resp.Success ? response : null, ((GetToneAnalyzerRequest)req).Data); + } - #endregion - #region IWatsonService interface - /// - public string GetServiceID() - { - return SERVICE_ID; - } + #endregion - /// - public void GetServiceStatus(ServiceStatus callback) - { - if ( Utilities.Config.Instance.FindCredentials( SERVICE_ID ) != null ) - new CheckServiceStatus( this, callback ); - else - callback( SERVICE_ID, false ); - } + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - private class CheckServiceStatus - { - private ToneAnalyzer m_Service = null; - private ServiceStatus m_Callback = null; - - public CheckServiceStatus( ToneAnalyzer service, ServiceStatus callback ) - { - m_Service = service; - m_Callback = callback; - - if (! m_Service.GetToneAnalyze( OnGetToneAnalyzed, "Test" ) ) - m_Callback( SERVICE_ID, false ); - } - - private void OnGetToneAnalyzed( ToneAnalyzerResponse resp , string data) - { - if ( m_Callback != null ) - m_Callback( SERVICE_ID, resp != null ); - } - }; - #endregion + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Utilities.Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); } + + private class CheckServiceStatus + { + private ToneAnalyzer m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(ToneAnalyzer service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + if (!m_Service.GetToneAnalyze(OnGetToneAnalyzed, "Test")) + m_Callback(SERVICE_ID, false); + } + + private void OnGetToneAnalyzed(ToneAnalyzerResponse resp, string data) + { + if (m_Callback != null) + m_Callback(SERVICE_ID, resp != null); + } + }; + #endregion + } } diff --git a/Scripts/Services/TradeoffAnalytics/DataModels.cs b/Scripts/Services/TradeoffAnalytics/DataModels.cs old mode 100644 new mode 100755 index 6b6ad114e..22e584f3d --- a/Scripts/Services/TradeoffAnalytics/DataModels.cs +++ b/Scripts/Services/TradeoffAnalytics/DataModels.cs @@ -19,435 +19,435 @@ namespace IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1 { - - /// - /// This object for response of Dilemma service - /// - [fsObject] - public class DilemmasResponse - { - /// - /// The problem. - /// - public Problem problem { get; set; } - /// - /// The resolution. - /// - public Resolution resolution { get; set; } - } - /// - /// Problem class for Dilema service. - /// - [fsObject] - public class Problem - { - /// - /// The problem columns. - /// - public Column[] columns { get; set; } - /// - /// The problem options. - /// - public Option[] options { get; set; } - /// - /// The problem subject. - /// - public string subject { get; set; } - } + /// + /// This object for response of Dilemma service + /// + [fsObject] + public class DilemmasResponse + { + /// + /// The problem. + /// + public Problem problem { get; set; } + /// + /// The resolution. + /// + public Resolution resolution { get; set; } + } + /// + /// Problem class for Dilema service. + /// + [fsObject] + public class Problem + { + /// + /// The problem columns. + /// + public Column[] columns { get; set; } + /// + /// The problem options. + /// + public Option[] options { get; set; } /// - /// Column class for Problem. - /// - [fsObject] - public class Column - { - /// - /// The key. - /// - public string key { get; set; } - /// - /// The type. - /// - public string type{ get; set; } - /// - /// The description. - /// - public string description { get; set; } - /// - /// The format. - /// - public string format { get; set; } - /// - /// The full name. - /// - public string full_name { get; set; } - /// - /// The goal. - /// - public string goal { get; set; } - /// - /// The insignificant loss. - /// - public int insignificant_loss { get; set; } - /// - /// Weather or not the column is the objective. - /// - public bool is_objective { get; set; } - /// - /// The column preferences. - /// - public string[] preference { get; set; } - /// - /// The range. - /// - public Range range { get; set; } - /// - /// The signficant gain. - /// - public long significant_gain{ get; set; } - /// - /// The significant loss. - /// - public long significant_loss{ get; set; } - } + /// The problem subject. + /// + public string subject { get; set; } + } + /// + /// Column class for Problem. + /// + [fsObject] + public class Column + { + /// + /// The key. + /// + public string key { get; set; } + /// + /// The type. + /// + public string type { get; set; } + /// + /// The description. + /// + public string description { get; set; } + /// + /// The format. + /// + public string format { get; set; } + /// + /// The full name. + /// + public string full_name { get; set; } + /// + /// The goal. + /// + public string goal { get; set; } + /// + /// The insignificant loss. + /// + public int insignificant_loss { get; set; } + /// + /// Weather or not the column is the objective. + /// + public bool is_objective { get; set; } + /// + /// The column preferences. + /// + public string[] preference { get; set; } + /// + /// The range. + /// + public Range range { get; set; } /// - /// Range class for Column. + /// The signficant gain. /// - [fsObject] - public class Range {}; + public long significant_gain { get; set; } + /// + /// The significant loss. + /// + public long significant_loss { get; set; } + } + /// + /// Range class for Column. + /// + [fsObject] + public class Range { }; + + /// + /// Categorical range. + /// + [fsObject] + public class CategoricalRange : Range + { /// - /// Categorical range. + /// The categorical range keys. /// - [fsObject] - public class CategoricalRange : Range - { - /// - /// The categorical range keys. - /// - public string[] keys { get; set; } - } + public string[] keys { get; set; } + } + /// + /// Date range. + /// + [fsObject] + public class DateRange : Range + { + /// + /// The date range low value. + /// + public string low { get; set; } /// - /// Date range. - /// - [fsObject] - public class DateRange : Range - { - /// - /// The date range low value. - /// - public string low { get; set; } - /// - /// The date range high value. - /// - public string high { get; set; } - } + /// The date range high value. + /// + public string high { get; set; } + } + /// + /// Value range. + /// + [fsObject] + public class ValueRange : Range + { + /// + /// The value range low value. + /// + public double low { get; set; } /// - /// Value range. - /// - [fsObject] - public class ValueRange : Range - { - /// - /// The value range low value. - /// - public double low { get; set; } - /// - /// The value range high value. - /// - public double high { get; set; } - } + /// The value range high value. + /// + public double high { get; set; } + } + /// + /// Option class for Problem. + /// + [fsObject] + public class Option + { + /// + /// The application data. + /// + public ApplicationData app_data { get; set; } + /// + /// The description. + /// + public string description_html { get; set; } + /// + /// The key. + /// + public string key { get; set; } /// - /// Option class for Problem. - /// - [fsObject] - public class Option - { - /// - /// The application data. - /// - public ApplicationData app_data { get; set; } - /// - /// The description. - /// - public string description_html { get; set; } - /// - /// The key. - /// - public string key { get; set; } - /// - /// THe name. - /// - public string name { get; set; } - /// - /// The application data values. - /// - public ApplicationDataValue values { get; set; } + /// THe name. + /// + public string name { get; set; } + /// + /// The application data values. + /// + public ApplicationDataValue values { get; set; } + + } - } + /// + /// Application data class for Options. Extend this for your application. + /// + [fsObject] + public class ApplicationData { } + /// + /// Application data value for Options. Extend this for your application. + /// + [fsObject] + public class ApplicationDataValue { } + + /// + /// Resolution. + /// + [fsObject] + public class Resolution + { /// - /// Application data class for Options. Extend this for your application. + /// The resolution map. /// - [fsObject] - public class ApplicationData {} - + public Map map { get; set; } /// - /// Application data value for Options. Extend this for your application. + /// The resolution solutions. /// - [fsObject] - public class ApplicationDataValue {} + public Solution[] solutions { get; set; } + } + /// + /// Map class for the resolution. + /// + [fsObject] + public class Map + { /// - /// Resolution. - /// - [fsObject] - public class Resolution - { - /// - /// The resolution map. - /// - public Map map { get; set; } - /// - /// The resolution solutions. - /// - public Solution[] solutions { get; set; } - } - + /// The map anchors. + /// + public Anchor[] anchors { get; set; } + /// + /// The map comments. + /// + public string comments { get; set; } /// - /// Map class for the resolution. - /// - [fsObject] - public class Map - { - /// - /// The map anchors. - /// - public Anchor[] anchors { get; set; } - /// - /// The map comments. - /// - public string comments{ get; set; } - /// - /// The map config. - /// - public Config config{ get; set; } - /// - /// The map nodes. - /// - public Node[] nodes{ get; set; } - } + /// The map config. + /// + public Config config { get; set; } + /// + /// The map nodes. + /// + public Node[] nodes { get; set; } + } + /// + /// Anchor class for the Map. + /// + [fsObject] + public class Anchor + { + /// + /// The anchor name. + /// + public string name { get; set; } /// - /// Anchor class for the Map. - /// - [fsObject] - public class Anchor - { - /// - /// The anchor name. - /// - public string name { get; set; } - /// - /// The anchor position. - /// - public Position position { get; set; } - } + /// The anchor position. + /// + public Position position { get; set; } + } + /// + /// Position class for the Anchor. + /// + [fsObject] + public class Position + { + /// + /// The X position. + /// + public double x { get; set; } /// - /// Position class for the Anchor. - /// - [fsObject] - public class Position - { - /// - /// The X position. - /// - public double x { get; set; } - /// - /// The Y position. - /// - public double y { get; set; } - } + /// The Y position. + /// + public double y { get; set; } + } + /// + /// Config class for the Map. + /// + [fsObject] + public class Config + { + /// + /// The config drivers. + /// + public Drivers drivers { get; set; } /// - /// Config class for the Map. - /// - [fsObject] - public class Config - { - /// - /// The config drivers. - /// - public Drivers drivers { get; set; } - /// - /// The config parameters. - /// - public Params @params { get; set; } - } + /// The config parameters. + /// + public Params @params { get; set; } + } + /// + /// Drivers class for the Config. + /// + [fsObject] + public class Drivers + { /// - /// Drivers class for the Config. - /// - [fsObject] - public class Drivers - { - /// - /// The drivers alpha init. - /// - public double alpha_init { get; set; } - /// - /// THe drivers data multiplier. - /// - public double data_multiplier { get; set; } - /// - /// The drivers maximum map size. - /// - public double max_map_size { get; set; } - /// - /// The drivers anchor init. - /// - public double r_anchor_init { get; set; } - /// - /// The drivers fin. - /// - public double r_fin { get; set; } - /// - /// The drivers init. - /// - public double r_init { get; set; } - /// - /// The drivers training anchors. - /// - public double training_anchors { get; set; } - /// - /// The drivers training length. - /// - public double training_length { get; set; } - } + /// The drivers alpha init. + /// + public double alpha_init { get; set; } + /// + /// THe drivers data multiplier. + /// + public double data_multiplier { get; set; } + /// + /// The drivers maximum map size. + /// + public double max_map_size { get; set; } + /// + /// The drivers anchor init. + /// + public double r_anchor_init { get; set; } + /// + /// The drivers fin. + /// + public double r_fin { get; set; } + /// + /// The drivers init. + /// + public double r_init { get; set; } + /// + /// The drivers training anchors. + /// + public double training_anchors { get; set; } + /// + /// The drivers training length. + /// + public double training_length { get; set; } + } + /// + /// Params class for the Config. + /// + [fsObject] + public class Params + { + /// + /// The parameters alpha init. + /// + public double alpha_init { get; set; } + /// + /// The drivers anchor epoch. + /// + public double anchor_epoch { get; set; } + /// + /// The drivers map size. + /// + public double map_size { get; set; } /// - /// Params class for the Config. - /// - [fsObject] - public class Params - { - /// - /// The parameters alpha init. - /// - public double alpha_init { get; set; } - /// - /// The drivers anchor epoch. - /// - public double anchor_epoch { get; set; } - /// - /// The drivers map size. - /// - public double map_size { get; set; } - /// - /// The drivers anchor. - /// - public double rAnchor { get; set; } - /// - /// The drivers finish. - /// - public double rFinish { get; set; } - /// - /// The drivers init. - /// - public double rInit { get; set; } - /// - /// The drivers seed. - /// - public double seed { get; set; } - /// - /// The drivers training period. - /// - public double training_period { get; set; } - } + /// The drivers anchor. + /// + public double rAnchor { get; set; } + /// + /// The drivers finish. + /// + public double rFinish { get; set; } + /// + /// The drivers init. + /// + public double rInit { get; set; } + /// + /// The drivers seed. + /// + public double seed { get; set; } + /// + /// The drivers training period. + /// + public double training_period { get; set; } + } + /// + /// Metrics class for the resolution. + /// + [fsObject] + public class Metrics + { + /// + /// The metrtics final kappa. + /// + public double final_kappa { get; set; } /// - /// Metrics class for the resolution. - /// - [fsObject] - public class Metrics - { - /// - /// The metrtics final kappa. - /// - public double final_kappa { get; set; } - /// - /// The metrics kappa. - /// - public double kappa { get; set; } - } + /// The metrics kappa. + /// + public double kappa { get; set; } + } + /// + /// Node class for the resolution + /// + [fsObject] + public class Node + { /// - /// Node class for the resolution - /// - [fsObject] - public class Node - { - /// - /// The node coordinates. - /// - public Position coordinates { get; set; } - /// - /// The nodes solution references. - /// - public string[] solution_refs { get; set; } - } + /// The node coordinates. + /// + public Position coordinates { get; set; } + /// + /// The nodes solution references. + /// + public string[] solution_refs { get; set; } + } + /// + /// Solution class for the resolution. + /// + [fsObject] + public class Solution + { /// - /// Solution class for the resolution. - /// - [fsObject] - public class Solution - { - /// - /// The solution' shadow mes - /// - public string[] shadow_me { get; set; } - /// - /// The solution' shadows. - /// - public string[] shadows { get; set; } - /// - /// The solution' reference. - /// - public string solution_ref { get; set; } - /// - /// The solution's status. - /// - public string status { get; set; } - /// - /// The solution's status cause. - /// - public StatusCause status_cause { get; set; } - } + /// The solution' shadow mes + /// + public string[] shadow_me { get; set; } + /// + /// The solution' shadows. + /// + public string[] shadows { get; set; } + /// + /// The solution' reference. + /// + public string solution_ref { get; set; } + /// + /// The solution's status. + /// + public string status { get; set; } + /// + /// The solution's status cause. + /// + public StatusCause status_cause { get; set; } + } + /// + /// Status cause class for the solution. + /// + [fsObject] + public class StatusCause + { + /// + /// The status cause's error code. + /// + public string error_code { get; set; } /// - /// Status cause class for the solution. - /// - [fsObject] - public class StatusCause - { - /// - /// The status cause's error code. - /// - public string error_code { get; set; } - /// - /// The status cause's message. - /// - public string message { get; set; } - /// - /// The status cause's tokens. - /// - public string[] tokens { get; set; } - } + /// The status cause's message. + /// + public string message { get; set; } + /// + /// The status cause's tokens. + /// + public string[] tokens { get; set; } + } } diff --git a/Scripts/Services/TradeoffAnalytics/TradeoffAnalytics.cs b/Scripts/Services/TradeoffAnalytics/TradeoffAnalytics.cs old mode 100644 new mode 100755 index c0851557a..d983e05bd --- a/Scripts/Services/TradeoffAnalytics/TradeoffAnalytics.cs +++ b/Scripts/Services/TradeoffAnalytics/TradeoffAnalytics.cs @@ -27,178 +27,178 @@ namespace IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1 { - /// - /// This class wraps the TradeOff Analytics service. - /// TradeOff Analytics Service - /// - public class TradeoffAnalytics : IWatsonService + /// + /// This class wraps the TradeOff Analytics service. + /// TradeOff Analytics Service + /// + public class TradeoffAnalytics : IWatsonService + { + + #region Private Data + private const string SERVICE_ID = "TradeoffAnalyticsV1"; + private static fsSerializer sm_Serializer = new fsSerializer(); + #endregion + + #region Dilemmas + private const string FUNCTION_DILEMMA = "/v1/dilemmas"; + /// + /// The On Dilemma callback delegate. + /// + /// + public delegate void OnDilemma(DilemmasResponse resp); + + public bool GetDilemma(OnDilemma callback, Problem problem, Boolean generateVisualization) { + if (callback == null) + throw new ArgumentNullException("callback"); - #region Private Data - private const string SERVICE_ID = "TradeoffAnalyticsV1"; - private static fsSerializer sm_Serializer = new fsSerializer(); - #endregion + RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_DILEMMA); + if (connector == null) + return false; - #region Dilemmas - private const string FUNCTION_DILEMMA = "/v1/dilemmas"; - /// - /// The On Dilemma callback delegate. - /// - /// - public delegate void OnDilemma( DilemmasResponse resp ); + GetDilemmaRequest req = new GetDilemmaRequest(); + req.Callback = callback; + req.OnResponse = GetDilemmaResponse; + req.Parameters["generate_visualization"] = generateVisualization.ToString(); - public bool GetDilemma(OnDilemma callback, Problem problem, Boolean generateVisualization) - { - if (callback == null) - throw new ArgumentNullException("callback"); - - RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, FUNCTION_DILEMMA); - if (connector == null) - return false; - - GetDilemmaRequest req = new GetDilemmaRequest(); - req.Callback = callback; - req.OnResponse = GetDilemmaResponse; - req.Parameters["generate_visualization"] = generateVisualization.ToString(); + fsData tempData = null; + sm_Serializer.TrySerialize(problem, out tempData); - fsData tempData = null; - sm_Serializer.TrySerialize(problem, out tempData); + Log.Status("GetDilemma", "JSON: {0}", tempData.ToString()); - Log.Status("GetDilemma", "JSON: {0}", tempData.ToString()); + req.Send = Encoding.UTF8.GetBytes(tempData.ToString()); + req.Headers["Content-Type"] = "application/json"; - req.Send = Encoding.UTF8.GetBytes(tempData.ToString()); - req.Headers["Content-Type"] = "application/json"; - - return connector.Send(req); - } + return connector.Send(req); + } - private class GetDilemmaRequest : RESTConnector.Request - { - public OnDilemma Callback { get; set; } - }; + private class GetDilemmaRequest : RESTConnector.Request + { + public OnDilemma Callback { get; set; } + }; - private void GetDilemmaResponse(RESTConnector.Request req, RESTConnector.Response resp) + private void GetDilemmaResponse(RESTConnector.Request req, RESTConnector.Response resp) + { + DilemmasResponse response = new DilemmasResponse(); + if (resp.Success) + { + try { - DilemmasResponse response = new DilemmasResponse(); - if (resp.Success) - { - try - { - fsData data = null; - fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - - object obj = response; - r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); - if (!r.Succeeded) - throw new WatsonException(r.FormattedMessages); - } - catch (Exception e) - { - Log.Error("TradeoffAnalytics", "GetDilemmaResponse Exception: {0}", e.ToString()); - resp.Success = false; - } - } - - if (((GetDilemmaRequest)req).Callback != null) - ((GetDilemmaRequest)req).Callback(resp.Success ? response : null); + fsData data = null; + fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); + + object obj = response; + r = sm_Serializer.TryDeserialize(data, obj.GetType(), ref obj); + if (!r.Succeeded) + throw new WatsonException(r.FormattedMessages); } - - #endregion - - #region IWatsonService interface - /// - public string GetServiceID() + catch (Exception e) { - return SERVICE_ID; + Log.Error("TradeoffAnalytics", "GetDilemmaResponse Exception: {0}", e.ToString()); + resp.Success = false; } + } - /// - public void GetServiceStatus(ServiceStatus callback) - { - if ( Utilities.Config.Instance.FindCredentials( SERVICE_ID ) != null ) - new CheckServiceStatus( this, callback ); - else - callback( SERVICE_ID, false ); - } + if (((GetDilemmaRequest)req).Callback != null) + ((GetDilemmaRequest)req).Callback(resp.Success ? response : null); + } - /// - /// Application data value. - /// - [fsObject] - public class PingDataValue : IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1.ApplicationDataValue - { - public double ping { get; set; } - } + #endregion - /// - /// Application data. - /// - [fsObject] - public class PingData : IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1.ApplicationData - { + #region IWatsonService interface + /// + public string GetServiceID() + { + return SERVICE_ID; + } - } + /// + public void GetServiceStatus(ServiceStatus callback) + { + if (Utilities.Config.Instance.FindCredentials(SERVICE_ID) != null) + new CheckServiceStatus(this, callback); + else + callback(SERVICE_ID, false); + } + + /// + /// Application data value. + /// + [fsObject] + public class PingDataValue : IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1.ApplicationDataValue + { + public double ping { get; set; } + } + + /// + /// Application data. + /// + [fsObject] + public class PingData : IBM.Watson.DeveloperCloud.Services.TradeoffAnalytics.v1.ApplicationData + { + + } - private class CheckServiceStatus + private class CheckServiceStatus + { + private TradeoffAnalytics m_Service = null; + private ServiceStatus m_Callback = null; + + public CheckServiceStatus(TradeoffAnalytics service, ServiceStatus callback) + { + m_Service = service; + m_Callback = callback; + + Problem problem = new Problem(); + problem.subject = "ping"; + + List listColumn = new List(); + Column pingColumn = new Column(); + pingColumn.key = "ping"; + pingColumn.type = "numeric"; + pingColumn.goal = "min"; + pingColumn.is_objective = true; + pingColumn.range = new ValueRange(); + ((ValueRange)pingColumn.range).high = 1; + ((ValueRange)pingColumn.range).low = 0; + listColumn.Add(pingColumn); + + problem.columns = listColumn.ToArray(); + + List