UWP Key Phrase Extraction Using Cognitive Service Text Anaytics API

Before reading this article, please go through the following articles.

  1. Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
  2. Getting Started With Microsoft Azure Cognitive Services - Text Analytics API

Microsoft Cognitive Services (formerly Project Oxford) are a set of APIs, SDKs and services available to developers to make their applications more intelligent, engaging and discoverable. Microsoft Cognitive Services expands on Microsoft’s evolving portfolio of machine learning APIs and enables developers to easily add intelligent features. Microsoft Cognitive Services let you build apps with powerful algorithms using just a few lines of code. They work across devices and platforms such as iOS, Android, and Windows, keep improving, and are easy to set up.

Text Analytics API, as described by Microsoft, is designed to detect sentiment, key phrases, topics, and language from your text.

Reading this article, you can learn how to do Cognitive Text Analytics API – Key Phrase Extraction in Universal Windows apps development with Azure, XAML and Visual C#.

The following important tools are required for developing UWP,

  1. Windows 10 (Recommended)
  2. Visual Studio 2015 Community Edition (It is a free software available online)
  3. Cognitive Service Text Analytics API Key (using azure Getting Started With Microsoft Azure Cognitive Services - Text Analytics API)

Now we can discuss step by step App development.

Step 1

Open Visual studio 2015 -> Start -> New Project-> Select Universal (under Visual C#->Windows)-> Blank App -> Give a suitable name for your app (UWPCogTextAnaly)->OK.

Microsoft

After choosing the target and minimum platform version that your app will support, the Project creates App.xaml and MainPage.xaml.

Microsoft

Step 2

Open (double click) the file MainPage.xaml in the Solution Explorer and add the Newtonsoft.Json reference in the project. Right click your project (UWPCogTextAnaly) and select "Manage NuGet Packages".

Microsoft

For adding Newtonsoft.Json reference, choose Browse and Search Newtonsoft.Json. Select the package and install it.

Microsoft

Reference is added to your project

Microsoft

Step 3

Add 2 TextBlock controls, change the name and text property for SampleText.

Microsoft

Add a Button Control, set the Name, and add the Edit icon for Listing Key Phrases.

Microsoft

Step 4

Add GridView Resources, using the code, mentioned below.

  1. <Grid.Resources>  
  2.     <CollectionViewSource x:Name="KeyPhraseResultsCol" Source="{x:Bind KeyPharseResults}" IsSourceGrouped="False" />  
  3. </Grid.Resources>  
Add a GridView Control and set the ItemSource properties.
  1. <GridView x:Name="gvKeyPhr" ItemsSource="{Binding Source={StaticResource KeyPhraseResultsCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="276" Margin="96,233,0,0" VerticalAlignment="Top" Width="1054">  
Microsoft

Add the following code for GridView Item Template for Phrase list.
  1. <GridView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <Border Background="AliceBlue" Width="330" Height="38" Margin="8">  
  4.             <Grid>  
  5.                 <Grid.ColumnDefinitions>  
  6.                     <ColumnDefinition Width="auto" />  
  7.                     <ColumnDefinition/>  
  8.                 </Grid.ColumnDefinitions>  
  9.                 <Grid Grid.Column="1" Margin="3,3,3,10">  
  10.                     <Grid.RowDefinitions>  
  11.                         <RowDefinition Height="auto" />  
  12.                     </Grid.RowDefinitions>  
  13.                     <StackPanel Margin="0,0,0,-143">  
  14.                         <TextBlock TextWrapping="Wrap" Text="{Binding kpco.phrases}" Style="{StaticResource CaptionTextBlockStyle}" Height="28" />  
  15.                     </StackPanel>  
  16.                 </Grid>  
  17.             </Grid>  
  18.         </Border>  
  19.     </DataTemplate>  
  20. </GridView.ItemTemplate>  
Microsoft

Step 5

Add the Click Event method for Phrase find button.

Microsoft

Note

Automatically, the following code will be generated in XAML code view, while we are done in the design view.
  1. <Page x:Class="UWPCogTextAnaly.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogTextAnaly" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">  
  2.     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  3.         <Grid.Resources>  
  4.             <CollectionViewSource x:Name="KeyPhraseResultsCol" Source="{x:Bind KeyPharseResults}" IsSourceGrouped="False" />  
  5.         </Grid.Resources>  
  6.         <TextBlock x:Name="tblTitle" HorizontalAlignment="Left" Margin="324,73,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Text Analytics - Key Phrase Extraction Demo" VerticalAlignment="Top" FontWeight="Bold" FontSize="20" />  
  7.         <TextBlock x:Name="tbltest" HorizontalAlignment="Left" Margin="46,166,0,0" TextWrapping="Wrap" Text="Sample Text : " VerticalAlignment="Top" FontWeight="Bold" FontSize="20" />  
  8.         <TextBlock x:Name="tblText" HorizontalAlignment="Left" Height="36" Margin="178,166,0,0" TextWrapping="Wrap" Text="The manual transmission is a bit twitchy. Also, the vehicle is old-school" VerticalAlignment="Top" Width="748" FontSize="22" />  
  9.         <Button x:Name="btnKeyPhrase" HorizontalAlignment="Left" Margin="952,170,0,0" VerticalAlignment="Top" Click="btnKeyPhrase_Click" RenderTransformOrigin="3.6,0.312" ToolTipService.ToolTip="Click to Key Phrase">  
  10. <SymbolIcon Symbol="Edit"></SymbolIcon>  
  11. </Button>  
  12.         <GridView x:Name="gvKeyPhr" ItemsSource="{Binding Source={StaticResource KeyPhraseResultsCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="276" Margin="96,233,0,0" VerticalAlignment="Top" Width="1054">  
  13.             <GridView.ItemTemplate>  
  14.                 <DataTemplate>  
  15.                     <Border Background="AliceBlue" Width="330" Height="38" Margin="8">  
  16.                         <Grid>  
  17.                             <Grid.ColumnDefinitions>  
  18.                                 <ColumnDefinition Width="auto" />  
  19.                                 <ColumnDefinition/>  
  20.                             </Grid.ColumnDefinitions>  
  21.                             <Grid Grid.Column="1" Margin="3,3,3,10">  
  22.                                 <Grid.RowDefinitions>  
  23.                                     <RowDefinition Height="auto" />  
  24.                                 </Grid.RowDefinitions>  
  25.                                 <StackPanel Margin="0,0,0,-143">  
  26.                                     <TextBlock TextWrapping="Wrap" Text="{Binding kpco.phrases}" Style="{StaticResource CaptionTextBlockStyle}" Height="28" />  
  27.                                 </StackPanel>  
  28.                             </Grid>  
  29.                         </Grid>  
  30.                     </Border>  
  31.                 </DataTemplate>  
  32.             </GridView.ItemTemplate>  
  33.         </GridView>  
  34.   
  35.     </Grid>  
  36. </Page>  
Step 6

Add the following namespaces in Mainpage.xaml.cs for Key Phrases,
  1. using System.Net.Http;  
  2. using System.Threading.Tasks;  
  3. using Newtonsoft.Json.Linq;  
  4. using System.Collections.ObjectModel;  
  5. using System.Net.Http.Headers;  
Step 7

Add the Text Analytics Client keys use Azure service and generate it (For more information, please refer the article Getting Started With Microsoft Azure Cognitive Services - Text Analytics API).

Bing Text Analytics API - Key Phrase Extraction endpoint

https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases?

Add the following code with Azure generated key for Bing Spell Check.
  1. public class Keypharesec {  
  2.     public string phrases {  
  3.         get;  
  4.         set;  
  5.     }  
  6. }  
  7. public class Kpcol {  
  8.     public Keypharesec kpco {  
  9.         get;  
  10.         set;  
  11.     }  
  12. }  
  13. static string requestString;  
  14. public ObservableCollection < Kpcol > KeyPharseResults {  
  15.     get;  
  16.     set;  
  17. } = new ObservableCollection < Kpcol > ();  
  18. private async void btnKeyPhrase_Click(object sender, RoutedEventArgs e) {  
  19.     var kp = await getKeyPhrase();  
  20.     for (int i = 0; i < kp.Count(); i++) {  
  21.         Keypharesec kc = kp.ElementAt(i);  
  22.         KeyPharseResults.Add(new Kpcol {  
  23.             kpco = kc  
  24.         });  
  25.     }  
  26. }  
  27. static async Task < IEnumerable < Keypharesec >> getKeyPhrase() {  
  28.     List < Keypharesec > phrases = new List < Keypharesec > ();  
  29.     var client = new HttpClient();  
  30.     string language = "en";  
  31.     string[] input = new string[] {  
  32.         "The manual transmission is a bit twitchy. Also, the vehicle is old-school"  
  33.     };  
  34.     if (input != null) {  
  35.         // Request body.  
  36.         requestString = "{\"documents\":[";  
  37.         for (int i = 0; i < input.Length; i++) {  
  38.             requestString += string.Format("{{\"id\":\"{0}\",\"text\":\"{1}\", \"language\":\"{2}\"}}", i, input[i].Replace("\"""'"), language);  
  39.             if (i != input.Length - 1) {  
  40.                 requestString += ",";  
  41.             }  
  42.         }  
  43.         requestString += "]}";  
  44.     }  
  45.     client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Key>");  
  46.     var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases?";  
  47.     HttpResponseMessage response;  
  48.     byte[] byteData = System.Text.Encoding.UTF8.GetBytes(requestString);  
  49.     using(var content = new ByteArrayContent(byteData)) {  
  50.         content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  51.         response = await client.PostAsync(uri, content);  
  52.     }  
  53.     string content1 = await response.Content.ReadAsStringAsync();  
  54.     if (!response.IsSuccessStatusCode) {  
  55.         throw new Exception("Text Analytics failed. " + content1);  
  56.     }  
  57.     dynamic data = JObject.Parse(content1);  
  58.     if (data.documents != null) {  
  59.         for (int i = 0; i < data.documents.Count; i++) {  
  60.             for (int j = 0; j < data.documents[i].keyPhrases.Count; j++) {  
  61.                 phrases.Add(new Keypharesec {  
  62.                     phrases = data.documents[i].keyPhrases[j]  
  63.                 });  
  64.             }  
  65.         }  
  66.     }  
  67.     return phrases;  
  68. }  
Step 8

Deploy your app in Local Machine. The output of the UWPCogTextAnaly app is,

Microsoft

After clicking the Button

Microsoft

Summary

Now, you  have successfully extracted the Key Phrases using Cognitive Service Text Analytics API, Azure, XAML AND C# with UWP environment.

If you are interested, please read the UWP Cognitive Service articles, mentioned below.
  1. Cognitive Service Bing Spell Check API Using Azure, XAML And C#
  2. Calchistogram Method In Cognitive Service Academic Knowledge API
  3. Interpret Method Output Value To Evaluate Method Expression In Cognitive Service Academic Knowledge API
  4. Cognitive Service Academic Knowledge API - Evaluate Method Using UWP With Azure, XAML And C#
  5. Cognitive Service Bing Web Search API Using UWP With Azure, XAML And C#
  6. Cognitive Service Bing Video Search API Using UWP With Azure, XAML And C#
  7. Cognitive Service Bing Image Search API Using UWP With Azure, XAML And C#
  8. Cognitive Service Bing News Search API Using UWP With Azure, XAML And C#
  9. Cognitive Service Bing AutoSuggest API Using UWP With Azure, XAML And C#
  10. Multiple People Emotions In UWP With Cognitive Service Emotion API, Azure, XAML And C#
  11. Cognitive Service Emotion API In UWP With Azure, XAML And C#
  12. Retrieving Face Attributes Using Cognitive Service Face API In UWP With Azure, XAML And C#
  13. Cognitive Service Face API, Using UWP With Azure, XAML And C#