Esempio n. 1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string cognitive_service_key      = Environment.GetEnvironmentVariable("cognitive_service_key");
            string cognitive_service_endpoint = Environment.GetEnvironmentVariable("cognitive_service_endpoint");

            int SentencesToSummarize = 3;

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  inputText   = data.text;

            var credentials = new ApiKeyServiceClientCredentials(cognitive_service_key);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = cognitive_service_endpoint
            };

            dynamic result = new JObject();

            //Detecting language first
            var inputDocuments = new LanguageBatchInput(
                new List <LanguageInput>
            {
                new LanguageInput(id: "1", text: inputText)
            });

            var langResults = await client.DetectLanguageAsync(false, inputDocuments);

            string inputLanguage = null;

            foreach (var document in langResults.Documents)
            {
                inputLanguage = document.DetectedLanguages[0].Iso6391Name;
            }

            result.language = inputLanguage;
            log.LogInformation($"{result.ToString()}");

            //Detecting sentiment of the input text
            var inputDocuments2 = new MultiLanguageBatchInput(
                new List <MultiLanguageInput>
            {
                new MultiLanguageInput(inputLanguage, "1", inputText)
            });

            var sentimentResult = await client.SentimentAsync(false, inputDocuments2);

            double?sentimentScore = 0;

            foreach (var document in sentimentResult.Documents)
            {
                sentimentScore = document.Score;
            }

            result.sentimentScore = sentimentScore;
            log.LogInformation($"{result.ToString()}");

            //Detecting entities in the text
            var entitiesResult = await client.EntitiesAsync(false, inputDocuments2);

            JArray entities = new JArray();

            foreach (var document in entitiesResult.Documents)
            {
                dynamic entityObject = new JObject();
                foreach (var entity in document.Entities)
                {
                    entityObject.name    = entity.Name;
                    entityObject.type    = entity.Type;
                    entityObject.subtype = entity.SubType;
                    foreach (var match in entity.Matches)
                    {
                        entityObject.offset = match.Offset;
                        entityObject.length = match.Length;
                        entityObject.score  = match.EntityTypeScore;
                        //log.LogInformation($"\t\t\tOffset: {match.Offset},\tLength: {match.Length},\tScore: {match.EntityTypeScore:F3}");
                    }
                    entities.Add(entityObject);
                }
            }
            result.entities = entities;
            log.LogInformation($"{result.ToString()}");

            //Detecting keyphrases
            var kpResults = await client.KeyPhrasesAsync(false, inputDocuments2);

            JArray keyPhrases = new JArray();
            var    Phrases    = new List <string>();

            // Printing keyphrases
            foreach (var document in kpResults.Documents)
            {
                foreach (string keyphrase in document.KeyPhrases)
                {
                    keyPhrases.Add(keyphrase);
                    Phrases.Add(keyphrase);
                }
            }
            result.keyphrases = keyPhrases;

            //Generating text summary
            String[] sentences = inputText.Split('!', '.', '?');

            List <Match> matchList = new List <Match>();
            int          counter   = 0;
            // Take the 10 best words
            var topPhrases = Phrases.Take(10);

            foreach (var sentence in sentences)
            {
                double count = 0;

                Match match = new Match();
                foreach (var phrase in topPhrases)
                {
                    if ((sentence.ToLower().IndexOf(phrase) > -1) &&
                        (sentence.Length > 20) && (WordCount(sentence) >= 3))
                    {
                        count++;
                    }
                    ;
                }

                if (count > 0)
                {
                    matchList.Add(new Match {
                        sentence = counter, total = count
                    });
                }
                counter++;
            }

            var           MatchList     = matchList.OrderByDescending(y => y.total).Take(SentencesToSummarize).OrderBy(x => x.sentence).ToList();
            StringBuilder summary       = new StringBuilder();
            List <string> SentenceList  = new List <string>();
            int           sentenceCount = 0;

            for (int i = 0; i < MatchList.Count; i++)
            {
                summary.Append(sentences[MatchList[i].sentence] + ".");
                sentenceCount++;
            }
            // If there are no sentences found, just take the first three
            if (sentenceCount == 0)
            {
                for (int i = 0; i < Math.Min(SentencesToSummarize, sentences.Count()); i++)
                {
                    summary.Append(sentences[MatchList[i].sentence] + ".");
                }
            }

            result.summary = summary.ToString();
            log.LogInformation($"{result.ToString()}");

            return(inputText != null
                ? (ActionResult) new OkObjectResult($"{result.ToString()}")
                : new BadRequestObjectResult("{ \"error\": \"Please pass the text input for the text analytics operations\""));
        }
Esempio n. 2
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string cognitive_service_key      = Environment.GetEnvironmentVariable("cognitive_service_key");
            string cognitive_service_endpoint = Environment.GetEnvironmentVariable("cognitive_service_endpoint");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  imageURL    = data.imageurl;
            //imageURL = "https://www.thehansindia.com/assets/9583_rahul-modi.jpg";

            dynamic result = new JObject();

            var credentials = new ApiKeyServiceClientCredentials(cognitive_service_key);

            ComputerVisionClient computerVision = new ComputerVisionClient(credentials,
                                                                           new System.Net.Http.DelegatingHandler[] { });

            // Specify the Azure region
            computerVision.Endpoint = cognitive_service_endpoint;

            // Analyzing image from remote URL
            if (!Uri.IsWellFormedUriString(imageURL, UriKind.Absolute))
            {
                log.LogError(
                    "\nInvalid remoteImageUrl:\n{0} \n", imageURL);
                log.LogInformation("invalid image URL provided.");
            }
            else
            {
                ImageAnalysis analysis = new ImageAnalysis();
                try
                {
                    analysis = await computerVision.AnalyzeImageAsync(imageURL, features);

                    // Getting caption
                    result.caption = "";
                    if (analysis.Description.Captions.Count != 0)
                    {
                        result.caption = analysis.Description.Captions[0].Text;
                    }

                    // Getting faces
                    dynamic faces       = new JArray();
                    dynamic celebrities = new JArray();
                    if (analysis.Faces.Count != 0)
                    {
                        foreach (var face in analysis.Faces)
                        {
                            dynamic faceObject = new JObject();
                            faceObject.rectangle = $"({face.FaceRectangle.Left.ToString()}, " +
                                                   $"{face.FaceRectangle.Top.ToString()}, " +
                                                   $"{face.FaceRectangle.Height.ToString()}, " +
                                                   $"{face.FaceRectangle.Width.ToString()})";
                            faceObject.age    = face.Age;
                            faceObject.gender = face.Gender.ToString();
                            faces.Add(faceObject);
                        }

                        var celebRecognition = await computerVision.AnalyzeImageByDomainAsync("celebrities", imageURL);

                        dynamic celebResult = JsonConvert.DeserializeObject(celebRecognition.Result.ToString());
                        if (celebResult.celebrities.Count > 1)
                        {
                            foreach (var celeb in celebResult.celebrities)
                            {
                                celebrities.Add(celeb);
                            }
                        }
                    }
                    result.faces       = faces;
                    result.celebrities = celebrities;

                    // Getting categories
                    dynamic categories = new JArray();
                    if (analysis.Categories.Count != 0)
                    {
                        foreach (var category in analysis.Categories)
                        {
                            categories.Add(category.Name);
                        }
                    }
                    result.categories = categories;

                    // Getting brands
                    dynamic brands = new JArray();
                    if (analysis.Brands.Count != 0)
                    {
                        foreach (var brand in analysis.Brands)
                        {
                            brands.Add(brand.Name);
                        }
                    }
                    result.brands = brands;

                    // Getting objects
                    dynamic objects = new JArray();
                    if (analysis.Objects.Count != 0)
                    {
                        foreach (var objectItem in analysis.Objects)
                        {
                            dynamic objObject = new JObject();
                            objObject.name      = objectItem.ObjectProperty;
                            objObject.rectangle = $"({objectItem.Rectangle.X.ToString()}, " +
                                                  $"{objectItem.Rectangle.Y.ToString()}, " +
                                                  $"{objectItem.Rectangle.H.ToString()}, " +
                                                  $"{objectItem.Rectangle.W.ToString()})";
                            objects.Add(objObject);
                        }
                    }
                    result.objects = objects;

                    // Getting tags
                    dynamic tags = new JArray();
                    if (analysis.Tags.Count != 0)
                    {
                        foreach (var tag in analysis.Tags)
                        {
                            tags.Add(tag.Name);
                        }
                    }
                    result.tags = tags;
                }
                catch (Exception ex)
                {
                    string exception = ex.Message;
                }
            }

            return(imageURL != null
                ? (ActionResult) new OkObjectResult($"{result.ToString()}")
                : new BadRequestObjectResult("{ \"error\": \"Please pass a valid image URL in the request\""));
        }