public IPredictionResult Predict(PredictorType predictorType, double[][] training, double[][] test, int numberOfDays, int numberOfIterations, double likelihoodTolerance)
        {
            var model = (HiddenMarkovModelWeightedMixtureDistribution)HiddenMarkovModelFactory.GetModel <HiddenMarkovModelWeightedMixtureDistribution, Mixture <IMultivariateDistribution> >(new ModelCreationParameters <Mixture <IMultivariateDistribution> > {
                Pi = _pi, TransitionProbabilityMatrix = _transitionProbabilityMatrix, Emissions = _emission
            });                                                                                                                                                                                                                                                                                                                                            //new HiddenMarkovModelState<IMultivariateDistribution>(_pi, _transitionProbabilityMatrix, _emission);

            model.Normalized = Normalized;
            var request = new PredictionRequest();

            request.TrainingSet  = training;
            request.TestSet      = test;
            request.NumberOfDays = numberOfDays;
            request.Tolerance    = PREDICTION_LIKELIHOOD_TOLERANCE;
            request.TrainingLikelihoodTolerance = likelihoodTolerance;
            request.NumberOfTrainingIterations  = numberOfIterations;

            var predictor = HiddenMarkovModelPredictorFactory.GetPredictor(predictorType);

            return(predictor.Predict(model, request));
        }
        private static PredictionRequest BuildRequest(ChangedFiles changedFiles)
        {
            var request = new PredictionRequest();

            foreach (var loopFile in changedFiles.Files)
            {
                request.Items.Add(new PredictionRequestFile
                {
                    Author  = loopFile.Author,
                    Path    = loopFile.Path,
                    OldPath = loopFile.OldPath,
                    NumberOfModifiedLines = loopFile.NumberOfModifiedLines,
                    CCMMd  = loopFile.CCMMd,
                    CCMAvg = loopFile.CCMAvg,
                    CCMMax = loopFile.CCMMax
                });
            }

            return(request);
        }
        /// <summary>
        /// Given a trackID, gets its audio features then passes that
        /// to the Machine Learning Web Service
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <JsonResult> GetPrediction(string id)
        {
            Task <JObject> audioFeatures = SpotifyAPIs.GetSpotifyAudioFeaturesAsync(id);
            Task <int>     trackYear     = SpotifyAPIs.GetTrackReleaseYear(id);
            await Task.WhenAll(audioFeatures, trackYear);

            string response;

            if (audioFeatures.Result != null && trackYear.Result != 0)
            {
                var scoreRequest = PredictionRequest.CreateRequest(audioFeatures.Result, trackYear.Result);
                response = await CallMlService(scoreRequest);
            }
            else
            {
                response = "Try again: Spotify Web APIs returned an error";
            }

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
Beispiel #4
0
        public async Task <string> PredictAsync(PredictionRequest request)
        {
            if (_model == null)
            {
                _model = await PredictionModel.ReadAsync <BankStatementLineItem, PredictedLabel>(
                    PredictionModelWrapper.GetModel());
            }

            var item = new BankStatementLineItem
            {
                Description = request.Description,
                Amount      = request.Amount,
                //AccountNumber = request.AccountNumber,
                //AccountName = request.AccountName,
                Bank = request.Bank
                       //TransactionUtcDate = request.TransactionUtcDate,
                       //Notes = request.Notes,
                       //Tags = request.Tags
            };

            await SemaphoreSlim.WaitAsync();

            PredictedLabel predicted = null;

            try
            {
                predicted = _model.Predict(item);
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "error {err}", request);
                throw;
            }
            finally
            {
                //When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready, or else we will end up with a Semaphore that is forever locked.
                SemaphoreSlim.Release();
            }

            return(predicted.SubCategory);
        }
        public void Evaluate_HMMMultivariateAndFTSESeriesLength20_ErrorEstimatorCalculated()
        {
            var util   = new TestDataUtils();
            var series = util.GetSvcData(util.FTSEFilePath, new DateTime(2010, 12, 18), new DateTime(2011, 12, 18));
            var test   = util.GetSvcData(util.FTSEFilePath, new DateTime(2011, 12, 18), new DateTime(2012, 01, 18));

            var model = (HiddenMarkovModelMultivariateGaussianDistribution)HiddenMarkovModelFactory.GetModel(new ModelCreationParameters <IMultivariateDistribution>()
            {
                NumberOfStates = _NumberOfStates
            });

            model.Normalized = true;
            model.Train(series, _NumberOfIterations, _LikelihoodTolerance);

            var pred    = new ViterbiBasedPredictor();
            var request = new PredictionRequest {
                TrainingSet = series, NumberOfDays = 20, TestSet = test
            };

            pred.NumberOfIterations  = _NumberOfIterations;
            pred.LikelihoodTolerance = _LikelihoodTolerance;
            var predictions  = pred.Predict(model, request);
            var errorRequest = new EvaluationRequest
            {
                EstimatorType        = ErrorEstimatorType.Value,
                PredictionParameters = request,
                PredictionToEvaluate = predictions
            };

            var errorEstimation = pred.Evaluate(errorRequest);

            for (int i = 0; i < series[0].Length; i++)
            {
                Assert.IsTrue(errorEstimation.CumulativeForecastError[i] > 0);
                Assert.IsTrue(errorEstimation.MeanAbsoluteDeviation[i] > 0);
                Assert.IsTrue(errorEstimation.MeanAbsolutePercentError[i] > 0);
                Assert.IsTrue(errorEstimation.MeanError[i] > 0);
                Assert.IsTrue(errorEstimation.MeanSquaredError[i] > 0);
                Assert.IsTrue(errorEstimation.RootMeanSquaredError[i] > 0);
            }
        }
        static async Task <PredictionResponse> GetPredictionAsync()
        {
            // Get client
            using (var luisClient = CreateClient())
            {
                // Change the query text to test the various options presented in the unit text
                var predictionRequest = new PredictionRequest
                {
                    Query = "turn on the light",
                };

                // get prediction
                return(await luisClient.Prediction.GetSlotPredictionAsync(
                           Guid.Parse(appId),
                           slotName : "production",
                           predictionRequest,
                           verbose : false,
                           showAllIntents : false,
                           log : true));
            }
        }
Beispiel #7
0
        public async Task <IActionResult> Search(PredictionRequest request)
        {
            Guard.AgainstNull(request);

            using (LogContext.PushProperty("request", request.ToJson()))
                using (LogContext.PushProperty("requestId", request.Id))
                {
                    try
                    {
                        var result = await _predictor.PredictAsync(request);

                        return(Ok(result));
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        Log.Warning(e, "PredictionController error {request}", request.ToJson());
                        return(NoContent());
                    }
                }
        }
        public void Predict_HMMMultivariateAndFTSESeriesLength1_PredictedOneDay()
        {
            var util   = new TestDataUtils();
            var series = util.GetSvcData(util.FTSEFilePath, new DateTime(2010, 12, 18), new DateTime(2011, 12, 18));

            var model = (HiddenMarkovModelMultivariateGaussianDistribution)HiddenMarkovModelFactory.GetModel(new ModelCreationParameters <IMultivariateDistribution>()
            {
                NumberOfStates = _NumberOfStates
            });

            model.Normalized = true;
            model.Train(series, _NumberOfIterations, _LikelihoodTolerance);
            var request = new PredictionRequest();

            request.TrainingSet  = series;
            request.NumberOfDays = 1;

            var pred = new ViterbiBasedPredictor();
            var res  = pred.Predict(model, request);

            Assert.AreEqual(1, res.Predicted.Length);
        }
        public PredictionResult PredictNumberByGrpc([FromBody] PredictionRequest model)
        {
            try
            {
                var stopWatch = Stopwatch.StartNew();
                var imageData = CreateImageDataFromModel(model.ImageData);

                //Init predict request
                var request = new PredictRequest()
                {
                    ModelSpec = new ModelSpec()
                    {
                        Name = "mnist_v1", SignatureName = "serving_default"
                    }
                };
                request.Inputs.Add("flatten_input", TensorBuilder.CreateTensorFromImage(imageData, 255.0f));

                //Create grpc request
                var channel         = new Channel(_configuration.GetSection("TfServer")["GrpcServerUrl"], ChannelCredentials.Insecure);
                var client          = new PredictionService.PredictionServiceClient(channel);
                var predictResponse = client.Predict(request);

                //Process response
                var maxValue       = predictResponse.Outputs["dense_1"].FloatVal.Max();
                var predictedValue = predictResponse.Outputs["dense_1"].FloatVal.IndexOf(maxValue);

                return(new PredictionResult()
                {
                    Success = true,
                    Results = predictResponse.Outputs["dense_1"].FloatVal.Select(x => x).ToList(),
                    PredictedValue = predictedValue.ToString(),
                    DebugText = $"Total time: {stopWatch.ElapsedMilliseconds} ms"
                });
            }
            catch (Exception ex)
            {
                return(ErrorResult(ex));
            }
        }
        private async Task <PredictionResponse> getLUISPredictionAsync(string query)
        {
            using (var client = new LUISRuntimeClient(credentials, new DelegatingHandler[] { })
            {
                Endpoint = _luisPredictionEndpoint
            }) {
                var appId    = Guid.Parse(_luisAppId);
                var slotName = "production";

                var options = new PredictionRequestOptions()
                {
                    DatetimeReference      = DateTime.Parse("2020-01-01"),
                    PreferExternalEntities = true
                };

                var predictionRequest = new PredictionRequest(query, options);

                var result = await client.Prediction.GetSlotPredictionAsync(appId, slotName, predictionRequest, true, true, true);

                return(result);
            }
        }
Beispiel #11
0
        private async void UpdatePredictionAsync()
        {
            bool isValid = await ValidateDataAsync();

            if (!isValid)
            {
                return;
            }

            string url = App.Current.Resources["UrlAPI"].ToString();

            if (!_apiService.CheckConnection())
            {
                await App.Current.MainPage.DisplayAlert(Languages.Error, Languages.ConnectionError, Languages.Accept);

                return;
            }

            UserResponse  user  = JsonConvert.DeserializeObject <UserResponse>(Settings.User);
            TokenResponse token = JsonConvert.DeserializeObject <TokenResponse>(Settings.Token);

            PredictionRequest request = new PredictionRequest
            {
                GoalsLocal   = GoalsLocal.Value,
                GoalsVisitor = GoalsVisitor.Value,
                MatchId      = Match.Id,
                UserId       = new Guid(user.Id),
                CultureInfo  = Languages.Culture
            };

            //manda el post al método predicción
            Response response = await _apiService.MakePredictionAsync(url, "/api", "/Predictions", request, "bearer", token.Token);

            if (!response.IsSuccess)
            {
                await App.Current.MainPage.DisplayAlert(Languages.Error, response.Message, Languages.Accept);
            }
        }
        public async Task <List <string> > GetSymbols(dynamic config)
        {
            var highestPredictionConfig = config as HighestPredictionConfig;
            var symbolDifferences       = new List <(string, double)>();

            foreach (var symbol in highestPredictionConfig.pool.symbols)
            {
                var req = new PredictionRequest {
                    Symbol      = symbol,
                    TrendLength = highestPredictionConfig.trend_length
                };

                try {
                    var res   = _predictorService.Predict(req);
                    var quote = await _datasourceService.GetQuote(symbol);

                    Console.WriteLine($"{symbol}: {res.ValDenorm} vs {quote.latestPrice}");

                    symbolDifferences.Add((symbol, (res.ValDenorm - quote.latestPrice) / quote.latestPrice));
                } catch (Exception e) {
                    Console.WriteLine($"Error getting symbol data: {e}");
                }
            }

            symbolDifferences.Sort((r1, r2) => r1.Item2.CompareTo(r2.Item2));

            // Best performing at start
            return(symbolDifferences
                   .Where(
                       diff =>
                       diff.Item2 >= highestPredictionConfig.filters.percent_change_floor &&
                       diff.Item2 <= highestPredictionConfig.filters.percent_change_ceiling
                       )
                   .Select((r) => r.Item1)
                   .Reverse()
                   .ToList());
        }
Beispiel #13
0
        public static IEnumerable <PredictionRequest> ToPredictionRequests(this BankStatementDownload download)
        {
            if (download == null)
            {
                return(null);
            }
            if (download.Error != null)
            {
                return(null);
            }

            var list = new List <PredictionRequest>();

            foreach (var account in download.FetchAllResponse.Accounts)
            {
                foreach (var item in account.StatementData.Details)
                {
                    var pr = new PredictionRequest
                    {
                        Id                 = Guid.NewGuid(),
                        Description        = item.Text,
                        AccountType        = AccountTypeConverter.Convert(account.AccountType),
                        Amount             = Convert.ToDouble(item.Amount),
                        Bank               = account.Institution,
                        TransactionUtcDate = item.DateObj.Date.UtcDateTime
                    };

                    list.Add(pr);
                }
            }

            var missing = list.Where(x => string.IsNullOrEmpty(x.Description));

            Debug.Assert(!missing.Any());
            return(list);
        }
Beispiel #14
0
        public async Task <PredictionResponse> QueryAsync(PredictionRequest predictionRequest, CancellationToken cancellationToken)
        {
            while (true)
            {
                try
                {
                    this.TraceQueryTarget();
                    if (this.LuisConfiguration.DirectVersionPublish)
                    {
                        return(await this.RuntimeClient.Prediction.GetVersionPredictionAsync(
                                   Guid.Parse(this.LuisConfiguration.AppId),
                                   this.LuisConfiguration.VersionId,
                                   predictionRequest,
                                   verbose : true,
                                   log : false,
                                   cancellationToken : cancellationToken)
                               .ConfigureAwait(false));
                    }

                    return(await this.RuntimeClient.Prediction.GetSlotPredictionAsync(
                               Guid.Parse(this.LuisConfiguration.AppId),
                               this.LuisConfiguration.SlotName,
                               predictionRequest,
                               verbose : true,
                               log : false,
                               cancellationToken : cancellationToken)
                           .ConfigureAwait(false));
                }
                catch (ErrorException ex)
                    when(IsTransientStatusCode(ex.Response.StatusCode))
                    {
                        Logger.LogTrace($"Received HTTP {(int)ex.Response.StatusCode} result from Cognitive Services. Retrying.");
                        await Task.Delay(ThrottleQueryDelay, cancellationToken).ConfigureAwait(false);
                    }
            }
        }
Beispiel #15
0
        private async static void GetPrediction(LUISRuntimeClient cliente, string mensaje)
        {
            var kbLUIS  = "30018600-f54e-46ce-a650-954172c06484";
            var request = new PredictionRequest {
                Query = mensaje
            };
            var result = await cliente.Prediction.GetSlotPredictionAsync(Guid.Parse(kbLUIS), slotName : "Staging", request);

            var prediction = result.Prediction;

            switch (prediction.TopIntent)
            {
            case "EnviaCorreo":
                Console.WriteLine("La intención es enviar correo");
                var entities = prediction.Entities;
                var correo   = entities["Correo"];
                Console.WriteLine($"Enviando correo a {((JArray)correo)[0]}");
                break;

            default:
                Console.WriteLine("No se cuál es la intención del usuario");
                break;
            }
        }
        public async Task <IActionResult> PostPrediction([FromBody] PredictionRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CultureInfo cultureInfo = new CultureInfo(request.CultureInfo);

            Resource.Culture = cultureInfo;

            MatchEntity matchEntity = await _context.Matches.FindAsync(request.MatchId);

            if (matchEntity == null)
            {
                return(BadRequest(Resource.MatchDoesntExists));
            }

            if (matchEntity.IsClosed)
            {
                return(BadRequest(Resource.MatchAlreadyClosed));
            }

            UserEntity userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest(Resource.UserDoesntExists));
            }

            if (matchEntity.Date <= DateTime.UtcNow)
            {
                return(BadRequest(Resource.MatchAlreadyStarts));
            }

            PredictionEntity predictionEntity = await _context.Predictions
                                                .FirstOrDefaultAsync(p => p.User.Id == request.UserId.ToString() && p.Match.Id == request.MatchId);

            if (predictionEntity == null)
            {
                predictionEntity = new PredictionEntity
                {
                    GoalsLocal   = request.GoalsLocal,
                    GoalsVisitor = request.GoalsVisitor,
                    Match        = matchEntity,
                    User         = userEntity
                };

                _context.Predictions.Add(predictionEntity);
            }
            else
            {
                predictionEntity.GoalsLocal   = request.GoalsLocal;
                predictionEntity.GoalsVisitor = request.GoalsVisitor;
                _context.Predictions.Update(predictionEntity);
            }

            await _context.SaveChangesAsync();

            return(NoContent());
        }
Beispiel #17
0
        public static async Task Main()
        {
            // <VariablesYouChange>
            var key = "REPLACE-WITH-YOUR-AUTHORING-KEY";

            var authoringResourceName  = "REPLACE-WITH-YOUR-AUTHORING-RESOURCE-NAME";
            var predictionResourceName = "REPLACE-WITH-YOUR-PREDICTION-RESOURCE-NAME";
            // </VariablesYouChange>

            // <VariablesYouDontNeedToChangeChange>
            var authoringEndpoint  = String.Format("https://{0}.cognitiveservices.azure.com/", authoringResourceName);
            var predictionEndpoint = String.Format("https://{0}.cognitiveservices.azure.com/", predictionResourceName);

            var appName    = "Contoso Pizza Company";
            var versionId  = "0.1";
            var intentName = "OrderPizzaIntent";
            // </VariablesYouDontNeedToChangeChange>

            // <AuthoringCreateClient>
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(key);
            var client      = new LUISAuthoringClient(credentials)
            {
                Endpoint = authoringEndpoint
            };
            // </AuthoringCreateClient>

            // Create app
            var appId = await CreateApplication(client, appName, versionId);

            // <AddIntent>
            await client.Model.AddIntentAsync(appId, versionId, new ModelCreateObject()
            {
                Name = intentName
            });

            // </AddIntent>

            // Add Entities
            await AddEntities(client, appId, versionId);

            // Add Labeled example utterance
            await AddLabeledExample(client, appId, versionId, intentName);

            // <TrainAppVersion>
            await client.Train.TrainVersionAsync(appId, versionId);

            while (true)
            {
                var status = await client.Train.GetStatusAsync(appId, versionId);

                if (status.All(m => m.Details.Status == "Success"))
                {
                    // Assumes that we never fail, and that eventually we'll always succeed.
                    break;
                }
            }
            // </TrainAppVersion>

            // <PublishVersion>
            await client.Apps.PublishAsync(appId, new ApplicationPublishObject { VersionId = versionId, IsStaging = false });

            // </PublishVersion>

            // <PredictionCreateClient>
            var runtimeClient = new LUISRuntimeClient(credentials)
            {
                Endpoint = predictionEndpoint
            };
            // </PredictionCreateClient>

            // <QueryPredictionEndpoint>
            // Production == slot name
            var request = new PredictionRequest {
                Query = "I want two small pepperoni pizzas with more salsa"
            };
            var prediction = await runtimeClient.Prediction.GetSlotPredictionAsync(appId, "Production", request);

            Console.Write(JsonConvert.SerializeObject(prediction, Formatting.Indented));
            // </QueryPredictionEndpoint>
        }
Beispiel #18
0
        public void Prediction_Slot()
        {
            UseClientFor(async client =>
            {
                var utterance = "today this is a test with post";
                var slotName  = "production";

                var requestOptions = new PredictionRequestOptions
                {
                    DatetimeReference   = DateTime.Parse("2019-01-01"),
                    OverridePredictions = true
                };

                var externalResolution = JObject.FromObject(new { text = "post", external = true });
                var externalEntities   = new[]
                {
                    new ExternalEntity
                    {
                        EntityName   = "simple",
                        StartIndex   = 26,
                        EntityLength = 4,
                        Resolution   = externalResolution
                    }
                };

                var dynamicLists = new[]
                {
                    new DynamicList
                    {
                        ListEntityName = "list",
                        RequestLists   = new[]
                        {
                            new RequestList
                            {
                                Name          = "test",
                                CanonicalForm = "testing",
                                Synonyms      = new[] { "this" }
                            }
                        }
                    }
                };

                var predictionRequest = new PredictionRequest
                {
                    Query            = utterance,
                    Options          = requestOptions,
                    ExternalEntities = externalEntities,
                    DynamicLists     = dynamicLists
                };

                var result = await client.Prediction.GetSlotPredictionAsync(
                    Guid.Parse(appId),
                    slotName,
                    predictionRequest,
                    verbose: true,
                    showAllIntents: true);

                var prediction = result.Prediction;
                Assert.Equal(utterance, result.Query);
                Assert.Equal(utterance, prediction.NormalizedQuery);
                Assert.Equal("intent", prediction.TopIntent);
                Assert.Equal(2, prediction.Intents.Count);
                Assert.Equal(4, prediction.Entities.Count);
                Assert.Contains("datetimeV2", prediction.Entities.Keys);
                Assert.Contains("simple", prediction.Entities.Keys);
                Assert.Contains("list", prediction.Entities.Keys);
                Assert.Contains("$instance", prediction.Entities.Keys);

                // Test external resolution
                var actualResolution = (prediction.Entities["simple"] as JArray).Single();
                Assert.True(JToken.DeepEquals(externalResolution, actualResolution));

                var topIntent = prediction.Intents[prediction.TopIntent];
                Assert.True(topIntent.Score > 0.5);

                Assert.Equal("positive", prediction.Sentiment.Label);
                Assert.True(prediction.Sentiment.Score > 0.5);

                // dispatch
                var child = topIntent.ChildApp;
                Assert.Equal(utterance, child.NormalizedQuery);
                Assert.Equal("None", child.TopIntent);
                Assert.Equal(1, child.Intents.Count);
                Assert.Equal(2, child.Entities.Count);
                Assert.Contains("datetimeV2", child.Entities.Keys);
                Assert.Contains("$instance", child.Entities.Keys);

                var dispatchTopIntent = child.Intents[child.TopIntent];
                Assert.True(dispatchTopIntent.Score > 0.5);

                Assert.Equal("positive", child.Sentiment.Label);
                Assert.True(child.Sentiment.Score > 0.5);
            });
        }
 public double GetResult([FromBody] PredictionRequest predictionRequest)
 {
     return(winPredictorService.GetResult(predictionRequest));
 }
Beispiel #20
0
        protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> context, CancellationToken cancellationToken)
        {
            var message = context.Activity;

            // To quickly test the bot after deploy to ensure the version we want is available.
            if (message.Text.ToLower().Equals("bot version"))
            {
                var version = typeof(SupportBot).Assembly.GetName().Version;

                var replyText = $"Art Gallery Support Assistant v{version?.Major}.{version?.Minor}.{version?.Build}.{version?.Revision}";
                await context.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);

                return;
            }

            // ******************************* Cognitive Services - Text Analysis API ******************************* //

            using var textAnalyticsClient = new TextAnalyticsClient(new TextAnalysisServiceClientCredentials(SubscriptionKeys.TextAnalysisServiceKey))
                  {
                      Endpoint = "https://eastus.api.cognitive.microsoft.com/"
                  };

            var langResult = await textAnalyticsClient.DetectLanguageAsync(false, new LanguageBatchInput(new List <LanguageInput>
            {
                new LanguageInput(id: "1", text: message.Text)
            }), cancellationToken : cancellationToken);

            await context.TraceActivityAsync("OnMessageActivity Trace", langResult, "LanguageResult", cancellationToken : cancellationToken);

            var languageCode = string.Empty;

            foreach (var document in langResult.Documents)
            {
                // Pick the language with the highest score
                var bestLanguage = document.DetectedLanguages?.OrderByDescending(l => l.Score).FirstOrDefault();

                if (string.IsNullOrEmpty(languageCode) && bestLanguage != null)
                {
                    languageCode = bestLanguage.Iso6391Name.ToLower();
                    await context.TraceActivityAsync("OnMessageActivity Trace", languageCode, "string", cancellationToken : cancellationToken);
                }
            }

            // If we couldn't detect language
            if (string.IsNullOrEmpty(languageCode))
            {
                var replyText = "We could not determine what language you're using. Please try again.";
                await context.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);

                return;
            }


            // ******************************* Cognitive Services - Text Translation API ******************************* //

            var query = string.Empty;

            // If the detected language was not English, translate it before sending to LUIS
            if (languageCode != "en")
            {
                try
                {
                    using var translationClient = new TextTranslationServiceClient(SubscriptionKeys.TextTranslationServiceKey);

                    var result = await translationClient.TranslateAsync(message.Text, "en");

                    var translatedQuery = result?.Translations?.FirstOrDefault()?.Text;

                    if (!string.IsNullOrEmpty(translatedQuery))
                    {
                        query = translatedQuery;
                    }
                }
                catch (Exception ex)
                {
                    var replyText = $"RespondWithTranslatedReply Exception: {ex.Message}";
                    await context.SendActivityAsync(MessageFactory.Text(replyText, replyText), cancellationToken);
                }
            }
            else
            {
                query = message.Text;
            }


            // ******************************* Cognitive Services - LUIS (Natural Language Understanding) API ******************************* //

            using var luisClient = new LUISRuntimeClient(new ApiKeyServiceClientCredentials(SubscriptionKeys.LuisPredictionKey));

            luisClient.Endpoint = SubscriptionKeys.LuisEndpoint;

            // Prepare a prediction request
            var predictionRequest = new PredictionRequest
            {
                Query = query
            };

            // Request a prediction, returns a PredictionResponse
            var predictionResponse = await luisClient.Prediction.GetSlotPredictionAsync(
                Guid.Parse(SubscriptionKeys.LuisAppId),
                "production",
                predictionRequest,
                verbose : true,
                showAllIntents : true,
                log : true,
                cancellationToken : cancellationToken);

            // You will get a full list of intents. For the purposes of this demo, we'll just use the highest scoring intent.
            var topScoringIntent = predictionResponse.Prediction.TopIntent;

            // Respond to the user depending on the detected intent of their query
            var respondedToQuery = await RespondWithEnglishAsync(context, topScoringIntent, languageCode, cancellationToken);


            // ******************************* Cognitive Services - Sentiment Analysis  ******************************* //

            // Only evaluate sentiment if we've given a meaningful reply (and not connection or service error messages).
            if (respondedToQuery)
            {
                // Use Text Analytics Sentiment analysis
                var sentimentResult = await textAnalyticsClient.SentimentAsync(
                    multiLanguageBatchInput : new MultiLanguageBatchInput(new List <MultiLanguageInput>
                {
                    new MultiLanguageInput(id: "1", text: query, language: languageCode)
                }),
                    cancellationToken : cancellationToken);


                if (sentimentResult?.Documents?.Count > 0)
                {
                    await context.TraceActivityAsync("SentimentAsync Trace", sentimentResult.Documents[0], "SentimentBatchResultItem", cancellationToken : cancellationToken);

                    SentimentBatchResultItem sentimentItem = sentimentResult.Documents[0];

                    // Use the sentiment score to determine if we need to react, the range is 0 (angriest) to 1 (happiest)
                    await EvaluateAndRespondToSentimentAsync(context, sentimentItem, languageCode, cancellationToken);
                }
            }
        }
        /// <summary>
        /// Gets the predictions for an application version.
        /// </summary>
        /// <param name='appId'>
        /// The application ID.
        /// </param>
        /// <param name='versionId'>
        /// The application version ID.
        /// </param>
        /// <param name='predictionRequest'>
        /// The prediction request parameters.
        /// </param>
        /// <param name='verbose'>
        /// Indicates whether to get extra metadata for the entities predictions or
        /// not.
        /// </param>
        /// <param name='showAllIntents'>
        /// Indicates whether to return all the intents in the response or just the top
        /// intent.
        /// </param>
        /// <param name='log'>
        /// Indicates whether to log the endpoint query or not.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <HttpOperationResponse <PredictionResponse> > GetVersionPredictionWithHttpMessagesAsync(System.Guid appId, string versionId, PredictionRequest predictionRequest, bool?verbose = default(bool?), bool?showAllIntents = default(bool?), bool?log = default(bool?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.Endpoint == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.Endpoint");
            }
            if (versionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "versionId");
            }
            if (predictionRequest == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "predictionRequest");
            }
            if (predictionRequest != null)
            {
                predictionRequest.Validate();
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("appId", appId);
                tracingParameters.Add("versionId", versionId);
                tracingParameters.Add("verbose", verbose);
                tracingParameters.Add("showAllIntents", showAllIntents);
                tracingParameters.Add("log", log);
                tracingParameters.Add("predictionRequest", predictionRequest);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "GetVersionPrediction", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri;
            var _url     = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "apps/{appId}/versions/{versionId}/predict";

            _url = _url.Replace("{Endpoint}", Client.Endpoint);
            _url = _url.Replace("{appId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(appId, Client.SerializationSettings).Trim('"')));
            _url = _url.Replace("{versionId}", System.Uri.EscapeDataString(versionId));
            List <string> _queryParameters = new List <string>();

            if (verbose != null)
            {
                _queryParameters.Add(string.Format("verbose={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(verbose, Client.SerializationSettings).Trim('"'))));
            }
            if (showAllIntents != null)
            {
                _queryParameters.Add(string.Format("show-all-intents={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(showAllIntents, Client.SerializationSettings).Trim('"'))));
            }
            if (log != null)
            {
                _queryParameters.Add(string.Format("log={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(log, Client.SerializationSettings).Trim('"'))));
            }
            if (_queryParameters.Count > 0)
            {
                _url += "?" + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("POST");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            if (predictionRequest != null)
            {
                _requestContent      = Rest.Serialization.SafeJsonConvert.SerializeObject(predictionRequest, Client.SerializationSettings);
                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new HttpOperationResponse <PredictionResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <PredictionResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
        public async Task <PredictionResponse> Predict(string query)
        {
            PredictionRequest predictionRequest = new PredictionRequest(query);

            return(await _recognizer.Prediction.GetSlotPredictionAsync(appId, "Production", predictionRequest, true, true));
        }
 public async Task <IHttpActionResult> GetPredictions(PredictionRequest predictionRequest)
 {
     return(this.Json(await this.client.Predict(await this.requestPrepareService.Prepare(predictionRequest))));
 }
Beispiel #24
0
        public async Task <SpeechPredictionResponse> RecognizeSpeechAsync(string speechFile, PredictionRequest predictionRequest, CancellationToken cancellationToken)
        {
            if (this.LuisConfiguration.SpeechKey == null)
            {
                throw new InvalidOperationException("Must provide speech key to perform speech intent recognition.");
            }

            var request = (HttpWebRequest)WebRequest.Create(this.LuisConfiguration.SpeechEndpoint);

            request.Method      = "POST";
            request.ContentType = "audio/wav; codec=audio/pcm; samplerate=16000";
            request.ServicePoint.Expect100Continue = true;
            request.SendChunked = true;
            request.Accept      = "application/json";
            request.Headers.Add("Ocp-Apim-Subscription-Key", this.LuisConfiguration.SpeechKey);

            JObject responseJson;

            using (var fileStream = File.OpenRead(speechFile))
                using (var requestStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
                {
                    await fileStream.CopyToAsync(requestStream).ConfigureAwait(false);

                    using (var response = await request.GetResponseAsync().ConfigureAwait(false))
                        using (var streamReader = new StreamReader(response.GetResponseStream()))
                        {
                            var responseText = await streamReader.ReadToEndAsync().ConfigureAwait(false);

                            responseJson = JObject.Parse(responseText);
                        }
                }

            if (responseJson.Value <string>("RecognitionStatus") != "Success")
            {
                throw new InvalidOperationException($"Received error from LUIS speech service: {responseJson}");
            }

            var speechMatch = responseJson["NBest"].OrderByDescending(t => t.Value <double?>("Confidence") ?? 0.0).First();
            var text        = speechMatch.Value <string>("Display");
            var textScore   = speechMatch.Value <double?>("Confidence");

            var speechPredictionRequest = new PredictionRequest
            {
                Query            = text,
                DynamicLists     = predictionRequest?.DynamicLists,
                ExternalEntities = predictionRequest?.ExternalEntities,
                Options          = predictionRequest?.Options,
            };

            var predictionResponse = await this.QueryAsync(speechPredictionRequest, cancellationToken).ConfigureAwait(false);

            return(new SpeechPredictionResponse(predictionResponse, textScore));
        }
Beispiel #25
0
        public PredictionResult PredictNumber([FromBody] PredictionRequest model)
        {
            try
            {
                //Load Bitmap from input base64
                Bitmap convertedImage = null;

                using (var str = new MemoryStream(Convert.FromBase64String(model.ImageData)))
                {
                    str.Position = 0;
                    using (var bmp = Image.FromStream(str))
                    {
                        //Resize image and convert to rgb24
                        convertedImage = ImageUtils.ResizeImage(bmp, 28, 28, 280, 280);
                    }
                }

                //Create channel
                var channel = new Channel(_configuration.GetSection("TfServer")["ServerUrl"], ChannelCredentials.Insecure);
                var client  = new PredictionService.PredictionServiceClient(channel);

                //Init predict request
                var request = new PredictRequest()
                {
                    ModelSpec = new ModelSpec()
                    {
                        Name = "mnist", SignatureName = ModelMethodClasses.PredictImages
                    }
                };

                //Convert image to 28x28 8bit per pixel image data array
                var imageData = ImageUtils.ConvertImageStreamToDimArrays(convertedImage);

                var textDebug = TextUtils.RenderImageData(imageData);

                //add image tensor
                request.Inputs.Add("images", TensorBuilder.CreateTensorFromImage(imageData, 255.0f));
                //add keep_prob tensor
                request.Inputs.Add("keep_prob", TensorBuilder.CreateTensor(1.0f));

                var predictResponse = client.Predict(request);

                var maxValue       = predictResponse.Outputs["scores"].FloatVal.Max();
                var predictedValue = predictResponse.Outputs["scores"].FloatVal.IndexOf(maxValue);

                return(new PredictionResult()
                {
                    Success = true,
                    Results = predictResponse.Outputs["scores"].FloatVal.Select(x => x).ToList(),
                    PredictedNumber = predictedValue,
                    DebugText = textDebug
                });
            }
            catch (Exception ex)
            {
                return(new PredictionResult()
                {
                    Success = false,
                    ErrorMessage = ex.ToString()
                });
            }
        }
Beispiel #26
0
        // It's always a good idea to access services in an async fashion
        public static async Task Main()
        {
            var authoringEndpoint  = String.Format("https://{0}.cognitiveservices.azure.com/", AUTHORING_RESOURCE_NAME);
            var predictionEndpoint = String.Format("https://{0}.cognitiveservices.azure.com/", PREDICTION_RESOURCE_NAME);

            var appName    = "Contoso Pizza Company";
            var versionId  = "0.1";
            var intentName = "OrderPizza";

            // Authenticate the client
            Console.WriteLine("Authenticating the client...");
            var credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(AUTHORING_KEY);
            var client      = new LUISAuthoringClient(credentials)
            {
                Endpoint = authoringEndpoint
            };

            // Create a LUIS app
            var newApp = new ApplicationCreateObject
            {
                Culture          = "en-us",
                Name             = appName,
                InitialVersionId = versionId
            };

            Console.WriteLine("Creating a LUIS app...");
            var appId = await client.Apps.AddAsync(newApp);

            // Create intent for the app
            Console.WriteLine("Creating intent for the app...");
            await client.Model.AddIntentAsync(appId, versionId, new ModelCreateObject()
            {
                Name = intentName
            });

            // Create entities for the app
            Console.WriteLine("Creating entities for the app...");

            // Add Prebuilt entity
            await client.Model.AddPrebuiltAsync(appId, versionId, new[] { "number" });

            // Define ml entity with children and grandchildren
            var mlEntityDefinition = new EntityModelCreateObject
            {
                Name     = "Pizza order",
                Children = new[]
                {
                    new ChildEntityModelCreateObject
                    {
                        Name     = "Pizza",
                        Children = new[]
                        {
                            new ChildEntityModelCreateObject {
                                Name = "Quantity"
                            },
                            new ChildEntityModelCreateObject {
                                Name = "Type"
                            },
                            new ChildEntityModelCreateObject {
                                Name = "Size"
                            }
                        }
                    },
                    new ChildEntityModelCreateObject
                    {
                        Name     = "Toppings",
                        Children = new[]
                        {
                            new ChildEntityModelCreateObject {
                                Name = "Type"
                            },
                            new ChildEntityModelCreateObject {
                                Name = "Quantity"
                            }
                        }
                    }
                }
            };

            // Add ML entity
            var mlEntityId = await client.Model.AddEntityAsync(appId, versionId, mlEntityDefinition);;

            // Add phraselist feature
            var phraselistId = await client.Features.AddPhraseListAsync(appId, versionId, new PhraselistCreateObject
            {
                EnabledForAllModels = false,
                IsExchangeable      = true,
                Name    = "QuantityPhraselist",
                Phrases = "few,more,extra"
            });

            // Get entity and subentities
            var model = await client.Model.GetEntityAsync(appId, versionId, mlEntityId);

            var toppingQuantityId = GetModelGrandchild(model, "Toppings", "Quantity");
            var pizzaQuantityId   = GetModelGrandchild(model, "Pizza", "Quantity");

            // add model as feature to subentity model
            await client.Features.AddEntityFeatureAsync(appId, versionId, pizzaQuantityId, new ModelFeatureInformation { ModelName = "number", IsRequired = true });

            await client.Features.AddEntityFeatureAsync(appId, versionId, toppingQuantityId, new ModelFeatureInformation { ModelName = "number" });

            // add phrase list as feature to subentity model
            await client.Features.AddEntityFeatureAsync(appId, versionId, toppingQuantityId, new ModelFeatureInformation { FeatureName = "QuantityPhraselist" });

            // Add example utterance to intent
            Console.WriteLine("Adding example utterance to intent...");

            // Define labeled example
            var labeledExampleUtteranceWithMLEntity = new ExampleLabelObject
            {
                Text         = "I want two small seafood pizzas with extra cheese.",
                IntentName   = intentName,
                EntityLabels = new[]
                {
                    new EntityLabelObject
                    {
                        StartCharIndex = 7,
                        EndCharIndex   = 48,
                        EntityName     = "Pizza order",
                        Children       = new[]
                        {
                            new EntityLabelObject
                            {
                                StartCharIndex = 7,
                                EndCharIndex   = 30,
                                EntityName     = "Pizza",
                                Children       = new[]
                                {
                                    new EntityLabelObject {
                                        StartCharIndex = 7, EndCharIndex = 9, EntityName = "Quantity"
                                    },
                                    new EntityLabelObject {
                                        StartCharIndex = 11, EndCharIndex = 15, EntityName = "Size"
                                    },
                                    new EntityLabelObject {
                                        StartCharIndex = 17, EndCharIndex = 23, EntityName = "Type"
                                    }
                                }
                            },
                            new EntityLabelObject
                            {
                                StartCharIndex = 37,
                                EndCharIndex   = 48,
                                EntityName     = "Toppings",
                                Children       = new[]
                                {
                                    new EntityLabelObject {
                                        StartCharIndex = 37, EndCharIndex = 41, EntityName = "Quantity"
                                    },
                                    new EntityLabelObject {
                                        StartCharIndex = 43, EndCharIndex = 48, EntityName = "Type"
                                    }
                                }
                            }
                        }
                    },
                }
            };

            // Add an example for the entity.
            // Enable nested children to allow using multiple models with the same name.
            // The quantity subentity and the phraselist could have the same exact name if this is set to True
            await client.Examples.AddAsync(appId, versionId, labeledExampleUtteranceWithMLEntity, enableNestedChildren : true);

            // Train the app
            Console.WriteLine("Training the app...");
            await client.Train.TrainVersionAsync(appId, versionId);

            while (true)
            {
                var status = await client.Train.GetStatusAsync(appId, versionId);

                if (status.All(m => m.Details.Status == "Success"))
                {
                    // Assumes that we never fail, and that eventually we'll always succeed.
                    break;
                }
            }

            // Publish app to production slot
            Console.WriteLine("Publishing the app to production slot...");
            await client.Apps.PublishAsync(appId, new ApplicationPublishObject { VersionId = versionId, IsStaging = false });

            // Authenticate the prediction runtime client
            Console.WriteLine("Authenticating the prediction client...");
            credentials = new Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.ApiKeyServiceClientCredentials(PREDICTION_KEY);
            var runtimeClient = new LUISRuntimeClient(credentials)
            {
                Endpoint = predictionEndpoint
            };

            // Get prediction from runtime
            // Production == slot name
            Console.WriteLine("Getting prediction...");
            var request = new PredictionRequest {
                Query = "I want two small pepperoni pizzas with more salsa"
            };
            var prediction = await runtimeClient.Prediction.GetSlotPredictionAsync(appId, "Production", request);

            Console.Write(JsonConvert.SerializeObject(prediction, Formatting.Indented));
        }
Beispiel #27
0
        public async Task <Response> MakePredictionAsync(string urlBase, string servicePrefix, string controller, PredictionRequest predictionRequest, string tokenType, string accessToken)
        {
            try
            {
                string        request = JsonConvert.SerializeObject(predictionRequest);
                StringContent content = new StringContent(request, Encoding.UTF8, "application/json");
                HttpClient    client  = new HttpClient
                {
                    BaseAddress = new Uri(urlBase)
                };

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                string url = $"{servicePrefix}{controller}";
                HttpResponseMessage response = await client.PostAsync(url, content);

                string result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = result
                    });
                }

                return(new Response
                {
                    IsSuccess = true
                });
            }
            catch (Exception ex) {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
Beispiel #28
0
 public PredictionResponse(PredictionRequest prq, string ClassName, float Proba) : base(prq.FilePath, prq.Image)
 {
     this.ClassName = ClassName;
     this.Proba     = Proba;
 }
Beispiel #29
0
 /// <summary>
 /// Gets the predictions for an application slot.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='appId'>
 /// The application ID.
 /// </param>
 /// <param name='slotName'>
 /// The application slot name.
 /// </param>
 /// <param name='predictionRequest'>
 /// The prediction request parameters.
 /// </param>
 /// <param name='verbose'>
 /// Indicates whether to get extra metadata for the entities predictions or
 /// not.
 /// </param>
 /// <param name='showAllIntents'>
 /// Indicates whether to return all the intents in the response or just the top
 /// intent.
 /// </param>
 /// <param name='log'>
 /// Indicates whether to log the endpoint query or not.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <PredictionResponse> GetSlotPredictionAsync(this IPredictionOperations operations, System.Guid appId, string slotName, PredictionRequest predictionRequest, bool?verbose = default(bool?), bool?showAllIntents = default(bool?), bool?log = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetSlotPredictionWithHttpMessagesAsync(appId, slotName, predictionRequest, verbose, showAllIntents, log, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Beispiel #30
0
        public async Task <IActionResult> PostPrediction([FromBody] PredictionRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            MatchEntity matchEntity = await _context.Matches.FindAsync(request.MatchId);

            if (matchEntity == null)
            {
                return(BadRequest("Este partido no existe."));
            }

            if (matchEntity.IsClosed)
            {
                return(BadRequest("Este partido está cerrado."));
            }

            User userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest("Este usuario no existe."));
            }

            if (matchEntity.Date <= DateTime.UtcNow)
            {
                return(BadRequest("Este partido ya empezó."));
            }

            PredictionEntity predictionEntity = await _context.Predictions
                                                .FirstOrDefaultAsync(p => p.Player.User.Id == request.UserId.ToString() && p.Match.Id == request.MatchId);

            if (predictionEntity == null)
            {
                //var playerResponse = JsonConvert.DeserializeObject<PlayerResponse>(Settings.Player);

                var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == request.UserId.ToString());

                var player = await _context.Players.FirstOrDefaultAsync(u => u.User.Id == user.Id);



                predictionEntity = new PredictionEntity
                {
                    GoalsLocal   = request.GoalsLocal,
                    GoalsVisitor = request.GoalsVisitor,
                    Match        = matchEntity,
                    Player       = player
                };

                _context.Predictions.Add(predictionEntity);
            }
            else
            {
                predictionEntity.GoalsLocal   = request.GoalsLocal;
                predictionEntity.GoalsVisitor = request.GoalsVisitor;
                _context.Predictions.Update(predictionEntity);
            }

            await _context.SaveChangesAsync();

            return(NoContent());
        }