UWP Language Detection From Text Using Cognitive Service Text Analytics API

Before reading this article, please go through the articles mentioned below.

  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 are available to the developers to make their Applications more intelligent, engaging and discoverable. Microsoft Cognitive Services expands on Microsoft’s evolving portfolio of machine learning API's and enables the developers to easily add intelligent features. Microsoft Cognitive Services allows you to build apps with the powerful algorithms, using few lines of code. They work across the 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.

Detect Language - API returns the detected language and a numeric score between 0 and 1. It scores close to 1 and indicates 100% certainty, which identified the language as true. A total of 120 languages are supported.

After reading this article, you will know how to detect the languages in the given text, using Cognitive Service Text Analytics API, Universal Windows Apps development with Azure, XAML and Visual C#.

The important tools required to develop UWP are shown below.

  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 the suitable name for your app (UWPTextAnalyLang)->OK.

UWP

After choosing the Target and minimum platform version for your Windows Universal, Application will support and the project creates App.xaml and MainPage.xaml.

UWP

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 (UWPTextAnalyLang) and select Manage NuGet Packages.

UWP

To add Newtonsoft.Json reference, choose browse and search Newtonsoft.Json. Select the package and install it.

UWP

The reference is added to your project.

UWP

Step 3

Add a TextBlock control, change the Name and Text property for Title.

UWP

Add a TextBlock and TextBox control, change the Name and clear the text property to get input text.

UWP

Add a Button Control, set the Name and add the Edit icon for Language Detection.

UWP

Step 4

Add GridView Resources, using the code, mentioned below.

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


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

Step 5

Add the Click event method for button to detect a language.

UWP

Note

Automatically, the code, mentioned below will be generated in XAML code view, while we are done in the design view.
<Page
  1. x: Class = "UWPTextAnalyLang.MainPage"  
  2. xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3. xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"  
  4. xmlns: local = "using:UWPTextAnalyLang"  
  5. xmlns: d = "http://schemas.microsoft.com/expression/blend/2008"  
  6. xmlns: mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"  
  7. mc: Ignorable = "d" > < Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"  
  8. Margin = "-2,0,2,0" > < Grid.Resources > < CollectionViewSource x: Name = "LanguageResultsCol"  
  9. Source = "{x:Bind LanguageResults}"  
  10. IsSourceGrouped = "False" / > < /Grid.Resources> < TextBlock x: Name = "tblTitle"  
  11. HorizontalAlignment = "Left"  
  12. Margin = "228,86,0,0"  
  13. TextWrapping = "Wrap"  
  14. Text = "UWP Language Detection - Coginitive Service Text Analytics API -Demo"  
  15. VerticalAlignment = "Top"  
  16. FontSize = "22"  
  17. FontWeight = "Bold" / > < TextBlock x: Name = "tblLangTit"  
  18. HorizontalAlignment = "Left"  
  19. Margin = "88,169,0,0"  
  20. TextWrapping = "Wrap"  
  21. Text = "Enter Your Text :"  
  22. VerticalAlignment = "Top"  
  23. Height = "32"  
  24. Width = "165"  
  25. FontWeight = "Bold"  
  26. FontSize = "20" / > < TextBox x: Name = "txtText"  
  27. HorizontalAlignment = "Left"  
  28. Margin = "281,169,0,0"  
  29. TextWrapping = "Wrap"  
  30. Text = ""  
  31. VerticalAlignment = "Top"  
  32. Width = "794"  
  33. FontSize = "20" / > < Button x: Name = "btnLangDetect"  
  34. HorizontalAlignment = "Left"  
  35. Margin = "1114,170,0,0"  
  36. VerticalAlignment = "Top"  
  37. Click = "btnLangDetect_Click"  
  38. RenderTransformOrigin = "3.6,0.312"  
  39. ToolTipService.ToolTip = "Click to Languages Detection" > < SymbolIcon Symbol = "Find" > < /SymbolIcon> < /Button> < GridView x: Name = "gvLang"  
  40. ItemsSource = "{Binding Source={StaticResource LanguageResultsCol}}"  
  41. SelectionMode = "None"  
  42. IsItemClickEnabled = "False"  
  43. HorizontalAlignment = "Left"  
  44. Height = "276"  
  45. Margin = "96,233,0,0"  
  46. VerticalAlignment = "Top"  
  47. Width = "1054" > < GridView.ItemTemplate > < DataTemplate > < Border Background = "AliceBlue"  
  48. Width = "330"  
  49. Height = "82"  
  50. Margin = "8" > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width = "auto" / > < ColumnDefinition / > < /Grid.ColumnDefinitions> < Grid Grid.Column = "1"  
  51. Margin = "3,3,3,10" > < Grid.RowDefinitions > < RowDefinition Height = "auto" / > < /Grid.RowDefinitions> < StackPanel Margin = "0,0,0,-143" > < TextBlock TextWrapping = "Wrap"  
  52. Text = "{Binding lgco.name}"  
  53. Style = "{StaticResource CaptionTextBlockStyle}"  
  54. Height = "28" / > < TextBlock TextWrapping = "Wrap"  
  55. Text = "{Binding lgco.isoname}"  
  56. Style = "{StaticResource CaptionTextBlockStyle}"  
  57. Height = "28" / > < TextBlock TextWrapping = "Wrap"  
  58. Text = "{Binding lgco.score}"  
  59. Style = "{StaticResource CaptionTextBlockStyle}"  
  60. Height = "28" / > < /StackPanel> < /Grid> < /Grid> < /Border> < /DataTemplate> < /GridView.ItemTemplate> < /GridView> < /Grid> < /Page>  
Step 6

Add the namespaces, mentioned below in Mainpage.xaml.cs for sentiment analysis.
  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 Text Analytics Client keys use Azure service and Generate it (For More Information, Please refer to the article Getting Started With Microsoft Azure Cognitive Services - Text Analytics API).

Text Analytics API – Detect Language endpoint 

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

Add the code, mentioned below with Azure generated key for Language Detection.
  1. public class languagec {  
  2.     public string name {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string isoname {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string score {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
  15. public class langcol {  
  16.     public languagec lgco {  
  17.         get;  
  18.         set;  
  19.     }  
  20. }  
  21. static string requestString, text;  
  22. public ObservableCollection < langcol > LanguageResults {  
  23.     get;  
  24.     set;  
  25. } = new ObservableCollection < langcol > ();  
  26. private async void btnLangDetect_Click(object sender, RoutedEventArgs e) {  
  27.     Text = txtText.Text;  
  28.     var lg = await getLanguage();  
  29.     for (int i = 0; i < lg.Count(); i++) {  
  30.         languagec lc = lg.ElementAt(i);  
  31.         LanguageResults.Add(new langcol {  
  32.             lgco = lc  
  33.         });  
  34.     }  
  35. }  
  36. static async Task < IEnumerable < languagec >> getLanguage() {  
  37.     List < languagec > lang = new List < languagec > ();  
  38.     var client = new HttpClient();  
  39.     string[] input = new string[] {  
  40.         Text  
  41.     };  
  42.     if (input != null) {  
  43.         // Request body.  
  44.         requestString = "{\"documents\":[";  
  45.         for (int i = 0; i < input.Length; i++) {  
  46.             requestString += string.Format("{{\"id\":\"{0}\",\"text\":\"{1}\"}}", i, input[i].Replace("\"""'"));  
  47.             if (i != input.Length - 1) {  
  48.                 requestString += ",";  
  49.             }  
  50.         }  
  51.         requestString += "]}";  
  52.     }  
  53.     client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""268bab39afce4c8d8e944de02ed722e2");  
  54.     var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages?numberOfLanguagesToDetect=5";  
  55.     HttpResponseMessage response;  
  56.     byte[] byteData = System.Text.Encoding.UTF8.GetBytes(requestString);  
  57.     using(var content = new ByteArrayContent(byteData)) {  
  58.         content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  59.         response = await client.PostAsync(uri, content);  
  60.     }  
  61.     string content1 = await response.Content.ReadAsStringAsync();  
  62.     if (!response.IsSuccessStatusCode) {  
  63.         throw new Exception("Text Analytics failed. " + content1);  
  64.     }  
  65.     dynamic data = JObject.Parse(content1);  
  66.     if (data.documents != null) {  
  67.         for (int i = 0; i < data.documents.Count; i++) {  
  68.             for (int j = 0; j < data.documents[i].detectedLanguages.Count; j++) {  
  69.                 lang.Add(new languagec {  
  70.                     name = data.documents[i].detectedLanguages[j].name,  
  71.                         isoname = data.documents[i].detectedLanguages[j].iso6391Name,  
  72.                         score = data.documents[i].detectedLanguages[j].score,  
  73.                 });  
  74.             }  
  75.         }  
  76.     }  
  77.     return lang;  
  78. }  
UWP

Step 8

Deploy your app in the local machine and the output of the UWPTextAnalyLang app is given below.

UWP

After detecting Japanese language, the screenshot will be, as shown below.

UWP

After detecting Spanish language, the output will be, as shown below.

UWP

Summary

Now, you have successfully detected the language from the given text, using Cognitive Service Text Analytics API, Azure, XAML and C# with UWP environment.

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