WPF Based on Azure for Cognitive Services Emotion Analysis Language Detection Key Phrase Extraction

This article is mainly about the Azure-based cognitive service of Amway, mainly text cognitive service, which can analyze the mood of the input text, and determine the language of the current input text.

This article is divided into two parts, one is the configuration on Azure and the other is the use of the WPF side

On Azure, I use Century Connected's one-dollar subscription, which allows me to subscribe for a month's trial, which is why I'm writing Azure-related blogs these days

Log in to the Azure console and create a new cognitive service. The basic idea is that the interface will change. Microsoft's interface will change, so I won't go into details.

This service is part of the Azure-side deployment when a new one is completed

Before you start, ask your partner to see if the pricing layer is free. Click Resource Management, click on the pricing layer, select Free, and click the Select button below.

Next you need to copy and paste the key and access address by clicking on the key and endpoint

In the picture above, you can see that there are two keys. In fact, either of them can be used in the code. Put two keys here just to make another one available after one has failed

Create a new WPF project, Install it through NuGet Microsoft.Azure.CognitiveServices.Language.TextAnalytics Library, this is version 2.1, the latest version is preview version 3.0.However, the 3.0 preview version requires support from the Azure server. The current version of Microsoft in China is not supported. If you use the 3.0 preview version, you will be prompted

{code: "404", message: "Resource not found"}

Installation required for 3.0 Preview Azure.AI.TextAnalytics library

Installing the NuGet library allows you to modify csproj's methods

    <!--<PackageReference Include="Azure.AI.TextAnalytics" Version="1.0.0-preview.4" />-->
    <PackageReference Include="Microsoft.Azure.CognitiveServices.Language.TextAnalytics" Version="4.0.0" />

The commented out library is a 3.0 preview version, and is it 2020.5 or preview now

Add a simple interface to WPF

            <RowDefinition Height="Auto"></RowDefinition>
            <TextBox x:Name="Text" Margin="10,10,10,10" TextWrapping="Wrap" AcceptsReturn="True"></TextBox>
        <Grid Grid.Row="1">
            <TextBox x:Name="ShowText" Margin="10,10,10,10" IsReadOnly="True" TextWrapping="Wrap"></TextBox>
        <StackPanel Margin="10,10,10,10" Grid.Row="2" Orientation="Horizontal">
                <Style TargetType="Button">
                    <Setter Property="Margin" Value="10,10,10,10"></Setter>
            <Button Content="Emotional Analysis" Click="SentimentAnalysis_OnClick"></Button>
            <Button Content="Language Detection" Click="LanguageDetection_OnClick"></Button>
            <Button Content="Named Entity Recognition (NER)" Click="RecognizeEntities_OnClick"></Button>
            <Button Content="Key Phrase Extraction" Click="KeyPhraseExtraction_OnClick"></Button>

You need to create a client model before you can use it, and you need to pass in the key s and endpoints you just copied, which are also the access addresses

        private static TextAnalyticsClient GetAnalyticsClient()
            var key = "d131f725093f460c99a09580beba34ed";
            var endpoint = "https://lindexi.cognitiveservices.azure.cn/";

            var credentials = new ApiKeyServiceClientCredentials(key);
            TextAnalyticsClient client = new TextAnalyticsClient(credentials)
                Endpoint = endpoint

            return client;

Please replace the key and endpoint above with your own Azure's

The ApiKeyServiceClientCredentials above are self-implemented classes, see the code

    class ApiKeyServiceClientCredentials : ServiceClientCredentials
        public ApiKeyServiceClientCredentials(string apiKey)
            _apiKey = apiKey;

        public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            request.Headers.Add("Ocp-Apim-Subscription-Key", _apiKey);
            return base.ProcessHttpRequestAsync(request, cancellationToken);

        private readonly string _apiKey;

There are many interesting methods to call when you get the TextAnalyticsClient class. The example in this article uses synchronous methods, but asynchronous methods are recommended for real projects.Using a synchronized method can cause the interface to crash

Here are the various method implementations of the interface

       private void SentimentAnalysis_OnClick(object sender, RoutedEventArgs e)
            var client = GetAnalyticsClient();

            var sentiment = client.Sentiment(Text.Text, "zh");
            ShowText.Text = $"Fraction:{sentiment.Score:0.00} \r\n A score close to 0 indicates negative mood and a score close to 1 indicates positive mood.";

        private void LanguageDetection_OnClick(object sender, RoutedEventArgs e)
            var client = GetAnalyticsClient();
            var detectLanguage = client.DetectLanguage(Text.Text);
            ShowText.Text =
                $"Identify possible languages {detectLanguage.DetectedLanguages.Count} individual \r\n {string.Join("\r\n", detectLanguage.DetectedLanguages.Select(temp => $"language {temp.Name} Fraction {temp.Score:0.00}"))}";

        private void RecognizeEntities_OnClick(object sender, RoutedEventArgs e)
            var client = GetAnalyticsClient();
            var result = client.Entities(Text.Text);
            ShowText.Text = "";
            foreach (var entity in result.Entities)
                ShowText.Text +=
                    $"Name: {entity.Name},\tType: {entity.Type ?? "N/A"},\tSub-Type: {entity.SubType ?? "N/A"} \r\n";
                foreach (var match in entity.Matches)
                    ShowText.Text +=
                        $"\tOffset: {match.Offset},\tLength: {match.Length},\tScore: {match.EntityTypeScore:F3}\r\n";

        private void KeyPhraseExtraction_OnClick(object sender, RoutedEventArgs e)
            var client = GetAnalyticsClient();
            var result = client.KeyPhrases(Text.Text);
            ShowText.Text = $"Key word: {string.Join(";", result.KeyPhrases)}";

Probably working as follows

Emotional analysis can analyze whether a sentence is positive or negative. Scores are used to indicate negative emotions with a score close to 0 and positive emotions with a score close to 1.

Language detection is mainly used to analyze which language the current input text belongs to

If you enter English, you will know that it is currently English

Named entities are used to analyze what certain words in the text belong to, for example, some words are people's names, some words are time, and so on.

Key phrase extraction can be used to extract keywords in a sentence

The overall functionality is still cool, especially with the ease of development.The service text is also very fast for Microsoft in China. It uses synchronous code, but in fact the interface is not card.

Quick Start: Text Analysis Client Library v3 - Azure Cognitive Services

The code for this article is placed in github Welcome to Small Partners

Tags: github

Posted on Thu, 21 May 2020 23:16:38 -0400 by Brian Swan