Пример #1
0
        protected override Task <PromptRecognizerResult <bool> > OnRecognizeAsync(ITurnContext context, IDictionary <string, object> state, PromptOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var result = new PromptRecognizerResult <bool>();

            if (context.Activity.Type == ActivityTypes.Message)
            {
                // Recognize utterance
                var message = context.Activity.AsMessageActivity();
                var culture = context.Activity.Locale ?? DefaultLocale ?? English;
                var results = ChoiceRecognizer.RecognizeBoolean(message.Text, culture);
                if (results.Count > 0)
                {
                    var first = results[0];
                    if (bool.TryParse(first.Resolution["value"].ToString(), out var value))
                    {
                        result.Succeeded = true;
                        result.Value     = value;
                    }
                }
            }

            return(Task.FromResult(result));
        }
Пример #2
0
        public void WithLazyInitialization_CacheEmpty()
        {
            var recognizer    = new ChoiceRecognizer(lazyInitialization: true);
            var internalCache = recognizer.GetInternalCache();

            Assert.AreEqual(0, internalCache.Count);
        }
Пример #3
0
        public void WithoutLazyInitialization_CacheFull()
        {
            var recognizer    = new ChoiceRecognizer(lazyInitialization: false);
            var internalCache = recognizer.GetInternalCache();

            Assert.AreNotEqual(0, internalCache.Count);
        }
Пример #4
0
        public void WithoutLazyInitializationAndCulture_CacheWithCulture()
        {
            var recognizer    = new ChoiceRecognizer(Culture.English, lazyInitialization: false);
            var internalCache = recognizer.GetInternalCache();

            Assert.IsTrue(internalCache.All(kv => kv.Key.culture == Culture.English));
        }
        protected override Task <InputState> OnRecognizeInputAsync(DialogContext dc, CancellationToken cancellationToken)
        {
            var validateText = dc.State.GetValue <object>(VALUE_PROPERTY);

            if (!(validateText is string))
            {
                return(Task.FromResult(InputState.Invalid));
            }

            var culture = GetCulture(dc);
            var message = validateText.ToString();

            var recognizeGuid = ChoiceRecognizer.RecognizeBoolean(message, culture);

            if (recognizeGuid == null || recognizeGuid.Count <= 0)
            {
                return(Task.FromResult(InputState.Unrecognized));
            }

            var result = recognizeGuid[0].Resolution["value"].ToString();

            if (ResultProperty != null)
            {
                dc.State.SetValue(ResultProperty.GetValue(dc.State), result);
            }

            return(Task.FromResult(InputState.Valid));
        }
        public void WithoutTargetCultureAndWithoutCulture_FallbackToEnglishCulture()
        {
            var recognizer  = new ChoiceRecognizer();
            var testedModel = recognizer.GetBooleanModel();

            TestChoice(testedModel, controlModel, TestInput);
        }
        public void WithInvalidCulture_AlwaysUseEnglish()
        {
            var recognizer  = new ChoiceRecognizer();
            var testedModel = recognizer.GetBooleanModel(InvalidCulture);

            TestChoice(testedModel, controlModel, TestInput);
        }
Пример #8
0
        /// <summary>
        /// Parse query with all recognizers
        /// </summary>
        private static IEnumerable <ModelResult> ParseAll(string query, string culture)
        {
            return(MergeResults(
                       // Number recognizer will find any number from the input
                       // E.g "I have two apples" will return "2".
                       NumberRecognizer.RecognizeNumber(query, culture),

                       // Ordinal number recognizer will find any ordinal number
                       // E.g "eleventh" will return "11".
                       NumberRecognizer.RecognizeOrdinal(query, culture),

                       // Percentage recognizer will find any number presented as percentage
                       // E.g "one hundred percents" will return "100%"
                       NumberRecognizer.RecognizePercentage(query, culture),

                       // Number Range recognizer will find any cardinal or ordinal number range
                       // E.g. "between 2 and 5" will return "(2,5)"
                       NumberRecognizer.RecognizeNumberRange(query, culture),

                       // Age recognizer will find any age number presented
                       // E.g "After ninety five years of age, perspectives change" will return "95 Year"
                       NumberWithUnitRecognizer.RecognizeAge(query, culture),

                       // Currency recognizer will find any currency presented
                       // E.g "Interest expense in the 1988 third quarter was $ 75.3 million" will return "75300000 Dollar"
                       NumberWithUnitRecognizer.RecognizeCurrency(query, culture),

                       // Dimension recognizer will find any dimension presented
                       // E.g "The six-mile trip to my airport hotel that had taken 20 minutes earlier in the day took more than three hours." will return "6 Mile"
                       NumberWithUnitRecognizer.RecognizeDimension(query, culture),

                       // Temperature recognizer will find any temperature presented
                       // E.g "Set the temperature to 30 degrees celsius" will return "30 C"
                       NumberWithUnitRecognizer.RecognizeTemperature(query, culture),

                       // Datetime recognizer This model will find any Date even if its write in coloquial language
                       // E.g "I'll go back 8pm today" will return "2017-10-04 20:00:00"
                       DateTimeRecognizer.RecognizeDateTime(query, culture),

                       // PhoneNumber recognizer will find any phone number presented
                       // E.g "My phone number is ( 19 ) 38294427."
                       SequenceRecognizer.RecognizePhoneNumber(query, culture),

                       // Add IP recognizer - This recognizer will find any Ipv4/Ipv6 presented
                       // E.g "My Ip is 8.8.8.8"
                       SequenceRecognizer.RecognizeIpAddress(query, culture),

                       // Add Boolean recognizer - This model will find yes/no like responses, including emoji -
                       // E.g "yup, I need that" will return "True"
                       ChoiceRecognizer.RecognizeBoolean(query, culture)
                       ));
        }
Пример #9
0
        public void RecognizeBoolean()
        {
            var input = "I don't thing so. no.";

            var actual = ChoiceRecognizer.RecognizeBoolean(input, Culture.English);

            Assert.AreEqual(1, actual.Count);
            Assert.AreEqual("boolean", actual[0].TypeName);
            Assert.AreEqual("no", actual[0].Text);

            Assert.AreEqual(false, actual[0].Resolution["value"]);
            Assert.AreEqual(0.5, actual[0].Resolution["score"]);
        }
Пример #10
0
        protected override Task <PromptRecognizerResult <bool> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var result = new PromptRecognizerResult <bool>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                // Recognize utterance
                var message = turnContext.Activity.AsMessageActivity();
                var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;
                var results = ChoiceRecognizer.RecognizeBoolean(message.Text, culture);
                if (results.Count > 0)
                {
                    var first = results[0];
                    if (bool.TryParse(first.Resolution["value"].ToString(), out var value))
                    {
                        result.Succeeded = true;
                        result.Value     = value;
                    }
                }
                else
                {
                    // First check whether the prompt was sent to the user with numbers - if it was we should recognize numbers
                    var choiceOptions = ChoiceOptions ?? DefaultChoiceOptions[culture];

                    // This logic reflects the fact that IncludeNumbers is nullable and True is the default set in Inline style
                    if (!choiceOptions.IncludeNumbers.HasValue || choiceOptions.IncludeNumbers.Value)
                    {
                        // The text may be a number in which case we will interpret that as a choice.
                        var confirmChoices = ConfirmChoices ?? DefaultConfirmChoices[culture];
                        var choices        = new List <Choice> {
                            confirmChoices.Item1, confirmChoices.Item2
                        };
                        var secondAttemptResults = ChoiceRecognizers.RecognizeChoices(message.Text, choices);
                        if (secondAttemptResults.Count > 0)
                        {
                            result.Succeeded = true;
                            result.Value     = secondAttemptResults[0].Resolution.Index == 0;
                        }
                    }
                }
            }

            return(Task.FromResult(result));
        }
Пример #11
0
        public static void CheckConformation(this Message message, out bool isConfirming, out double confidence)
        {
            isConfirming = false;
            confidence   = 0.1;
            var recognizer = new ChoiceRecognizer(Culture.Dutch);
            var model      = recognizer.GetBooleanModel();
            var check      = model.Parse(message.Text);

            if (check.Count > 0)
            {
                double.TryParse(check.First().Resolution["score"].ToString(), out confidence);
                bool.TryParse(check.First().Resolution["value"].ToString(), out isConfirming);
                isConfirming = isConfirming && confidence > 0.5;
            }
        }
Пример #12
0
        [NotNull] public static BooleanChoiceExtraction BooleanChoice(string input, string culture = Culture.EnglishOthers)
        {
            var bools = ChoiceRecognizer.RecognizeBoolean(input, culture).Where(a => a.TypeName == "boolean").ToArray();

            var   trues          = 0;
            var   falses         = 0;
            float bestConfidence = 0;

            foreach (var item in bools)
            {
                if (!item.Resolution.TryGetValue("value", out var valueObj))
                {
                    continue;
                }
                if (!item.Resolution.TryGetValue("score", out var confidenceObj))
                {
                    continue;
                }

                var value      = Convert.ToBoolean(valueObj);
                var confidence = Convert.ToSingle(confidenceObj);

                //Keep a count of true and false matches
                if (value)
                {
                    trues++;
                }
                else
                {
                    falses++;
                }

                //Return false as soon as we find both results (i.e. we're not sure)
                if (trues * falses != 0)
                {
                    return(new BooleanChoiceExtraction(false, 0));
                }

                bestConfidence = Math.Max(bestConfidence, confidence);
            }

            return(new BooleanChoiceExtraction(trues > 0, bestConfidence));
        }
Пример #13
0
        public static PromptRecognizerResult <bool> ConfirmYesOrNo(string utterance, string locale = null)
        {
            var result = new PromptRecognizerResult <bool>();

            if (!string.IsNullOrEmpty(utterance))
            {
                // Recognize utterance
                var results = ChoiceRecognizer.RecognizeBoolean(utterance, locale);
                if (results.Count > 0)
                {
                    var first = results[0];
                    if (bool.TryParse(first.Resolution["value"].ToString(), out var value))
                    {
                        result.Succeeded = true;
                        result.Value     = value;
                    }
                }
            }

            return(result);
        }
        bool GetBool(string text)
        {
            var entities = ChoiceRecognizer.RecognizeBoolean(text, Culture.English);;

            foreach (var entity in entities)
            {
                if (entity.TypeName != "boolean")
                {
                    break;
                }
                if (entity.Resolution.TryGetValue("score", out object scoreObject))
                {
                    double score = Convert.ToDouble(scoreObject);
                    if (score >= 0.5)
                    {
                        if (entity.Resolution.TryGetValue("value", out object valuObject))
                        {
                            return((bool)valuObject);
                        }
                    }
                }
            }
            throw new System.Exception("not a valid response");
        }
Пример #15
0
 public void RecognizeBoolean(string text, string culture, string scale, string typeName)
 {
     ChoiceRecognizer.RecognizeBoolean(text, culture);
 }
        public void InitializationWithIntOption_ResolveOptionsEnum()
        {
            var recognizer = new ChoiceRecognizer(EnglishCulture, 0);

            Assert.IsTrue(recognizer.Options.HasFlag(ChoiceOptions.None));
        }
        public void InitializationNonLazy_CanGetModel()
        {
            var recognizer = new ChoiceRecognizer(EnglishCulture, ChoiceOptions.None, lazyInitialization: false);

            Assert.AreEqual(recognizer.GetBooleanModel(), recognizer.GetBooleanModel(EnglishCulture));
        }
        public void WithoutTargetCultureAndWithoutCulture_FallbackToEnglishCulture()
        {
            var recognizer = new ChoiceRecognizer();

            Assert.AreEqual(recognizer.GetBooleanModel(), recognizer.GetBooleanModel(EnglishCulture));
        }
        public void WithInvalidCultureAsTargetAndWithoutFallback_ThrowError()
        {
            var recognizer = new ChoiceRecognizer(InvalidCulture);

            Assert.ThrowsException <ArgumentException>(() => recognizer.GetBooleanModel(fallbackToDefaultCulture: false));
        }
        public void WithInvalidCulture_UseTargetCulture()
        {
            var recognizer = new ChoiceRecognizer(EnglishCulture);

            Assert.AreEqual(recognizer.GetBooleanModel(InvalidCulture), recognizer.GetBooleanModel());
        }
Пример #21
0
        private void OutputButton_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();

            string query = InputField.Text;
            string SelectedRecognizer = RecognizerField.Text;
            string culture            = LanguageToCode(LanguageField.Text);

            if (query != "")
            {
                //----------------------------------------------------------Recognizers
                try
                {
                    if (SelectedRecognizer == "Number Recognizer")
                    {
                        // Number recognizer will find any number from the input
                        // E.g "I have two apples" will return "2".
                        var Recognizer = NumberRecognizer.RecognizeNumber(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Ordinal Recognizer")
                    {
                        // Ordinal number recognizer will find any ordinal number
                        // E.g "eleventh" will return "11".
                        var Recognizer = NumberRecognizer.RecognizeOrdinal(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Percentage Recognizer")
                    {
                        // Percentage recognizer will find any number presented as percentage
                        // E.g "one hundred percents" will return "100%"
                        var Recognizer = NumberRecognizer.RecognizePercentage(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Number Range Recognizer")
                    {
                        // Number Range recognizer will find any cardinal or ordinal number range
                        // E.g. "between 2 and 5" will return "(2,5)"
                        var Recognizer = NumberRecognizer.RecognizeNumberRange(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Age Recognizer")
                    {
                        // Age recognizer will find any age number presented
                        // E.g "After ninety five years of age, perspectives change" will return "95 Year"
                        var Recognizer = NumberWithUnitRecognizer.RecognizeAge(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Currency Recognizer")
                    {
                        // Currency recognizer will find any currency presented
                        // E.g "Interest expense in the 1988 third quarter was $ 75.3 million" will return "75300000 Dollar"
                        var Recognizer = NumberWithUnitRecognizer.RecognizeCurrency(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Dimention Recognizer")
                    {
                        // Dimension recognizer will find any dimension presented
                        // E.g "The six-mile trip to my airport hotel that had taken 20 minutes earlier in the day took more than three hours." will return "6 Mile"
                        var Recognizer = NumberWithUnitRecognizer.RecognizeDimension(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Temperature Recognizer")
                    {
                        // Temperature recognizer will find any temperature presented
                        // E.g "Set the temperature to 30 degrees celsius" will return "30 C"
                        var Recognizer = NumberWithUnitRecognizer.RecognizeTemperature(query, culture);
                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Date And Time Recognizer")
                    {
                        // Datetime recognizer This model will find any Date even if its write in coloquial language
                        // E.g "I'll go back 8pm today" will return "2017-10-04 20:00:00"
                        var Recognizer = DateTimeRecognizer.RecognizeDateTime(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Phone Number Recognizer")
                    {
                        // PhoneNumber recognizer will find any phone number presented
                        // E.g "My phone number is ( 19 ) 38294427."
                        var Recognizer = SequenceRecognizer.RecognizePhoneNumber(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Ip Address Recognizer")
                    {
                        //IP recognizer will find any Ipv4/Ipv6 presented
                        // E.g "My Ip is 8.8.8.8"
                        var Recognizer = SequenceRecognizer.RecognizeIpAddress(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                    else if (SelectedRecognizer == "Choice Recognizer")
                    {
                        //Boolean recognizer will find yes/no like responses, including emoji -
                        // E.g "yup, I need that" will return "True"
                        var Recognizer = ChoiceRecognizer.RecognizeBoolean(query, culture);

                        for (int i = 0; i < Recognizer.Count; i++)
                        {
                            string[]     arr = new string[4];
                            ListViewItem itm;
                            //add items to ListView
                            arr[0] = Recognizer[i].Text.ToString();
                            arr[1] = Recognizer[i].Resolution["value"].ToString();
                            arr[2] = Recognizer[i].Start.ToString();
                            arr[3] = Recognizer[i].End.ToString();
                            itm    = new ListViewItem(arr);
                            listView1.Items.Add(itm);
                        }
                    }
                }
                catch (Exception error)
                {
                    MessageBox.Show("Unable to Recognize\n" + "Exception: " + error.Message.ToString());
                }
            }
            //----------------------------------------------------------Recognizers End
        }
 protected override List <ModelResult> Recognize(string text, string culture)
 {
     return(ChoiceRecognizer.RecognizeBoolean(text, culture));
 }
Пример #23
0
        public void Initialization()
        {
            var recognizer = new ChoiceRecognizer();

            recognizer.GetInternalCache().Clear();
        }