Ejemplo n.º 1
0
        public Search(Filter img)
        {
            var client       = new ImageSearchAPI(new ApiKeyServiceClientCredentials("API KEY Bing search v7"));
            var imageResults = client.Images.SearchAsync(
                query: img.search,
                imageType: img.type,
                size: img.size,
                aspect: img.aspect,
                license: img.isFree,
                count: img.nbResult
                ).Result;

            foreach (var val in imageResults.Value)
            {
                picList.Add(val.ContentUrl);
            }

            //if (String.IsNullOrEmpty(picList.First<String>))
            //{
            //    if (imageResults.PivotSuggestions.Count > 0)
            //        var Suggestion = imageResults.PivotSuggestions.First().Suggestions.First().Text;
            //    if (imageResults.QueryExpansions.Count > 0)
            //        var QueryExpansion = imageResults.QueryExpansions.First().Text;
            //}
        }
Ejemplo n.º 2
0
        public async static Task SearchImageAsync(IDialogContext context, string key, string query)
        {
            IImageSearchAPI client = new ImageSearchAPI(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(key));
            var             result = await client.Images.SearchAsync(query : query, count : 5, imageType : ImageType.Line, aspect : ImageAspect.Square);

            if (result?.Value?.Count > 0)
            {
                await context.PostAsync($"Here is top 5 Image search result for **{query}**");

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

                foreach (var item in result.Value)
                {
                    HeroCard card = new HeroCard
                    {
                        Title  = item.Name,
                        Images = new List <CardImage>
                        {
                            new CardImage(item.ContentUrl)
                        },
                        Buttons = new List <CardAction>
                        {
                            new CardAction(ActionTypes.OpenUrl, "View Image", value: item.ContentUrl)
                        }
                    };
                    message.Attachments.Add(card.ToAttachment());
                }
                await context.PostAsync(message);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 根据文本获取对就关联的图片
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task <string> GetImageFromTextAsync(string content)
        {
            // 调用文本分析提取关键词
            var textClient = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(TextKey))
            {
                Endpoint = "https://eastasia.api.cognitive.microsoft.com"
            };
            // 根据关键词查询图片
            var result = await textClient.KeyPhrasesAsync(new MultiLanguageBatchInput(new List <MultiLanguageInput>()
            {
                new MultiLanguageInput()
                {
                    Id = "id",
                    Text = content,
                    Language = "en"
                }
            }));

            foreach (var keyword in result.Documents[0].KeyPhrases)
            {
                var imageClient  = new ImageSearchAPI(new ApiKeyServiceClientCredentials(ImageKey));
                var imageResults = await imageClient.Images.SearchAsync(query : keyword, acceptLanguage : "EN", color : "ColorOnly", freshness : "Month", count : 5, size : "Medium");

                if (imageResults.Value?.Count > 0)
                {
                    var firstImageResult = imageResults.Value?.First();
                    return(firstImageResult.ContentUrl);
                }
                else
                {
                    continue;
                }
            }
            return(default);
Ejemplo n.º 4
0
        private static IList <ImageObject> SearchImagesWithSdk(string searchTerm)
        {
            var subscriptionKey = Startup.BingSearchApiKey;
            var client          = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));
            var imageResults    = client.Images.SearchAsync(query: searchTerm).Result;

            return(imageResults.Value);
        }
Ejemplo n.º 5
0
        public static async Task DoMention_Job(string body)
        {
            var req = JObject.Parse(body);

            var mentionedBy = (string)req["event"]["user"];
            var text        = (string)req["event"]["text"];
            var channel     = (string)req["event"]["channel"];

            var splitted = text.Split(new char[] { ' ', ' ' }).ToArray();

            if (splitted.Length < 1 || splitted[0].IndexOf("<@") != 0)
            {
                return; // ignore
            }

            var args = splitted.Skip(1).ToArray();

            var parser = new CommandLineApplication();
            var limit  = parser.Option <int>("--limit <LIMITATION>", "Limitation", CommandOptionType.SingleValue);
            var show   = parser.Option <int>("--show <COUNT>", "Count of attachment", CommandOptionType.SingleValue);
            var random = parser.Option <bool>("--random", "Sort by random", CommandOptionType.NoValue);
            var terms  = parser.Argument <string>("Terms", "Search terms", multipleValues: true);

            parser.OnExecute(async() => {
                var limitation = limit.HasValue() ? limit.ParsedValue : 3;
                var client     = new ImageSearchAPI(new ApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("IMAJIN_BING_KEY")));

                var result = (await client.Images.SearchAsync(
                                  string.Join(" ", terms.Values),
                                  count: limitation,
                                  license: "All",
                                  safeSearch: "Strict"
                                  )).Value;

                if (result.Count < 1)
                {
                    await PostImageToSlack(channel, null);
                }
                else
                {
                    await PostImageToSlack(
                        channel,
                        (random.HasValue() ? result.OrderBy(_ => Guid.NewGuid()).ToArray() : result)
                        .Take(show.HasValue() ? show.ParsedValue : 1)
                        .Select(x => x.ThumbnailUrl)
                        .ToArray()
                        );
                }
            });

            parser.OnValidationError((e) => {
                throw new ArgumentException(e.ToString());
            });

            parser.Execute(args);
        }
        private static IList <ImageObject> SearchImagesWithSdk(string searchTerm, string color, string freshness, string countryCode,
                                                               string safeSearch, string aspect)
        {
            var subscriptionKey = Startup.BingSearchApiKey;
            var client          = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));
            var imageResults    = client.Images.SearchAsync(query: searchTerm, color: color, freshness: freshness, countryCode: countryCode,
                                                            safeSearch: safeSearch, aspect: aspect).Result;

            return(imageResults.Value);
        }
Ejemplo n.º 7
0
        // Add SearchBing
        public async Task SearchBing(ITurnContext context, string searchText)
        {
            // Step 1: Call the Bing Image Search API
            //IMPORTANT: replace this variable with your Cognitive Services subscription key.
            string subscriptionKey = "YourBingKey";
            //initialize the client
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));
            //images to be returned by the Bing Image Search API
            Images imageResults = null;

            try
            {
                // Call the API and store the results
                imageResults = client.Images.SearchAsync(query: searchText).Result; //search query
            }
            catch (Exception ex)
            {
                // If there's an exception, return the error in the chat window
                await context.SendActivityAsync("Encountered exception. " + ex.Message);
            }
            // Step 2: Process the results and send to the user
            // If the API returns images
            if (imageResults != null)
            {
                // Parse out the first five images from ImageResults
                // Add the content URL to a simple message attachment
                var activity = MessageFactory.Attachment(new Attachment[]
                {
                    new Attachment {
                        ContentUrl = imageResults.Value[0].ContentUrl, ContentType = "image/png"
                    },
                    new Attachment {
                        ContentUrl = imageResults.Value[1].ContentUrl, ContentType = "image/png"
                    },
                    new Attachment {
                        ContentUrl = imageResults.Value[2].ContentUrl, ContentType = "image/png"
                    },
                    new Attachment {
                        ContentUrl = imageResults.Value[3].ContentUrl, ContentType = "image/png"
                    },
                    new Attachment {
                        ContentUrl = imageResults.Value[4].ContentUrl, ContentType = "image/png"
                    }
                });
                // Send the activity to the user.
                await SearchResponses.ReplyWithBingResults(context, searchText);

                await context.SendActivityAsync(activity);
            }
            else // If the API doesn't return any images
            {
                await SearchResponses.ReplyWithNoResults(context, searchText);
            }
        }
Ejemplo n.º 8
0
 public Form1()
 {
     InitializeComponent();
     LoadWords();
     LoadRadioGroup();
     _indexRadioLoaded = new List <int>();
     _indexWordLoaded  = new List <int>();
     _random           = new Random();
     _client           = new ImageSearchAPI(new ApiKeyServiceClientCredentials(ApplicationContants.SubscriptionKey));
     LoadDataQuiz();
 }
Ejemplo n.º 9
0
 public static void DownloadImages(string[] categories)
 {
     foreach (var category in categories)
     {
         var client       = new ImageSearchAPI(new ApiKeyServiceClientCredentials(BING_KEY));
         var imageResults = client.Images.SearchAsync(query: category, count: MaxCount).Result;
         foreach (var item in imageResults.Value)
         {
             DownloadPhoto(category, item.ContentUrl);
         }
     }
 }
Ejemplo n.º 10
0
        public IActionResult IndexGet(ImageSearchParameters imageSearchParameters)
        {
            if (!string.IsNullOrEmpty(imageSearchParameters.Query))
            {
                ImageSearchAPI client       = new ImageSearchAPI(new ApiKeyServiceClientCredentials(_config["Keys:BingSearch"]));
                Images         imageResults = client.Images.SearchAsync(query: imageSearchParameters.Query, offset: imageSearchParameters.Offset, count: imageSearchParameters.Count).Result;

                TempData.Put("Images", imageResults);
            }

            return(View("~/Views/Projects/BingSearch/Index.cshtml", imageSearchParameters));
        }
Ejemplo n.º 11
0
        public static void ImageTrending(string subscriptionKey)
        {
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var trendingResults = client.Images.TrendingAsync().Result;
                Console.WriteLine("Search trending images");

                if (trendingResults == null)
                {
                    Console.WriteLine("Didn't see any trending image data.");
                }
                else
                {
                    // Categories
                    if (trendingResults.Categories?.Count > 0)
                    {
                        var firstCategory = trendingResults.Categories[0];
                        Console.WriteLine($"Category count: {trendingResults.Categories.Count}");
                        Console.WriteLine($"First category title: {firstCategory.Title}");

                        // Tiles
                        if (firstCategory.Tiles?.Count > 0)
                        {
                            var firstTile = firstCategory.Tiles[0];
                            Console.WriteLine($"Tile count: {firstCategory.Tiles.Count}");
                            Console.WriteLine($"First tile text: {firstTile.Query.Text}");
                            Console.WriteLine($"First tile url: {firstTile.Query.WebSearchUrl}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find tiles!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find categories!");
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
Ejemplo n.º 12
0
        public static async Task SearchForImageAsync()
        {
            var rnd = Vars.Rand.Next(Vars.Activities.Count);

            Vars.Activity = Vars.Activities[rnd];

            Vars.StatusMessage.Text = Vars.Activity;

            // Add your Bing search API key here
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials("<API KEY>"));

            var imageResults = await client.Images.SearchAsync(query : Vars.Activity, imageType : ImageType.Photo, safeSearch : SafeSearch.Strict, count : 150, imageContent : ImageContent.Portrait);

            var result = "";

            if (imageResults == null)
            {
                result += "Didn't see any image result data.";
            }
            else
            {
                // First image result
                if (imageResults.Value.Count > 0)
                {
                    var r = Vars.Rand.Next(imageResults.Value.Count);
                    var firstImageResult = imageResults.Value[r];

                    result += $"\r\nImage result count: {imageResults.Value.Count}\nRandom: {r}";

                    Vars.ImageURL = firstImageResult.ContentUrl;

                    var fullFilePath = firstImageResult.ThumbnailUrl;

                    BitmapImage bitmap = new BitmapImage();
                    bitmap.BeginInit();
                    bitmap.UriSource = new Uri(fullFilePath, UriKind.Absolute);
                    bitmap.EndInit();
                    Vars.Before.Source = bitmap;
                }
                else
                {
                    result += "Couldn't find image results!";
                }
            }
            Vars.StatusMessage.Text += result;
        }
Ejemplo n.º 13
0
        public async Task Main()
        {
            Console.WriteLine("Searching Bing images for: " + SearchTerm);
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(BingAPIKey));

            client.BaseUri = new Uri(BingUri);
            var images = await client.Images.SearchAsync(query : SearchTerm, count : MaxResultCount, maxFileSize : MaxFileSize, minFileSize : MinFileSize, license : License, safeSearch : SafeSearch);

            if (images != null)
            {
                Console.WriteLine($"{images.Value.Count} images found");
                string path            = $"{DestinationPath}\\{SearchTerm}";
                var    savedImageCount = await SaveBingSearchImages(images.Value, path);

                Console.WriteLine($"{savedImageCount} images saved");
            }
        }
Ejemplo n.º 14
0
        // Searches for results on query (Canadian Rockies) and gets an ImageInsightsToken.
        // Also prints first image insights token, thumbnail url, and image content url.
        private static String ImageResults(String subKey)
        {
            String insightTok = "None";

            try
            {
                var client       = new ImageSearchAPI(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(subKey)); //
                var imageResults = client.Images.SearchAsync(query: "canadian rockies").Result;
                Console.WriteLine("Search images for query \"canadian rockies\"");

                if (imageResults == null)
                {
                    Console.WriteLine("No image result data.");
                }
                else
                {
                    // Image results
                    if (imageResults.Value.Count > 0)
                    {
                        var firstImageResult = imageResults.Value.First();

                        Console.WriteLine($"\r\nImage result count: {imageResults.Value.Count}");
                        insightTok = firstImageResult.ImageInsightsToken;
                        Console.WriteLine($"First image insights token: {firstImageResult.ImageInsightsToken}");
                        Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
                        Console.WriteLine($"First image content url: {firstImageResult.ContentUrl}");
                    }
                    else
                    {
                        insightTok = "None found";
                        Console.WriteLine("Couldn't find image results!");
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("\r\nEncountered exception. " + ex.Message);
            }

            return(insightTok);
        }
Ejemplo n.º 15
0
        //retrieve an image for each elements on the menu using the SDK for Bing Search
        private async Task SearchMenuBingImageAsync()
        {
            IsLoading = true;

            var clientImageSearch = new ImageSearchAPI(new ApiKeyServiceClientCredentials(bingSearchSubscriptionKey));

            foreach (var menuItem in MenuItems)
            {
                var imageResults = await clientImageSearch.Images.SearchAsync(query : menuItem.Title);

                if (imageResults.Value.Count > 0)
                {
                    var firstImageResult = imageResults.Value.First();
                    menuItem.Image   = firstImageResult.ThumbnailUrl;
                    menuItem.Content = firstImageResult.ContentUrl;
                }
            }

            IsLoading = false;
        }
        static void Main(string[] args)
        {
            //IMPORTANT: replace this variable with your Cognitive Services subscription key.
            string subscriptionKey = "ENTER YOUR KEY HERE";
            // the image search term used in the query
            string searchTerm = "canadian rockies";
            //initialize the client
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            Console.WriteLine("This application will send an HTTP request to the Bing Image Search API for {0} and print the response.", searchTerm);

            //images to be returned by the Bing Image Search API
            Images imageResults = null;

            //try to send the request, and get the results.
            Console.WriteLine("Search results for the image query: {0}", searchTerm);
            try
            {
                imageResults = client.Images.SearchAsync(query: searchTerm).Result; //search query
            }
            catch (Exception ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }

            if (imageResults != null)
            {
                //display the details for the first image result. After running the application,
                //you can copy the resulting URLs from the console into your browser to view the image.
                var firstImageResult = imageResults.Value.First();
                Console.WriteLine($"\nTotal number of returned images: {imageResults.Value.Count}\n");
                Console.WriteLine($"Copy the following URLs to view these images on your browser.\n");
                Console.WriteLine($"URL to the first image:\n\n {firstImageResult.ContentUrl}\n");
                Console.WriteLine($"Thumbnail URL for the first image:\n\n {firstImageResult.ThumbnailUrl}");
                Console.Write("\nPress Enter to exit ");
                Console.ReadKey();
            }
        }
Ejemplo n.º 17
0
        public static void ImageSearchWithFilters(string subscriptionKey)
        {
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var imageResults = client.Images.SearchAsync(query: "studio ghibli", imageType: ImageType.AnimatedGif, aspect: ImageAspect.Wide).Result;
                Console.WriteLine("Search images for \"studio ghibli\" results that are animated gifs and wide aspect");

                if (imageResults == null)
                {
                    Console.WriteLine("Didn't see any image result data.");
                }
                else
                {
                    // First image result
                    if (imageResults.Value.Count > 0)
                    {
                        var firstImageResult = imageResults.Value.First();

                        Console.WriteLine($"Image result count: {imageResults.Value.Count}");
                        Console.WriteLine($"First image insightsToken: {firstImageResult.ImageInsightsToken}");
                        Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
                        Console.WriteLine($"First image web search url: {firstImageResult.WebSearchUrl}");
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find image results!");
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
Ejemplo n.º 18
0
        public static void ImageDetail(string subscriptionKey)
        {
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var imageResults = client.Images.SearchAsync(query: "degas").Result;

                var firstImage = imageResults?.Value?.FirstOrDefault();

                if (firstImage != null)
                {
                    var modules = new List <string>()
                    {
                        ImageInsightModule.All
                    };
                    var imageDetail = client.Images.DetailsAsync(query: "degas", insightsToken: firstImage.ImageInsightsToken, modules: modules).Result;
                    Console.WriteLine($"Search detail for image insightsToken={firstImage.ImageInsightsToken}");

                    if (imageDetail != null)
                    {
                        // Insights token
                        Console.WriteLine($"Expected image insights token: {imageDetail.ImageInsightsToken}");

                        // Best representative query
                        if (imageDetail.BestRepresentativeQuery != null)
                        {
                            Console.WriteLine($"Best representative query text: {imageDetail.BestRepresentativeQuery.Text}");
                            Console.WriteLine($"Best representative query web search url: {imageDetail.BestRepresentativeQuery.WebSearchUrl}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find best representative query!");
                        }

                        // Caption
                        if (imageDetail.ImageCaption != null)
                        {
                            Console.WriteLine($"Image caption: {imageDetail.ImageCaption.Caption}");
                            Console.WriteLine($"Image caption data source url: {imageDetail.ImageCaption.DataSourceUrl}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find image caption!");
                        }

                        // Pages including the image
                        if (imageDetail.PagesIncluding?.Value?.Count > 0)
                        {
                            var firstPage = imageDetail.PagesIncluding.Value[0];
                            Console.WriteLine($"Pages including count: {imageDetail.PagesIncluding.Value.Count}");
                            Console.WriteLine($"First page content url: {firstPage.ContentUrl}");
                            Console.WriteLine($"First page name: {firstPage.Name}");
                            Console.WriteLine($"First page date published: {firstPage.DatePublished}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find any pages including this image!");
                        }

                        // Related searches
                        if (imageDetail.RelatedSearches?.Value?.Count > 0)
                        {
                            var firstRelatedSearch = imageDetail.RelatedSearches.Value[0];
                            Console.WriteLine($"Related searches count: {imageDetail.RelatedSearches.Value.Count}");
                            Console.WriteLine($"First related search text: {firstRelatedSearch.Text}");
                            Console.WriteLine($"First related search web search url: {firstRelatedSearch.WebSearchUrl}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find any related searches!");
                        }

                        // Visually similar images
                        if (imageDetail.VisuallySimilarImages?.Value?.Count > 0)
                        {
                            var firstVisuallySimilarImage = imageDetail.VisuallySimilarImages.Value[0];
                            Console.WriteLine($"Visually similar images count: {imageDetail.RelatedSearches.Value.Count}");
                            Console.WriteLine($"First visually similar image name: {firstVisuallySimilarImage.Name}");
                            Console.WriteLine($"First visually similar image content url: {firstVisuallySimilarImage.ContentUrl}");
                            Console.WriteLine($"First visually similar image size: {firstVisuallySimilarImage.ContentSize}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find any related searches!");
                        }

                        // Image tags
                        if (imageDetail.ImageTags?.Value?.Count > 0)
                        {
                            var firstTag = imageDetail.ImageTags.Value[0];
                            Console.WriteLine($"Image tags count: {imageDetail.ImageTags.Value.Count}");
                            Console.WriteLine($"First tag name: {firstTag.Name}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find any related searches!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find detail about the image!");
                    }
                }
                else
                {
                    Console.WriteLine("Couldn't find image results!");
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }
Ejemplo n.º 19
0
        private async Task <DialogTurnResult> SearchBingAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var state = await _accessors.PictureState.GetAsync(stepContext.Context);

            //since we got here via a prompt, the step context's "Result" property
            //should be a true or false value indicating whether the user
            //clicked yes or no.

            //If the user said YES to Bing Search...
            // - create a new instance of Microsoft.Azure.CognitiveServices.Search.ImageSearch.ImageSearchAPI
            // - This ImageSearchAPI instance should use an instance of ApiKeyServiceClientCredentials based on your BING key
            // - pass the same query parameter to the the client's Images property's SearchAsync method. (this is on the state!)
            // - Let us assume all images are PNG. You will want to map (Select =>) some number of these
            //   as an Attachment (Bot.Builder) where the ContentUrl is the image's ContentUrl, and the ContentType is "image/png"
            // - Use MessageFactory to create a carousel of these attachments.
            // - Be sure to use try and Catch! We have our OnTurnError callback but the user should ideally never see it

            //If the user said no...
            // - Respect their choice :)

            //In any case end the dialog
            var choice = (bool)stepContext.Result;

            if (choice)
            {
                var key    = "";
                var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(key));

                try
                {
                    Azure.CognitiveServices.Search.ImageSearch.Models.Images results = await client.Images.SearchAsync(state.Search);

                    var attachments = results.Value.Take(5)
                                      .Select(img => new Attachment
                    {
                        ContentUrl  = img.ContentUrl,
                        ContentType = "image/png"
                    });

                    var activity = MessageFactory.Attachment(attachments, "We found the following images on Bing:");
                    activity.AttachmentLayout = "carousel";

                    await stepContext.Context.SendActivityAsync(activity, cancellationToken);
                }
                catch (Exception e)
                {
                    await stepContext.Context.SendActivityAsync($"Problem during Bing search: {e.Message}");
                }
            }
            else
            {
                await stepContext.Context.SendActivityAsync("Alright, we will not Bing.");
            }


            //Reset the state
            state.Search      = string.Empty;
            state.IsSearching = false;
            await _accessors.ConversationState.SaveChangesAsync(stepContext.Context);

            return(await stepContext.EndDialogAsync());
        }
        //const string accessKey = "988c2071beae433e8d422f8a52a89e45";
        //const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/search";

        //struct SearchResult
        //{
        //    public String jsonResult;
        //    public Dictionary<String, String> relevantHeaders;
        // }


        //static SearchResult BingWebSearch(string searchQuery)
        //{
        //    // Construct the URI of the search request
        //    var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);

        //    // Perform the Web request and get the response
        //    WebRequest request = HttpWebRequest.Create(uriQuery);
        //    request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
        //    HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
        //    string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

        //    // Create result object for return
        //    var searchResult = new SearchResult()
        //    {
        //        jsonResult = json,
        //        relevantHeaders = new Dictionary<String, String>()
        //    };

        //    // Extract Bing HTTP headers
        //    foreach (String header in response.Headers)
        //    {
        //        if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
        //            searchResult.relevantHeaders[header] = response.Headers[header];
        //    }

        //    return searchResult;
        //}

        //static string JsonPrettyPrint(string json)
        //{
        //    if (string.IsNullOrEmpty(json))
        //        return string.Empty;

        //    json = json.Replace(Environment.NewLine, "").Replace("\t", "");

        //    StringBuilder sb = new StringBuilder();
        //    bool quote = false;
        //    bool ignore = false;
        //    char last = ' ';
        //    int offset = 0;
        //    int indentLength = 2;

        //    foreach (char ch in json)
        //    {
        //        switch (ch)
        //        {
        //            case '"':
        //                if (!ignore)
        //                    quote = !quote;
        //                break;
        //            case '\\':
        //                if (quote && last != '\\')
        //                    ignore = true;
        //                break;
        //        }

        //        if (quote)
        //        {
        //            sb.Append(ch);
        //            if (last == '\\' && ignore)
        //                ignore = false;
        //        }
        //        else
        //        {
        //            switch (ch)
        //            {
        //                case '{':
        //                case '[':
        //                    sb.Append(ch);
        //                    sb.Append(Environment.NewLine);
        //                    sb.Append(new string(' ', ++offset * indentLength));
        //                    break;
        //                case '}':
        //                case ']':
        //                    sb.Append(Environment.NewLine);
        //                    sb.Append(new string(' ', --offset * indentLength));
        //                    sb.Append(ch);
        //                    break;
        //                case ',':
        //                    sb.Append(ch);
        //                    sb.Append(Environment.NewLine);
        //                    sb.Append(new string(' ', offset * indentLength));
        //                    break;
        //                case ':':
        //                    sb.Append(ch);
        //                    sb.Append(' ');
        //                    break;
        //                default:
        //                    if (quote || ch != ' ')
        //                        sb.Append(ch);
        //                    break;
        //            }
        //        }
        //        last = ch;
        //    }

        //    return sb.ToString().Trim();
        //}

        /// <summary>
        /// Método que pesquisa imagens do hotel pedido com cognitiveservices do azure
        /// </summary>
        /// <param name="queryHotel"></param>
        /// <param name="canal"></param>
        /// <returns></returns>
        public static List <string> ImageSearch(string queryHotel, string canal)
        {
            var           client       = new ImageSearchAPI(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(ConfigurationManager.AppSettings["BingSearchKey"].ToString()));
            List <string> urlList      = null;
            int           numm_imagess = int.Parse(ConfigurationManager.AppSettings["Numimages"].ToString());

            try
            {
                var imageResults = client.Images.SearchAsync(query: queryHotel).Result;

                urlList = new List <string>();

                if (canal == "skype")
                {
                    numm_imagess = 10;
                }

                if (imageResults == null)
                {
                    //nao encontrou nada
                    urlList.Add("");
                }
                else
                {
                    // Image results
                    if (imageResults.Value.Count > 0)
                    {
                        //var firstImageResult = imageResults.Value.First();

                        //Console.WriteLine($"Image result count: {imageResults.Value.Count}");
                        //Console.WriteLine($"First image insights token: {firstImageResult.ImageInsightsToken}");
                        // Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
                        //Console.WriteLine($"First image content url: {firstImageResult.ContentUrl}");

                        for (int i = 0; i < numm_imagess; i++)
                        {
                            urlList.Add(imageResults.Value.ElementAt(i).ContentUrl);
                        }
                    }
                    else
                    {
                        urlList.Add("");
                    }

                    //Console.WriteLine($"Image result total estimated matches: {imageResults.TotalEstimatedMatches}");
                    //Console.WriteLine($"Image result next offset: {imageResults.NextOffset}");

                    //// Pivot suggestions
                    //if (imageResults.PivotSuggestions.Count > 0)
                    //{
                    //    var firstPivot = imageResults.PivotSuggestions.First();

                    //    Console.WriteLine($"Pivot suggestion count: {imageResults.PivotSuggestions.Count}");
                    //    Console.WriteLine($"First pivot: {firstPivot.Pivot}");

                    //    if (firstPivot.Suggestions.Count > 0)
                    //    {
                    //        var firstSuggestion = firstPivot.Suggestions.First();

                    //        Console.WriteLine($"Suggestion count: {firstPivot.Suggestions.Count}");
                    //        Console.WriteLine($"First suggestion text: {firstSuggestion.Text}");
                    //        Console.WriteLine($"First suggestion web search url: {firstSuggestion.WebSearchUrl}");
                    //    }
                    //    else
                    //    {
                    //        Console.WriteLine("Couldn't find suggestions!");
                    //    }
                    //}
                    //else
                    //{
                    //    Console.WriteLine("Couldn't find pivot suggestions!");
                    //}

                    //// Query expansions
                    //if (imageResults.QueryExpansions.Count > 0)
                    //{
                    //    var firstQueryExpansion = imageResults.QueryExpansions.First();

                    //    Console.WriteLine($"Query expansion count: {imageResults.QueryExpansions.Count}");
                    //    Console.WriteLine($"First query expansion text: {firstQueryExpansion.Text}");
                    //    Console.WriteLine($"First query expansion search link: {firstQueryExpansion.SearchLink}");
                    //}
                    //else
                    //{
                    //    Console.WriteLine("Couldn't find query expansions!");
                    //}
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }

            return(urlList);
        }
Ejemplo n.º 21
0
 public PictureService(ImageSearchAPI imageSearchApi, IHttpClientFactory clientFactory)
 {
     _imageSearchApi = imageSearchApi;
     _clientFactory  = clientFactory;
 }
Ejemplo n.º 22
0
        public static void ImageSearch(string subscriptionKey)
        {
            var client = new ImageSearchAPI(new ApiKeyServiceClientCredentials(subscriptionKey));

            try
            {
                var imageResults = client.Images.SearchAsync(query: "canadian rockies").Result;
                Console.WriteLine("Search images for query \"canadian rockies\"");

                if (imageResults == null)
                {
                    Console.WriteLine("No image result data.");
                }
                else
                {
                    // Image results
                    if (imageResults.Value.Count > 0)
                    {
                        var firstImageResult = imageResults.Value.First();

                        Console.WriteLine($"Image result count: {imageResults.Value.Count}");
                        Console.WriteLine($"First image insights token: {firstImageResult.ImageInsightsToken}");
                        Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}");
                        Console.WriteLine($"First image content url: {firstImageResult.ContentUrl}");
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find image results!");
                    }

                    Console.WriteLine($"Image result total estimated matches: {imageResults.TotalEstimatedMatches}");
                    Console.WriteLine($"Image result next offset: {imageResults.NextOffset}");

                    // Pivot suggestions
                    if (imageResults.PivotSuggestions.Count > 0)
                    {
                        var firstPivot = imageResults.PivotSuggestions.First();

                        Console.WriteLine($"Pivot suggestion count: {imageResults.PivotSuggestions.Count}");
                        Console.WriteLine($"First pivot: {firstPivot.Pivot}");

                        if (firstPivot.Suggestions.Count > 0)
                        {
                            var firstSuggestion = firstPivot.Suggestions.First();

                            Console.WriteLine($"Suggestion count: {firstPivot.Suggestions.Count}");
                            Console.WriteLine($"First suggestion text: {firstSuggestion.Text}");
                            Console.WriteLine($"First suggestion web search url: {firstSuggestion.WebSearchUrl}");
                        }
                        else
                        {
                            Console.WriteLine("Couldn't find suggestions!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find pivot suggestions!");
                    }

                    // Query expansions
                    if (imageResults.QueryExpansions.Count > 0)
                    {
                        var firstQueryExpansion = imageResults.QueryExpansions.First();

                        Console.WriteLine($"Query expansion count: {imageResults.QueryExpansions.Count}");
                        Console.WriteLine($"First query expansion text: {firstQueryExpansion.Text}");
                        Console.WriteLine($"First query expansion search link: {firstQueryExpansion.SearchLink}");
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find query expansions!");
                    }
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Encountered exception. " + ex.Message);
            }
        }