コード例 #1
0
        private static async Task <SentimentResp> GetRatingScore(SentimentReq sd)
        {
            //https://southeastasia.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment
            var taUrl    = "https://southeastasia.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
            var postData = JsonConvert.SerializeObject(sd);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, taUrl);

            request.Content = new StringContent(postData,
                                                Encoding.UTF8,
                                                "application/json");
            request.Content.Headers.Add("Ocp-Apim-Subscription-Key", "987bb1fbe0e54280b15341cfa8d45f26");

            var result = await httpClient.SendAsync(request);

            var ret = await result.Content.ReadAsAsync <SentimentResp>();

            return(ret);
        }
コード例 #2
0
        // [FunctionName("UpdateRatingSentiment")]
        public static async Task RunAsync([CosmosDBTrigger(
                                               databaseName: "Ratings",
                                               collectionName: "ratings",
                                               ConnectionStringSetting = "CosmosDBConnection")] IReadOnlyList <Document> documents,
                                          [CosmosDB(
                                               databaseName: "Ratings",
                                               collectionName: "ratings",
                                               ConnectionStringSetting = "CosmosDBConnection")] DocumentClient documentClient,


                                          ILogger log)

        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            var s       = new List <SentimentReqItem>();// = documents.ToDictionary(<SentimentInput>(x=> new SentimentInput {text = x.userNote});
            var ratings = new List <Rating>();

            for (int i = 0; i < documents.Count; i++)
            {
                ratings.Add(JsonConvert.DeserializeObject <Rating>(documents[i].ToString()));
                s.Add(new SentimentReqItem()
                {
                    id = documents[i].SelfLink, text = ratings[i].userNotes
                });
            }
            var sd = new SentimentReq()
            {
                documents = s
            };
            var ret = await GetRatingScore(sd);

            var dburi = UriFactory.CreateDocumentCollectionUri("Ratings", "ratings");

            for (int i = 0; i < ret.documents.Count; i++)
            {
                ratings[i].sentimentScore = ret.documents[i].score;
                var re = await documentClient.UpsertDocumentAsync(dburi, ratings[i]);
            }
        }
コード例 #3
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] Rating data,
                                                     [CosmosDB(
                                                          databaseName: "Ratings",
                                                          collectionName: "ratings",
                                                          ConnectionStringSetting = "CosmosDBConnection")] IAsyncCollector <Rating> documentsToStore, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            // string requestBody = new StreamReader(req.Body).ReadToEnd();
            // RatingData data = JsonConvert.DeserializeObject<RatingData>(requestBody);
            string errorField = "";

            if (data != null)
            {
                bool productValid = await ProductIdValid(data.productId.ToString());

                bool userValid = await UserIdValid(data.userId.ToString());

                bool ratingValid = data.rating >= 0 && data.rating <= 5;
                if (productValid && userValid && ratingValid)
                {
                    data.id        = Guid.NewGuid();
                    data.timestamp = DateTime.UtcNow;

                    try{
                        var sd = new SentimentReq()
                        {
                            documents = new List <SentimentReqItem>()
                            {
                                new SentimentReqItem()
                                {
                                    id = data.id.ToString(), text = data.userNotes
                                }
                            }
                        };
                        var sentimentResp = await GetRatingScore(sd);

                        data.sentimentScore = sentimentResp.documents[0].score;


                        log.LogMetric("RatingSentiments", sentimentResp.documents[0].score, new Dictionary <string, object>()
                        {
                            { "UserNote", data.userNotes },
                            { "RatingId", data.id }
                        });
                        await documentsToStore.AddAsync(data);

                        //
                    }
                    catch (Exception e) {
                        return(new BadRequestObjectResult("CosmosDB error: " + e.Message));
                    }
                    return((ActionResult) new OkObjectResult(data));
                }
                else if (!productValid)
                {
                    errorField = "productId";
                }
                else if (!userValid)
                {
                    errorField = "userId";
                }
                else if (!ratingValid)
                {
                    errorField = "rating value";
                }
            }
            return(new BadRequestObjectResult("meow3 please input valid " + errorField));
        }