Introduction

Microsoft Cognitive services is set of cloud-based intelligence APIs for building richer and smarter application development. Cognitive API will use for Search meta data from Photos and video and emotions, sentiment analysis and authenticating speakers via voice verification.

Microsoft Cognitive services

The Computer Vision API will help developers to identify the objects with access to advanced algorithms for processing images and returning image meta data information. In this article, you will learn about Computer Vision API and how to implement Compute Vision API into Bot application.

You can follow below steps for implement object detection in Bot Application

Computer Vision API Key Creation

Computer Vision API returns information about visual content found in an image. You can follow the below steps for creating Vision API key.

  1. Navigate to https://azure.microsoft.com/en-us/try/cognitive-services/

    Microsoft Cognitive services

  2. Click on “Get API Key “or Login with Azure login.
  3. Login with Microsoft Account and Get API key

    Microsoft Cognitive services

  4. Copy API key and store securely, we will use this API key into our application

Step 2 Create New Bot Application

Let's create a new bot application using Visual Studio 2017. Open Visual Studio > Select File > Create New Project (Ctrl + Shift +N) > Select Bot application.

Microsoft Cognitive services

The Bot application template gets created with all the components and all required NuGet references installed in the solutions.

Microsoft Cognitive services

In this solution, we are going edit Messagecontroller and add Service class.

Install Microsoft.ProjectOxford.Vision Nuget Package

The Microsoft project oxford vision nuget package will help with access to cognitive service so Install “Microsoft.ProjectOxford.Vision” Library from the solution

Microsoft Cognitive services

Create Vision Service

Create a new helper class to the project called VisionService that wraps around the functionality from the VisionServiceClient from Cognitive Services and only returns what we currently need.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using System.Web;
  7. using Microsoft.ProjectOxford.Vision;
  8. using Microsoft.ProjectOxford.Vision.Contract;
  9. namespace BotObjectDetection.Service
  10. {
  11. public class VisionService : ICaptionService
  12. {
  13. /// <summary>
  14. /// Microsoft Computer Vision API key.
  15. /// </summary>
  16. private static readonly string ApiKey = "<API Key>";
  17. /// <summary>
  18. /// The set of visual features we want from the Vision API.
  19. /// </summary>
  20. private static readonly VisualFeature[] VisualFeatures = { VisualFeature.Description };
  21. public async Task<string> GetCaptionAsync(string url)
  22. {
  23. var client = new VisionServiceClient(ApiKey);
  24. var result = await client.AnalyzeImageAsync(url, VisualFeatures);
  25. return ProcessAnalysisResult(result);
  26. }
  27. public async Task<string> GetCaptionAsync(Stream stream)
  28. {
  29. var client = new VisionServiceClient(ApiKey);
  30. var result = await client.AnalyzeImageAsync(stream, VisualFeatures);
  31. return ProcessAnalysisResult(result);
  32. }
  33. /// <summary>
  34. /// Processes the analysis result.
  35. /// </summary>
  36. /// <param name="result">The result.</param>
  37. /// <returns>The caption if found, error message otherwise.</returns>
  38. private static string ProcessAnalysisResult(AnalysisResult result)
  39. {
  40. string message = result?.Description?.Captions.FirstOrDefault()?.Text;
  41. return string.IsNullOrEmpty(message) ?
  42. "Couldn't find a caption for this one" :
  43. "I think it's " + message;
  44. }
  45. }
  46. }

In the above helper class, replace vision API key and call the Analyze image client method for identify image meta data

Messages Controller

MessagesController is created by default and it is the main entry point of the application. it will call our helper service class which will handle the interaction with the Microsoft APIs. You can update “Post” method like below

  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Text.RegularExpressions;
  9. using System.Threading.Tasks;
  10. using System.Web.Http;
  11. using BotObjectDetection.Service;
  12. using Microsoft.Bot.Builder.Dialogs;
  13. using Microsoft.Bot.Connector;
  14. namespace BotObjectDetection
  15. {
  16. [BotAuthentication]
  17. public class MessagesController : ApiController
  18. {
  19. private readonly ICaptionService captionService = new VisionService();
  20. /// <summary>
  21. /// POST: api/Messages
  22. /// Receive a message from a user and reply to it
  23. /// </summary>
  24. public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
  25. {
  26. if (activity.Type == ActivityTypes.Message)
  27. {
  28. //await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
  29. var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
  30. string message;
  31. try
  32. {
  33. message = await this.GetCaptionAsync(activity, connector);
  34. }
  35. catch (Exception)
  36. {
  37. message = "I am object Detection Bot , You can Upload or share Image Url ";
  38. }
  39. Activity reply = activity.CreateReply(message);
  40. await connector.Conversations.ReplyToActivityAsync(reply);
  41. }
  42. else
  43. {
  44. HandleSystemMessage(activity);
  45. }
  46. var response = Request.CreateResponse(HttpStatusCode.OK);
  47. return response;
  48. }
  49. private Activity HandleSystemMessage(Activity message)
  50. {
  51. if (message.Type == ActivityTypes.DeleteUserData)
  52. {
  53. // Implement user deletion here
  54. // If we handle user deletion, return a real message
  55. }
  56. else if (message.Type == ActivityTypes.ConversationUpdate)
  57. {
  58. // Handle conversation state changes, like members being added and removed
  59. // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
  60. // Not available in all channels
  61. }
  62. else if (message.Type == ActivityTypes.ContactRelationUpdate)
  63. {
  64. // Handle add/remove from contact lists
  65. // Activity.From + Activity.Action represent what happened
  66. }
  67. else if (message.Type == ActivityTypes.Typing)
  68. {
  69. // Handle knowing tha the user is typing
  70. }
  71. else if (message.Type == ActivityTypes.Ping)
  72. {
  73. }
  74. return null;
  75. }
  76. private async Task<string> GetCaptionAsync(Activity activity, ConnectorClient connector)
  77. {
  78. var imageAttachment = activity.Attachments?.FirstOrDefault(a => a.ContentType.Contains("image"));
  79. if (imageAttachment != null)
  80. {
  81. using (var stream = await GetImageStream(connector, imageAttachment))
  82. {
  83. return await this.captionService.GetCaptionAsync(stream);
  84. }
  85. }
  86. string url;
  87. if (TryParseAnchorTag(activity.Text, out url))
  88. {
  89. return await this.captionService.GetCaptionAsync(url);
  90. }
  91. if (Uri.IsWellFormedUriString(activity.Text, UriKind.Absolute))
  92. {
  93. return await this.captionService.GetCaptionAsync(activity.Text);
  94. }
  95. // If we reach here then the activity is neither an image attachment nor an image URL.
  96. throw new ArgumentException("The activity doesn't contain a valid image attachment or an image URL.");
  97. }
  98. private static async Task<Stream> GetImageStream(ConnectorClient connector, Attachment imageAttachment)
  99. {
  100. using (var httpClient = new HttpClient())
  101. {
  102. var uri = new Uri(imageAttachment.ContentUrl);
  103. return await httpClient.GetStreamAsync(uri);
  104. }
  105. }
  106. private static bool TryParseAnchorTag(string text, out string url)
  107. {
  108. var regex = new Regex("^<a href=\"(?<href>[^\"]*)\">[^<]*</a>$", RegexOptions.IgnoreCase);
  109. url = regex.Matches(text).OfType<Match>().Select(m => m.Groups["href"].Value).FirstOrDefault();
  110. return url != null;
  111. }
  112. }
  113. }

Run Bot Application

The emulator is a desktop application that lets us test and debug our bot on localhost. Now, you can click on "Run the application" in Visual studio and execute in the browser

Microsoft Cognitive services
Test Application on Bot Emulator

You can follow the below steps to test your bot application.

  1. Open Bot Emulator.
  2. Copy the above localhost url and paste it in emulator e.g. - http://localHost:3979
  3. You can append the /api/messages in the above url; e.g. - http://localHost:3979/api/messages.
  4. You won't need to specify Microsoft App ID and Microsoft App Password for localhost testing, so click on "Connect".

    Microsoft Cognitive services Microsoft Cognitive services

Related Article

I have explained about Bot framework Installation, deployment and implementation in the below articles:

  1. Getting Started with Chatbot Using Azure Bot Service
  2. Getting Started with Bots Using Visual Studio 2017
  3. Deploying A Bot to Azure Using Visual Studio 2017
  4. How to Create ChatBot In Xamarin
  5. Getting Started with Dialog Using Microsoft Bot Framework
  6. Getting Started with Prompt Dialog Using Microsoft Bot Framework
  7. Getting Started With Conversational Forms And FormFlow Using Microsoft Bot Framework
  8. Getting Started With Customizing A FormFlow Using Microsoft Bot Framework
  9. Sending Bot Reply Message With Attachment Using Bot Framework
  10. Getting Started With Hero Card Design Using Microsoft Bot Framework
  11. Getting Started With Thumbnail Card Design Using Microsoft Bot Framework
  12. Getting Started With Adaptive Card Design Using Microsoft Bot Framework
  13. Getting Started with Receipt Card Design Using Microsoft Bot Framework
  14. Building Bot Application With Azure AD Login Authentication Using AuthBot
  15. Building Chat Bots With Bing Search Results Using Bot Framework

Summary

In this article, you learned how to create an Intelligent Image Object Detection Bot using Microsoft Cognitive Computer Vision API. If you have any questions/feedback/ issues, please write in the comment box.