Example #1
0
 public void OnResponse(WitResponseNode response)
 {
     if (!showJson)
     {
         textArea.text = response["text"];
     }
 }
Example #2
0
        public static WitEntity FromJson(WitResponseNode entityWitResponse)
        {
            var entity = new WitEntity();

            entity.UpdateData(entityWitResponse);
            return(entity);
        }
Example #3
0
        private void SubmitUtterance()
        {
            // Remove response
            _response = null;

            if (Application.isPlaying)
            {
                if (service)
                {
                    _status       = WitTexts.Texts.UnderstandingViewerListeningLabel;
                    _responseText = _status;
                    service.Activate(_utterance);
                    // Hack to watch for loading to complete. Response does not
                    // come back on the main thread so Repaint in onResponse in
                    // the editor does nothing.
                    EditorApplication.update += WatchForWitResponse;
                }
            }
            else
            {
                _status       = WitTexts.Texts.UnderstandingViewerLoadingLabel;
                _responseText = _status;
                _submitStart  = System.DateTime.Now;
                _request      = witConfiguration.MessageRequest(_utterance, new WitRequestOptions());
                _request.onPartialResponse += (r) => OnPartialResponse(r?.ResponseData);
                _request.onResponse        += (r) => OnResponse(r?.ResponseData);
                _request.Request();
            }
        }
Example #4
0
 private void OnPartialResponse(WitResponseNode ResponseData)
 {
     if (null != ResponseData)
     {
         ShowResponse(ResponseData, true);
     }
 }
Example #5
0
        public static WitIntent FromJson(WitResponseNode intentWitResponse)
        {
            var intent = new WitIntent();

            intent.UpdateData(intentWitResponse);
            return(intent);
        }
Example #6
0
 protected virtual void OnHandlePartialResponse(WitResponseNode response)
 {
     if (handlePartialResponses)
     {
         OnHandleResponse(response);
     }
 }
Example #7
0
        // Apply all application data
        private static void ApplyAllApplicationData(string serverToken, WitResponseNode witResponse, Action <string> onComplete)
        {
            var applications = witResponse.AsArray;

            for (int i = 0; i < applications.Count; i++)
            {
                // Get application
                var    application = WitApplication.FromJson(applications[i]);
                string appID       = application?.id;
                // Apply app server token if applicable
                if (applications[i]["is_app_for_token"].AsBool)
                {
                    WitAuthUtility.SetAppServerToken(appID, serverToken);
                }
                // Apply to configuration
                int witConfigIndex = Array.FindIndex(WitConfigs, (configuration) => string.Equals(appID, configuration?.application?.id));
                if (witConfigIndex != -1)
                {
                    WitConfiguration configuration = _witConfigs[witConfigIndex];
                    configuration.application = application;
                    EditorUtility.SetDirty(configuration);
                    configuration.RefreshData();
                }
            }
            onComplete("");
        }
Example #8
0
        /// <summary>
        /// Imported json data into an existing TTSPreloadSettings asset
        /// </summary>
        public static bool ImportData(TTSPreloadSettings preloadSettings, string textFilePath)
        {
            // Check for file
            if (!File.Exists(textFilePath))
            {
                Debug.LogError($"TTS Preload Utility - Preload file does not exist\nPath: {textFilePath}");
                return(false);
            }
            // Load file
            string textFileContents = File.ReadAllText(textFilePath);

            if (string.IsNullOrEmpty(textFileContents))
            {
                Debug.LogError($"TTS Preload Utility - Preload file load failed\nPath: {textFilePath}");
                return(false);
            }
            // Parse file
            WitResponseNode node = WitResponseNode.Parse(textFileContents);

            if (node == null)
            {
                Debug.LogError($"TTS Preload Utility - Preload file parse failed\nPath: {textFilePath}");
                return(false);
            }
            // Iterate children for texts
            WitResponseClass data = node.AsObject;
            Dictionary <string, List <string> > textsByVoice = new Dictionary <string, List <string> >();

            foreach (var voiceName in data.ChildNodeNames)
            {
                // Get texts list
                List <string> texts;
                if (textsByVoice.ContainsKey(voiceName))
                {
                    texts = textsByVoice[voiceName];
                }
                else
                {
                    texts = new List <string>();
                }

                // Add text phrases
                string[] voicePhrases = data[voiceName].AsStringArray;
                if (voicePhrases != null)
                {
                    foreach (var phrase in voicePhrases)
                    {
                        if (!string.IsNullOrEmpty(phrase) && !texts.Contains(phrase))
                        {
                            texts.Add(phrase);
                        }
                    }
                }

                // Apply
                textsByVoice[voiceName] = texts;
            }
            // Import
            return(ImportData(preloadSettings, textsByVoice));
        }
Example #9
0
        /// <summary>
        /// Gets The first entity with the given name as int data
        /// </summary>
        /// <param name="witResponse"></param>
        /// <param name="name">The entity name typically something like name:name</param>
        /// <returns></returns>
        public static WitEntityIntData GetFirstWitIntEntity(this WitResponseNode witResponse,
                                                            string name)
        {
            var array = witResponse?["entities"]?[name].AsArray;

            return(array?.Count > 0 ? array[0].AsWitIntEntity : null);
        }
Example #10
0
        /// <summary>
        /// Directly processes a command result getting the slots with WitResult utilities
        /// </summary>
        /// <param name="commandResult">Result data from Wit.ai activation to be processed</param>
        public void UpdateColor(WitResponseNode commandResult)
        {
            string colorName = commandResult.GetFirstEntityValue("color:color");
            string shape     = commandResult.GetFirstEntityValue("shape:shape");

            UpdateColor(colorName, shape);
        }
Example #11
0
 private void ShowResponse(WitResponseNode r, bool isPartial)
 {
     _response      = r;
     _responseText  = _response.ToString();
     _requestLength = DateTime.Now - _submitStart;
     _status        = $"{(isPartial ? "Partial" : "Full")}Response time: {_requestLength}";
 }
Example #12
0
        // Safely handles
        private bool ProcessStringResponse(string stringResponse)
        {
            // Decode full response
            responseData = WitResponseJson.Parse(stringResponse);

            // Handle responses
            bool isFinal = responseData.HandleResponse((transcription, final) =>
            {
                // Call partial transcription
                if (!final)
                {
                    MainThreadCallback(() => onPartialTranscription?.Invoke(transcription));
                }
                // Call full transcription
                else
                {
                    MainThreadCallback(() => onFullTranscription?.Invoke(transcription));
                }
            }, (response, final) =>
            {
                // Call partial response
                SafeInvoke(onPartialResponse);
                // Call final response
                if (final)
                {
                    SafeInvoke(onResponse);
                }
            });

            // Return final
            return(isFinal);
        }
Example #13
0
        public static WitApplication FromJson(WitResponseNode appWitResponse)
        {
            var app = new WitApplication();

            app.UpdateData(appWitResponse);
            return(app);
        }
Example #14
0
        public static WitTrait FromJson(WitResponseNode traitWitResponse)
        {
            var trait = new WitTrait();

            trait.UpdateData(traitWitResponse);
            return(trait);
        }
Example #15
0
        protected override void OnHandleResponse(WitResponseNode response)
        {
            var text = response["text"].Value;

            if (useRegex)
            {
                if (null == regex)
                {
                    regex = new Regex(searchText, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }

                var match = regex.Match(text);
                if (match.Success)
                {
                    if (exactMatch && match.Value == text)
                    {
                        onUtteranceMatched?.Invoke(text);
                    }
                    else
                    {
                        onUtteranceMatched?.Invoke(text);
                    }
                }
            }
            else if (exactMatch && text.ToLower() == searchText.ToLower())
            {
                onUtteranceMatched?.Invoke(text);
            }
            else if (text.ToLower().Contains(searchText.ToLower()))
            {
                onUtteranceMatched?.Invoke(text);
            }
        }
Example #16
0
 private void ShowResponse(WitResponseNode r)
 {
     response      = r;
     responseText  = response.ToString();
     requestLength = DateTime.Now - submitStart;
     status        = $"Response time: {requestLength}";
 }
Example #17
0
        protected override void OnHandleResponse(WitResponseNode response)
        {
            if (null == response)
            {
                return;
            }

            bool matched = false;

            foreach (var intentNode in response?["intents"]?.Childs)
            {
                var resultConfidence = intentNode["confidence"].AsFloat;
                if (intent == intentNode["name"].Value)
                {
                    matched = true;
                    if (resultConfidence >= confidence)
                    {
                        onIntentTriggered.Invoke();
                    }

                    CheckInsideRange(resultConfidence);
                    CheckOutsideRange(resultConfidence);
                }
            }

            if (!matched)
            {
                CheckInsideRange(0);
                CheckOutsideRange(0);
            }
        }
Example #18
0
 public override void UpdateData(WitResponseNode appWitResponse)
 {
     id        = appWitResponse["id"].Value;
     name      = appWitResponse["name"].Value;
     lang      = appWitResponse["lang"].Value;
     isPrivate = appWitResponse["private"].AsBool;
     createdAt = appWitResponse["created_at"].Value;
 }
Example #19
0
 public static WitEntityRole FromJson(WitResponseNode roleNode)
 {
     return(new WitEntityRole()
     {
         id = roleNode["id"],
         name = roleNode["name"]
     });
 }
Example #20
0
 public static WitKeyword FromJson(WitResponseNode keywordNode)
 {
     return(new WitKeyword()
     {
         keyword = keywordNode["keyword"],
         synonyms = keywordNode["synonyms"].AsStringArray
     });
 }
Example #21
0
 public WitIntentData FromIntentWitResponseNode(WitResponseNode node)
 {
     responseNode = node;
     id           = node[WitIntent.Fields.ID];
     name         = node[WitIntent.Fields.NAME];
     confidence   = node[WitIntent.Fields.CONFIDENCE].AsFloat;
     return(this);
 }
Example #22
0
 public static WitTraitValue FromJson(WitResponseNode traitValueNode)
 {
     return(new WitTraitValue()
     {
         id = traitValueNode["id"],
         value = traitValueNode["value"]
     });
 }
Example #23
0
        protected override void OnHandleResponse(WitResponseNode response)
        {
            var intentNode = WitResultUtilities.GetFirstIntent(response);

            if (intent == intentNode["name"].Value && intentNode["confidence"].AsFloat > confidence)
            {
                onIntentTriggered.Invoke();
            }
        }
Example #24
0
        public override bool Equals(WitResponseNode response, object value)
        {
            if (value is string sValue)
            {
                return(GetStringValue(response) == sValue);
            }

            return("" + value == GetStringValue(response));
        }
Example #25
0
        public override string GetStringValue(WitResponseNode response)
        {
            if (null != child)
            {
                return(child.GetStringValue(response[index]));
            }

            return(response[index].Value);
        }
Example #26
0
        public override string GetStringValue(WitResponseNode response)
        {
            if (null != child && null != response?[key])
            {
                return(child.GetStringValue(response[key]));
            }

            return(response?[key]?.Value);
        }
Example #27
0
        public override float GetFloatValue(WitResponseNode response)
        {
            if (null != child)
            {
                return(child.GetFloatValue(response[key]));
            }

            return(response[key].AsFloat);
        }
Example #28
0
        public override int GetIntValue(WitResponseNode response)
        {
            if (null != child)
            {
                return(child.GetIntValue(response[key]));
            }

            return(response[key].AsInt);
        }
Example #29
0
        /// <summary>
        /// Gets a collection of string value containing the selected value from
        /// each entity in the response.
        /// </summary>
        /// <param name="witResponse"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string[] GetAllEntityValues(this WitResponseNode witResponse, string name)
        {
            var values = new string[witResponse?["entities"]?[name]?.Count ?? 0];

            for (var i = 0; i < witResponse?["entities"]?[name]?.Count; i++)
            {
                values[i] = witResponse?["entities"]?[name]?[i]?["value"]?.Value;
            }
            return(values);
        }
Example #30
0
 public void OnResponse(WitResponseNode response)
 {
     if (!string.IsNullOrEmpty(response["text"]))
     {
         textArea.text = "I heard: " + response["text"];
     }
     else
     {
         textArea.text = freshStateText;
     }
 }