Esempio n. 1
0
        public static bool CheckAge(string input, out int age, out string message)
        {
            age     = 0;
            message = null;
            try
            {
                List <ModelResult> results = NumberRecognizer.RecognizeNumber(input, "en-us");
                foreach (ModelResult result in results)
                {
                    if (result.Resolution.TryGetValue("value", out object value))
                    {
                        age = Convert.ToInt32(value);
                        if (age >= 18 && age <= 120)
                        {
                            return(true);
                        }
                    }
                }
                message = "Please enter an age between 18 and 120.";
            }
            catch
            {
                message = "I'm sorry, I could not interpret that as an age. Please enter an age between 18 and 120.";
            }

            return(message is null);
        }
Esempio n. 2
0
        public static bool ValidateAge(string input, out int age, out string message)
        {
            age     = 0;
            message = null;

            try
            {
                var results = NumberRecognizer.RecognizeNumber(input, Culture.English);

                foreach (var result in results)
                {
                    // The result resolution is a dictionary, where the "value" entry contains the processed string.
                    if (result.Resolution.TryGetValue("value", out object value))
                    {
                        age = Convert.ToInt32(value);
                        if (age >= 18 && age <= 120)
                        {
                            return(true);
                        }
                    }
                }

                message = "Please enter an age between 18 and 120.";
            }
            catch
            {
                message = "I'm sorry, I could not interpret that as an age. Please enter an age between 18 and 120.";
            }

            return(message is null);
        }
Esempio n. 3
0
        private bool TryGetNumber(string text, out decimal result)
        {
            // Get Number for the specified culture
            var style   = NumberStyles.Number | NumberStyles.AllowCurrencySymbol;
            var culture = CultureInfo.CreateSpecificCulture(Culture.English);
            var results = NumberRecognizer.RecognizeNumber(text, Culture.English);

            if (results.Count > 0)
            {
                if (results.First().TypeName == "number" &&
                    decimal.TryParse(results.First().Resolution["value"].ToString(), style, culture, out result))
                {
                    // Validate number
                    if (result < 0)
                    {
                        result = 0;
                        return(false);
                    }

                    return(true);
                }
            }

            result = 0;
            return(false);
        }
        public void RecognizeNumber()
        {
            var actual = NumberRecognizer.RecognizeNumber("192", Culture.English);

            Assert.AreEqual("number", actual[0].TypeName);
            Assert.AreEqual("192", actual[0].Text);
            Assert.AreEqual("192", actual[0].Resolution["value"]);
        }
Esempio n. 5
0
        public void GivenNumber_WhenRecognizeNumber_ThenGetExpectedDigit(string number, int expectedDigit)
        {
            // Act
            var numberRecognizer = new NumberRecognizer();
            var digit            = numberRecognizer.RecognizeNumber(number);

            //Assert
            Assert.AreEqual(expectedDigit, digit, "{0} should be recognized as {1}", number, expectedDigit);
        }
Esempio n. 6
0
        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);
            List <ModelResult> results;

            var message = validateText.ToString();

            switch (NumberType.GetValue(dc.State))
            {
            case NumberWithTypeInputType.Percentage:
                results = NumberRecognizer.RecognizePercentage(message, culture);
                break;

            case NumberWithTypeInputType.Number:
                results = NumberRecognizer.RecognizeNumber(message, culture);
                break;

            case NumberWithTypeInputType.NumberRange:
                results = NumberRecognizer.RecognizeNumberRange(message, culture);
                break;

            case NumberWithTypeInputType.Ordinal:
                results = NumberRecognizer.RecognizeOrdinal(message, culture);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (results == null || results.Count <= 0 || results[0].Resolution == null)
            {
                return(Task.FromResult(InputState.Unrecognized));
            }

            var result = new
            {
                Text  = results[0].Text,
                Value = results[0].Resolution["value"].ToString(),
            };

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

            return(Task.FromResult(InputState.Valid));
        }
Esempio n. 7
0
        protected override Task <PromptRecognizerResult <NumberWithTypeResult> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options, CancellationToken cancellationToken = new CancellationToken())
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var result = new PromptRecognizerResult <NumberWithTypeResult>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity();
                var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;

                List <ModelResult> results = null;
                switch (PromptType)
                {
                case NumberWithTypePromptType.Ordinal:
                    results = NumberRecognizer.RecognizeOrdinal(message.Text, culture);
                    break;

                case NumberWithTypePromptType.Percentage:
                    results = NumberRecognizer.RecognizePercentage(message.Text, culture);
                    break;

                case NumberWithTypePromptType.NumberRange:
                    results = NumberRecognizer.RecognizeNumberRange(message.Text, culture);
                    break;

                case NumberWithTypePromptType.Number:
                    results = NumberRecognizer.RecognizeNumber(message.Text, culture);
                    break;
                }

                if (results?.Count > 0)
                {
                    var resolution = results[0].Resolution;
                    if (resolution != null)
                    {
                        result.Succeeded = true;
                        var numberWithTypeResult = new NumberWithTypeResult()
                        {
                            Text  = results[0].Text,
                            Value = resolution["value"].ToString()
                        };

                        result.Value = numberWithTypeResult;
                    }
                }
            }

            return(Task.FromResult(result));
        }
Esempio n. 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)
                       ));
        }
Esempio n. 9
0
        protected override Task <InputState> OnRecognizeInput(DialogContext dc)
        {
            var dcState = dc.GetState();
            var input   = dcState.GetValue <object>(VALUE_PROPERTY);

            var culture = GetCulture(dc);
            var results = NumberRecognizer.RecognizeNumber(input.ToString(), culture);

            if (results.Count > 0)
            {
                // Try to parse value based on type
                var text = results[0].Resolution["value"].ToString();

                if (int.TryParse(text, out var intValue))
                {
                    input = intValue;
                }
                else
                {
                    if (float.TryParse(text, out var value))
                    {
                        input = value;
                    }
                    else
                    {
                        return(Task.FromResult(InputState.Unrecognized));
                    }
                }
            }
            else
            {
                return(Task.FromResult(InputState.Unrecognized));
            }

            dcState.SetValue(VALUE_PROPERTY, input);

            if (OutputFormat != null)
            {
                var(outputValue, error) = this.OutputFormat.TryGetValue(dcState);
                if (error == null)
                {
                    dcState.SetValue(VALUE_PROPERTY, outputValue);
                }
                else
                {
                    throw new Exception($"In TextInput, OutputFormat Expression evaluation resulted in an error. Expression: {this.OutputFormat}. Error: {error}");
                }
            }

            return(Task.FromResult(InputState.Valid));
        }
        private static double TryExtractWorkHours(List <string> possibleValues)
        {
            var hourTokens   = new[] { "hours", "hrs", "hr", "h" };
            var minuteTokens = new[] { "minutes", "min", "mn", "m" };
            var result       = 0.0;

            foreach (var val in possibleValues)
            {
                var hours           = 0.0;
                var hoursMultiplier = 0.0;
                foreach (var token in hourTokens)
                {
                    if (val.ToLower().Contains(token))
                    {
                        hoursMultiplier = 1.0;
                    }
                }

                foreach (var token in minuteTokens)
                {
                    if (val.ToLower().Contains(token))
                    {
                        hoursMultiplier = 1.0 / 60.0;
                    }
                }

                if (double.TryParse(val.Split(' ')[0], out hours))
                {
                    if (result <= 0)
                    {
                        result = hours * hoursMultiplier;
                    }
                }
                else
                {
                    var possibleHours = NumberRecognizer.RecognizeNumber(val.Split(' ')[0], Culture.English);
                    if (possibleHours.Count > 0)
                    {
                        possibleHours.FirstOrDefault().Resolution.TryGetValue("value", out var hoursString);
                        result = Convert.ToDouble(hoursString) * hoursMultiplier;
                    }
                }
            }

            return(result);
        }
Esempio n. 11
0
        /// <summary>
        /// Validator function to verify if the quantity the user entered gets recognized.
        /// </summary>
        /// <param name="promptContext">Context for this prompt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        private async Task <bool> ValidateQuantity(PromptValidatorContext <string> promptContext, CancellationToken cancellationToken)
        {
            var result  = promptContext.Recognized.Value ?? string.Empty;
            var results = NumberRecognizer.RecognizeNumber(result, culture);

            if (results.Count == 0)
            {
                await promptContext.Context.SendActivityAsync(InvalidQuantityErrorMessage);

                return(false);
            }

            if (results.First().TypeName == "number" && double.TryParse(results.First().Resolution["value"].ToString(), out double value))
            {
                // Validate number
                if ((value < 1) || (value % 1 != 0))
                {
                    await promptContext.Context.SendActivityAsync(InvalidQuantityErrorMessage);

                    return(false);
                }

                if (value > 100)
                {
                    await promptContext.Context.SendActivityAsync(InvalidOverQuantityErrorMessage);

                    return(false);
                }

                var quantityRoses   = Convert.ToInt32(results.First().Resolution["value"]);
                var quantityMessage = quantityRoses == 1
                ? "I'll send just one rose."
                : $"I'll send {quantityRoses} roses.";
                promptContext.Recognized.Value = quantityRoses.ToString();
                await promptContext.Context.SendActivityAsync(quantityMessage);

                return(true);
            }
            else
            {
                await promptContext.Context.SendActivityAsync(InvalidQuantityErrorMessage);

                return(false);
            }
        }
Esempio n. 12
0
        public static int ParserNumberFromText(string text, int defValue = 0)
        {
            var number = defValue;

            const string DefaultCulture = Culture.Chinese;
            var          result         = NumberRecognizer.RecognizeNumber(text, DefaultCulture);

            if (result.Count > 0)
            {
                var resolution = result[0].Resolution;
                if (resolution.ContainsKey("value"))
                {
                    int.TryParse(resolution["value"].ToString(), out number);
                }
            }

            return(number);
        }
        protected override async Task <PromptRecognizerResult <string> > 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 <string>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity().Text.ToUpper();

                var regex = new Regex("INC[0-9]{7}");
                if (regex.IsMatch(message))
                {
                    result.Succeeded = true;
                    result.Value     = message;
                }

                if (!result.Succeeded)
                {
                    var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;
                    var results = NumberRecognizer.RecognizeNumber(message, culture);
                    if (results.Count > 0)
                    {
                        var text = results[0].Resolution["value"].ToString();
                        if (int.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            if (value >= 1 && value <= 9999999)
                            {
                                result.Succeeded = true;
                                result.Value     = $"INC{value:D7}";
                            }
                        }
                    }
                }
            }

            return(await Task.FromResult(result));
        }
Esempio n. 14
0
        private static bool IsValidNumberCurrency(string ammount, string currency)
        {
            if ((String.IsNullOrEmpty(currency)) || (String.IsNullOrEmpty(ammount)))
            {
                return(false);
            }
            if (NumberWithUnitRecognizer.RecognizeCurrency(ammount, Culture.French).Where(x => x.TypeName == "currency").FirstOrDefault() != null)
            {
                // var ret = res.Resolution["value"];
                return(true);
            }
            else
            {
                if (NumberRecognizer.RecognizeNumber(ammount, Culture.French).Where(x => x.TypeName == "number").FirstOrDefault() != null)
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 15
0
        protected override Task <InputState> OnRecognizeInput(DialogContext dc)
        {
            var input = dc.State.GetValue <object>(VALUE_PROPERTY);

            var culture = GetCulture(dc);
            var results = NumberRecognizer.RecognizeNumber(input.ToString(), culture);

            if (results.Count > 0)
            {
                // Try to parse value based on type
                var text = results[0].Resolution["value"].ToString();

                if (float.TryParse(text, out var value))
                {
                    input = value;
                }
                else
                {
                    return(Task.FromResult(InputState.Unrecognized));
                }
            }
            else
            {
                return(Task.FromResult(InputState.Unrecognized));
            }

            switch (this.OutputFormat)
            {
            case NumberOutputFormat.Float:
            default:
                dc.State.SetValue(VALUE_PROPERTY, input);
                break;

            case NumberOutputFormat.Integer:
                dc.State.SetValue(VALUE_PROPERTY, Math.Floor((float)input));
                break;
            }

            return(Task.FromResult(InputState.Valid));
        }
Esempio n. 16
0
        private static List <ModelResult> RecognizeNumberWithUnit(string utterance, string culture)
        {
            var number = NumberRecognizer.RecognizeNumber(utterance, culture);

            if (number.Any())
            {
                // Result when it matches with a number recognizer
                return(number);
            }
            else
            {
                // Analyze every option for numberWithUnit
                var results = new List <List <ModelResult> >();
                results.Add(NumberWithUnitRecognizer.RecognizeCurrency(utterance, culture));
                results.Add(NumberWithUnitRecognizer.RecognizeAge(utterance, culture));
                results.Add(NumberWithUnitRecognizer.RecognizeTemperature(utterance, culture));
                results.Add(NumberWithUnitRecognizer.RecognizeDimension(utterance, culture));

                // Filter the options that returned nothing and return the one that matched
                return(results.FirstOrDefault(r => r.Any()) ?? new List <ModelResult>());
            }
        }
Esempio n. 17
0
        protected override bool TryParse(IMessageActivity message, out int result)
        {
            result = 0;

            // Get Number for the specified culture
            var results = NumberRecognizer.RecognizeNumber(message.Text, this.culture);

            if (results.Count > 0)
            {
                if (results.First().TypeName == "number" &&
                    double.TryParse(results.First().Resolution["value"].ToString(), out double value))
                {
                    // Validate number
                    if (value < 1)
                    {
                        this.promptOptions.DefaultRetry = "I need to deliver at least one rose =)";
                        return(false);
                    }
                    else if (value > 100)
                    {
                        this.promptOptions.DefaultRetry = "You cannot order more than 100 roses per day. Sorry!";
                        return(false);
                    }
                    else if (value % 1 != 0)
                    {
                        this.promptOptions.DefaultRetry = "I need to send whole roses, not fractions of them. How many would you like to send?";
                        return(false);
                    }

                    // return as Int
                    result = Convert.ToInt32(value);
                    return(true);
                }
            }

            // No parse results
            this.promptOptions.DefaultRetry = "I'm sorry, that doesn't seem to be a valid quantity";
            return(false);
        }
Esempio n. 18
0
        public bool TryGetIntent(string input, IEnumerable <Intent> possibleIntents, out Intent intent)
        {
            var result = new List <ModelResult>();

            result.AddRange(NumberRecognizer.RecognizeNumber(input, RecognitionCulture));
            result.AddRange(NumberRecognizer.RecognizeOrdinal(input, RecognitionCulture));

            intent = default;

            if (result.Count != 1)
            {
                return(false);
            }

            var recognizedResolution = result[0].Resolution;

            if (recognizedResolution.TryGetValue("value", out var value) && int.TryParse(value?.ToString(), out var possibleIntentIndex))
            {
                intent = possibleIntents.FirstOrDefault(p => p.Index != default && p.Index == possibleIntentIndex);
            }

            return(intent != default);
        }
Esempio n. 19
0
        private static IEnumerable <ModelResult> ParseAll(string query, string culture)
        {
            return(MergeResults(
                       // Number recognizer will find any number from the input
                       NumberRecognizer.RecognizeNumber(query, culture),

                       // Ordinal number recognizer will find any ordinal number
                       NumberRecognizer.RecognizeOrdinal(query, culture),

                       // Percentage recognizer will find any number presented as percentage
                       NumberRecognizer.RecognizePercentage(query, culture),

                       // Number Range recognizer will find any cardinal or ordinal number range
                       NumberRecognizer.RecognizeNumberRange(query, culture),

                       // Age recognizer will find any age number presented
                       NumberWithUnitRecognizer.RecognizeAge(query, culture),

                       // Currency recognizer will find any currency presented
                       NumberWithUnitRecognizer.RecognizeCurrency(query, culture),

                       // Dimension recognizer will find any dimension presented
                       NumberWithUnitRecognizer.RecognizeDimension(query, culture),

                       // Temperature recognizer will find any temperature presented
                       NumberWithUnitRecognizer.RecognizeTemperature(query, culture),

                       // Datetime recognizer This model will find any Date even if its write in coloquial language
                       DateTimeRecognizer.RecognizeDateTime(query, culture),

                       // PhoneNumber recognizer will find any phone number presented
                       SequenceRecognizer.RecognizePhoneNumber(query, culture),

                       // Add IP recognizer - This recognizer will find any Ipv4/Ipv6 presented
                       SequenceRecognizer.RecognizeIpAddress(query, culture)
                       ));
        }
Esempio n. 20
0
        private bool TryGetNumber(string text, out decimal result)
        {
            // Get Number for the specified culture
            var results = NumberRecognizer.RecognizeNumber(text, Culture.English);

            if (results.Count > 0)
            {
                if (results.First().TypeName == "number" &&
                    decimal.TryParse(results.First().Resolution["value"].ToString(), out result))
                {
                    // Validate number
                    if (result < 0)
                    {
                        result = 0;
                        return(false);
                    }

                    return(true);
                }
            }

            result = 0;
            return(false);
        }
 protected override List <ModelResult> Recognize(string text, string culture)
 {
     return(NumberRecognizer.RecognizeNumber(text, culture));
 }
Esempio n. 22
0
        protected override Task <PromptRecognizerResult <T> > OnRecognizeAsync(ITurnContext turnContext, IDictionary <string, object> state, PromptOptions options)
        {
            if (turnContext == null)
            {
                throw new ArgumentNullException(nameof(turnContext));
            }

            var result = new PromptRecognizerResult <T>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity();
                var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;
                var results = NumberRecognizer.RecognizeNumber(message.Text, culture);
                if (results.Count > 0)
                {
                    // Try to parse value based on type
                    var text = results[0].Resolution["value"].ToString();
                    if (typeof(T) == typeof(float))
                    {
                        if (float.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(int))
                    {
                        if (int.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(long))
                    {
                        if (long.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(double))
                    {
                        if (double.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(decimal))
                    {
                        if (decimal.TryParse(text, out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else
                    {
                        throw new NotSupportedException($"NumberPrompt: type argument T of type 'typeof(T)' is not supported");
                    }
                }
            }

            return(Task.FromResult(result));
        }
Esempio n. 23
0
        /// <summary>
        /// Check the Forms Recognizer response - once complete map it to a POCO
        /// </summary>
        /// <param name="receipt"></param>
        /// <returns></returns>
        private async Task <Receipt> ReceiptAnalysisResult(Receipt receipt)
        {
            _logger.LogInformation($"Getting receipt analysis result: {receipt.Id}");
            using HttpResponseMessage response = await _httpClient.GetAsync(receipt.OCRRequestUrl);

            var ocrResponse = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                var serviceError = JsonSerializer.Deserialize <OCRError>(ocrResponse);
                _logger.LogError($"OCR Response status code: {response.IsSuccessStatusCode} : Error Code: {serviceError.error.code}, Error Message: {serviceError.error.message}");
                receipt.Status = serviceError.error.message;
                return(receipt);
            }

            try
            {
                var ocrResult = JsonSerializer.Deserialize <OCRResult>(ocrResponse);
                receipt.Status = ocrResult.status;
                _logger.LogInformation($"OCR response status: {receipt.Status}");

                if (receipt.Status.Equals(Constants.OCRServiceOperationStatus.Succeeded.ToString(), StringComparison.InvariantCultureIgnoreCase) ||
                    receipt.Status.Equals(Constants.OCRServiceOperationStatus.Failed.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    receipt.OCRComplete = true;
                }

                if (ocrResult.analyzeResult?.documentResults?.Length > 0)
                {
                    // Assuming only 1 receipt per scan
                    var ocrReceipt = ocrResult.analyzeResult?.documentResults.FirstOrDefault();

                    receipt.RequestComplete = DateTime.Now;
                    receipt.Merchant        = ocrReceipt.fields.MerchantName?.text;
                    receipt.Total           = Convert.ToDouble(ocrReceipt.fields.Total?.valueNumber);
                    receipt.SubTotal        = Convert.ToDouble(ocrReceipt.fields.Subtotal?.valueNumber);
                    receipt.Tax             = Convert.ToDouble(ocrReceipt.fields.Tax?.valueNumber);
                    receipt.Tip             = Convert.ToDouble(ocrReceipt.fields.Tip?.valueNumber);
                    //receipt.Address = ocrReceipt.fields.MerchantAddress?.text;

                    if (ocrReceipt.fields.TransactionTime != null &&
                        DateTime.TryParse(ocrReceipt.fields.TransactionTime.text, out DateTime time))
                    {
                        receipt.Time = time;
                    }

                    if (ocrReceipt.fields.TransactionDate != null)
                    {
                        // Dates could come in a variety of different formats and styles
                        var recognizerDate = DateTimeRecognizer.RecognizeDateTime(ocrReceipt.fields.TransactionDate.text, Culture.English);
                        if (recognizerDate.Any())
                        {
                            var recognizerValues = (List <Dictionary <string, string> >)recognizerDate.First().Resolution["values"];
                            if (recognizerValues.Any())
                            {
                                if (recognizerValues[0].TryGetValue("value", out string v))
                                {
                                    DateTime.TryParse(v, out DateTime outputDate);
                                    receipt.Date = outputDate;
                                }
                            }
                        }
                    }

                    // Extract line items
                    if (ocrReceipt.fields.Items?.valueArray?.Length > 0)
                    {
                        receipt.Items = new LineItem[ocrReceipt.fields.Items.valueArray.Length];
                        for (int i = 0; i < ocrReceipt.fields.Items.valueArray.Length; i++)
                        {
                            LineItem lineItem = new LineItem
                            {
                                Item = ocrReceipt.fields.Items?.valueArray[i].valueObject?.Name?.text,
                            };

                            if (ocrReceipt.fields.Items?.valueArray[i].valueObject?.Quantity?.text != null)
                            {
                                var quantityRecognizer = NumberRecognizer.RecognizeNumber(ocrReceipt.fields.Items.valueArray[i].valueObject.Quantity.text, Culture.English);
                                if (quantityRecognizer.Any())
                                {
                                    var recognizerValue = quantityRecognizer.FirstOrDefault().Resolution["value"];
                                    if (recognizerValue != null)
                                    {
                                        double.TryParse(recognizerValue.ToString(), out double outputQuantity);
                                        lineItem.Quantity = outputQuantity;
                                    }
                                }
                            }

                            // Total price could include currency symbol
                            if (ocrReceipt.fields.Items?.valueArray[i].valueObject?.TotalPrice?.text != null)
                            {
                                var numberRecognizer = NumberRecognizer.RecognizeNumber(ocrReceipt.fields.Items.valueArray[i].valueObject.TotalPrice.text, Culture.English);
                                if (numberRecognizer.Any())
                                {
                                    var recognizerValue = numberRecognizer.FirstOrDefault().Resolution["value"];
                                    if (recognizerValue != null)
                                    {
                                        double.TryParse(recognizerValue.ToString(), out double outputTotal);
                                        lineItem.TotalPrice = outputTotal;
                                    }
                                }
                            }
                            receipt.Items[i] = lineItem;
                        }
                    }
                    _logger.LogInformation($"Successful OCR receipt extraction Id: {receipt.Id} Total: {receipt.Total}");
                }
            }
            catch (Exception exp)
            {
                _logger.LogError($"Error deserialising the OCR response: {exp.Message}");
                receipt.Status = exp.Message;
            }
            return(receipt);
        }
        public SortedDictionary <string, object> RecognizeNumber(string query)
        {
            var result = NumberRecognizer.RecognizeNumber(query, _culture);

            return(result[0].Resolution);
        }
 public void RecognizeNumber(string text, string culture, string scale, string typeName)
 {
     NumberRecognizer.RecognizeNumber(text, culture);
 }
Esempio n. 26
0
        /// <summary>
        /// Attempts to recognize the user's input.
        /// </summary>
        /// <param name="turnContext">Context for the current turn of conversation with the user.</param>
        /// <param name="state">Contains state for the current instance of the prompt on the dialog stack.</param>
        /// <param name="options">A prompt options object constructed from the options initially provided
        /// in the call to <see cref="DialogContext.PromptAsync(string, PromptOptions, CancellationToken)"/>.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        /// <remarks>If the task is successful, the result describes the result of the recognition attempt.</remarks>
        protected override Task <PromptRecognizerResult <T> > 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 <T>();

            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                var message = turnContext.Activity.AsMessageActivity();
                var culture = turnContext.Activity.Locale ?? DefaultLocale ?? English;
                var results = NumberRecognizer.RecognizeNumber(message.Text, culture, NumberOptions.SuppressExtendedTypes);
                if (results.Count > 0)
                {
                    // Try to parse value based on type
                    var text = results[0].Resolution["value"].ToString();
                    if (typeof(T) == typeof(float))
                    {
                        if (float.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(int))
                    {
                        if (int.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(long))
                    {
                        if (long.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(double))
                    {
                        if (double.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                    else if (typeof(T) == typeof(decimal))
                    {
                        if (decimal.TryParse(text, NumberStyles.Any, new CultureInfo(culture), out var value))
                        {
                            result.Succeeded = true;
                            result.Value     = (T)(object)value;
                        }
                    }
                }
            }

            return(Task.FromResult(result));
        }
 private static List <ModelResult> DoNumber(string query, string culture)
 {
     return(NumberRecognizer.RecognizeNumber(query, culture).Where(i => i.Text.IsNumericValue()).ToList());
 }
Esempio n. 28
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
        }