예제 #1
0
        public async static Task SearchPlaceAsync(IDialogContext context, string key, string query)
        {
            IEntitySearchAPI client = new EntitySearchAPI(new Microsoft.Azure.CognitiveServices.Search.EntitySearch.ApiKeyServiceClientCredentials(key));
            var result = await client.Entities.SearchAsync(query : query);

            if (result?.Places?.Value?.Count > 0)
            {
                await context.PostAsync($"Places search: **{query}**");

                var message = context.MakeMessage();
                message.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                foreach (var item in result.Places.Value)
                {
                    var      place = item as Microsoft.Azure.CognitiveServices.Search.EntitySearch.Models.Place;
                    HeroCard card  = new HeroCard
                    {
                        Title    = place.Name,
                        Text     = $"Address: {place.Address.AddressLocality}, {place.Address.AddressRegion}, {place.Address.AddressCountry} Postal: {place.Address.PostalCode}",
                        Subtitle = $"Telephone: {place.Telephone}",
                        Buttons  = new List <CardAction>
                        {
                            new CardAction(ActionTypes.OpenUrl, "View More", value: place.WebSearchUrl)
                        }
                    };
                    message.Attachments.Add(card.ToAttachment());
                }
                await context.PostAsync(message);
            }
        }
        public static void Error(string subscriptionKey)
        {
            var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var entityData = client.Entities.Search(query: "tom cruise", market: "no-ty");
            }
            catch (ErrorResponseException ex)
            {
                // The status code of the error should be a good indication of what occurred. However, if you'd like more details, you can dig into the response.
                // Please note that depending on the type of error, the response schema might be different, so you aren't guaranteed a specific error response schema.
                Console.WriteLine("Exception occurred, status code {0} with reason {1}.", ex.Response.StatusCode, ex.Response.ReasonPhrase);

                // if you'd like more descriptive information (if available), attempt to parse the content as an ErrorResponse
                var issue = JsonConvert.DeserializeObject <ErrorResponse>(ex.Response.Content);

                if (issue != null && issue.Errors?.Count > 0)
                {
                    if (issue.Errors[0].SubCode == ErrorSubCode.ParameterInvalidValue)
                    {
                        Console.WriteLine("Turns out the issue is parameter \"{0}\" has an invalid value \"{1}\". Detailed message is \"{2}\"", issue.Errors[0].Parameter, issue.Errors[0].Value, issue.Errors[0].Message);
                    }
                }
            }
        }
예제 #3
0
        public async static Task SearchEntityAsync(IDialogContext context, string key, string query)
        {
            IEntitySearchAPI client = new EntitySearchAPI(new Microsoft.Azure.CognitiveServices.Search.EntitySearch.ApiKeyServiceClientCredentials(key));
            var result = await client.Entities.SearchAsync(query : query);

            if (result?.Entities?.Value?.Count > 0)
            {
                await context.PostAsync($"Entity search: **{query}**");

                var message = context.MakeMessage();
                message.AttachmentLayout = AttachmentLayoutTypes.Carousel;

                foreach (var item in result.Entities.Value)
                {
                    HeroCard card = new HeroCard
                    {
                        Title  = item.Name,
                        Text   = item.Description,
                        Images = new List <CardImage>
                        {
                            new CardImage(item.Image.HostPageUrl)
                        },
                        Buttons = new List <CardAction>
                        {
                            new CardAction(ActionTypes.OpenUrl, "Read More", value: item.Url)
                        }
                    };
                    message.Attachments.Add(card.ToAttachment());
                }
                await context.PostAsync(message);
            }
        }
        public static void DominantEntityLookup(string subscriptionKey)
        {
            var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var entityData = client.Entities.Search(query: "tom cruise");

                if (entityData?.Entities?.Value?.Count > 0)
                {
                    // find the entity that represents the dominant one
                    var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();

                    if (mainEntity != null)
                    {
                        Console.WriteLine("Searched for \"Tom Cruise\" and found a dominant entity with this description:");
                        Console.WriteLine(mainEntity.Description);
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find main entity tom cruise!");
                    }
                }
                else
                {
                    Console.WriteLine("Didn't see any data..");
                }
            }
            catch (ErrorResponseException ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
        public static void RestaurantLookup(string subscriptionKey)
        {
            var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var entityData = client.Entities.Search(query: "john howie bellevue");

                if (entityData?.Places?.Value?.Count > 0)
                {
                    // Some local entities will be places, others won't be. Depending on the data you want, try to cast to the appropriate schema
                    // In this case, the item being returned is technically a Restaurant, but the Place schema has the data we want (telephone)
                    var restaurant = entityData.Places.Value.FirstOrDefault() as Place;

                    if (restaurant != null)
                    {
                        Console.WriteLine("Searched for \"John Howie Bellevue\" and found a restaurant with this phone number:");
                        Console.WriteLine(restaurant.Telephone);
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find a place!");
                    }
                }
                else
                {
                    Console.WriteLine("Didn't see any data..");
                }
            }
            catch (ErrorResponseException ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
        public static void HandlingDisambiguation(string subscriptionKey)
        {
            var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var entityData = client.Entities.Search(query: "harry potter");

                if (entityData?.Entities?.Value?.Count > 0)
                {
                    // find the entity that represents the dominant one
                    var mainEntity       = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();
                    var disambigEntities = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DisambiguationItem).ToList();

                    if (mainEntity != null)
                    {
                        Console.WriteLine("Searched for \"harry potter\" and found a dominant entity with type hint \"{0}\" with this description:", mainEntity.EntityPresentationInfo.EntityTypeDisplayHint);
                        Console.WriteLine(mainEntity.Description);
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find a reliable dominant entity for harry potter!");
                    }

                    if (disambigEntities?.Count > 0)
                    {
                        Console.WriteLine();
                        Console.WriteLine("This query is pretty ambiguous and can be referring to multiple things. Did you mean one of these: ");

                        var sb = new StringBuilder();

                        foreach (var disambig in disambigEntities)
                        {
                            sb.AppendFormat(", or {0} the {1}", disambig.Name, disambig.EntityPresentationInfo.EntityTypeDisplayHint);
                        }

                        Console.WriteLine(sb.ToString().Substring(5) + "?");
                    }
                    else
                    {
                        Console.WriteLine("We didn't find any disambiguation items for harry potter, so we must be certain what you're talking about!");
                    }
                }
                else
                {
                    Console.WriteLine("Didn't see any data..");
                }
            }
            catch (ErrorResponseException ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
        public static void MultipleRestaurantLookup(string subscriptionKey)
        {
            var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var restaurants = client.Entities.Search(query: "seattle restaurants");

                if (restaurants?.Places?.Value?.Count > 0)
                {
                    // get all the list items that relate to this query
                    var listItems = restaurants.Places.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.ListItem).ToList();

                    if (listItems?.Count > 0)
                    {
                        var sb = new StringBuilder();

                        foreach (var item in listItems)
                        {
                            var place = item as Place;

                            if (place == null)
                            {
                                Console.WriteLine("Unexpectedly found something that isn't a place named \"{0}\"", item.Name);
                                continue;
                            }

                            sb.AppendFormat(",{0} ({1}) ", place.Name, place.Telephone);
                        }

                        Console.WriteLine("Ok, we found these places: ");
                        Console.WriteLine(sb.ToString().Substring(1));
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find any relevant results for \"seattle restaurants\"");
                    }
                }
                else
                {
                    Console.WriteLine("Didn't see any data..");
                }
            }
            catch (ErrorResponseException ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
예제 #8
0
        public static EntityData SearchEntity(string query, string languague = "pt-BR")
        {
            try
            {
                var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(credential));
                // client.BaseUri = new Uri(endpoint);

                var entityData = client.Entities.Search(query: query, market: languague);
                if (entityData.Entities == null)
                {
                    return(new EntityData()
                    {
                        Name = new System.Globalization.CultureInfo("pt-BR", false).TextInfo.ToTitleCase(query)
                    });
                }
                else
                {
                    var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();

                    if (mainEntity != null)
                    {
                        return(new EntityData()
                        {
                            Description = mainEntity.Description,
                            Name = mainEntity.Name,
                            ImageUrlThumbnail = mainEntity.Image != null ? mainEntity.Image.ThumbnailUrl : null,
                            ImageUrl = (mainEntity.Image != null ? mainEntity.Image.Url : null) == null &&
                                       mainEntity.Image != null &&
                                       mainEntity.Image.HostPageUrl != null
                                  ? mainEntity.Image.HostPageUrl
                                  : null,
                            GeneralContent = Newtonsoft.Json.JsonConvert.SerializeObject(entityData)
                        });
                    }
                    else
                    {
                        return(new EntityData()
                        {
                            Name = new System.Globalization.CultureInfo(languague, false).TextInfo.ToTitleCase(query)
                        });
                    }
                }
            }
            catch (Exception)
            {
                throw; //joga o erro pra cima
            }
        }
예제 #9
0
        /// <summary>
        /// Perform an entity search on the celebrity and return the description.
        /// </summary>
        /// <param name="celebrity">The celebrity to search for.</param>
        /// <returns>The description of the celebrity.</returns>
        private async Task <Thing> EntitySearch(Celebrity celebrity)
        {
            var client = new EntitySearchAPI(new ApiKeyServiceClientCredentials(ENTITY_KEY));
            var data   = await client.Entities.SearchAsync(query : celebrity.Name);

            if (data?.Entities?.Value?.Count > 0)
            {
                return((from v in data.Entities.Value
                        where v.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity
                        select v).FirstOrDefault());
            }
            else
            {
                return(null);
            }
        }
예제 #10
0
        static void Main3(string[] args)
        {
            while (true)
            {
                Console.WriteLine("informe uma entidade:");
                var entidade   = Console.ReadLine();
                var client     = new EntitySearchAPI(new ApiKeyServiceClientCredentials("59af8519d4594b538dd75698d72905a3"));
                var entityData = client.Entities.Search(query: entidade, market: "pt-BR");
                if (entityData.Entities == null)
                {
                    Console.WriteLine("========= NAO LOCALIZADO ==============");
                    Console.WriteLine(JsonConvert.SerializeObject(entityData, Formatting.Indented));
                }
                else
                {
                    var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();
                    Console.WriteLine(mainEntity.Description);
                    Console.WriteLine(JsonConvert.SerializeObject(mainEntity, Formatting.Indented));
                }

                Console.ReadKey();
                Console.Clear();
            }
        }
        public string Get(string textToInspect)
        {
            // Create a client.
            ITextAnalyticsAPI client = new TextAnalyticsAPI();

            client.AzureRegion = AzureRegions.Westeurope;

            client.SubscriptionKey = config["TextAnalysisKey"];

            StringBuilder sb = new StringBuilder();


            // Extracting language
            sb.AppendLine("===== LANGUAGE EXTRACTION ======");

            LanguageBatchResult result = client.DetectLanguage(
                new BatchInput(
                    new List <Input>()
            {
                new Input("1", textToInspect),
            }));

            // Printing language results.
            foreach (var document in result.Documents)
            {
                sb.AppendLine($"Document ID: {document.Id} , Language: {document.DetectedLanguages[0].Name}");

                // Getting key-phrases
                sb.AppendLine("\n\n===== KEY-PHRASE EXTRACTION ======");

                var isoLanguageName = document.DetectedLanguages[0].Iso6391Name;

                KeyPhraseBatchResult phraseResult = client.KeyPhrases(
                    new MultiLanguageBatchInput(
                        new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(isoLanguageName, "1", textToInspect),
                }));

                var phrasesFound = phraseResult.Documents.FirstOrDefault();
                if (phrasesFound == null)
                {
                    throw new Exception("Failed processing message - no phrase result");
                }

                sb.AppendLine($"Document ID: {phrasesFound.Id} ");

                sb.AppendLine("\t Key phrases:");

                foreach (string keyphrase in phrasesFound.KeyPhrases)
                {
                    sb.AppendLine("\t\t" + keyphrase);

                    var entitySearchApi = new EntitySearchAPI(new ApiKeyServiceClientCredentials(config["EntityKey"]));
                    var entityData      = entitySearchApi.Entities.Search(keyphrase);
                    if (entityData?.Entities?.Value?.Count > 0)
                    {
                        // find the entity that represents the dominant one
                        var mainEntity = entityData.Entities.Value.Where(thing => thing.EntityPresentationInfo.EntityScenario == EntityScenario.DominantEntity).FirstOrDefault();

                        if (mainEntity != null)
                        {
                            sb.AppendLine($"Searched for {keyphrase} and found a dominant entity with this description:");
                            sb.AppendLine(mainEntity.Description);
                        }
                        else
                        {
                            sb.AppendLine($"Couldn't find a main entity for {keyphrase}");
                        }
                    }
                    else
                    {
                        sb.AppendLine($"No data returned for entity {keyphrase}");
                    }
                }

                // Extracting sentiment
                sb.AppendLine("\n\n===== SENTIMENT ANALYSIS ======");

                SentimentBatchResult sentimentResult = client.Sentiment(
                    new MultiLanguageBatchInput(
                        new List <MultiLanguageInput>()
                {
                    new MultiLanguageInput(isoLanguageName, "0", textToInspect),
                }));


                var sentiment = sentimentResult.Documents.FirstOrDefault();
                if (sentiment == null)
                {
                    throw new Exception("Failed processing message - no sentiment result");
                }

                // Printing sentiment results
                sb.AppendLine($"Document ID: {sentiment.Id} , Sentiment Score: {sentiment.Score}");
            }

            return(sb.ToString());
        }