Comment reconnaître les intentions avec des critères spéciaux d’entité personnalisés

Le Speech SDK Azure AI services possède une fonctionnalité intégrée afin d’offrir une reconnaissance de l’intention à l’aide des critères spéciaux de langage simple. Une intention est quelque chose que l’utilisateur souhaite faire : fermer une fenêtre, marquer une case à cocher, insérer du texte, etc.

Dans ce guide, vous utilisez le SDK Speech pour développer une application console Cqui dégage des intentions à partir des énoncés vocaux obtenus par le microphone de votre appareil. Vous allez apprendre à effectuer les actions suivantes :

  • Créer un projet Visual Studio faisant référence au package NuGet du kit SDK Speech
  • Créer une configuration de reconnaissance vocale et obtenir un module de reconnaissance de l’intention
  • Ajouter des intentions et des modèles via l’API du kit de développement logiciel (SDK) Speech
  • Ajouter des entités personnalisées via l’API du kit de développement logiciel (SDK) Speech
  • Utiliser la reconnaissance continue pilotée par événements, asynchrone

Quand utiliser des critères spéciaux

Utilisez une correspondance de modèle si :

  • Vous êtes uniquement intéressé par la correspondance stricte avec ce qu’a dit l’utilisateur. Ces modèles correspondent de manière plus agressive qu’une compréhension du langage courant (CLU).
  • Vous n’avez pas accès à un modèle CLU, mais vous souhaitez néanmoins des intentions.

Pour plus d’informations, consultez la vue d’ensemble des critères spéciaux.

Prérequis

Veillez à disposer des éléments suivants avant de commencer à suivre ce guide :

Création d’un projet

Créez un projet d’application console C# dans Visual Studio 2019 et installez le Kit de développement logiciel (SDK) Speech.

Commencer avec du code réutilisable

Nous allons ouvrir Program.cs et ajouter du code qui servira de squelette à notre projet.

using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Intent;

namespace helloworld
{
    class Program
    {
        static void Main(string[] args)
        {
            IntentPatternMatchingWithMicrophoneAsync().Wait();
        }

        private static async Task IntentPatternMatchingWithMicrophoneAsync()
        {
            var config = SpeechConfig.FromSubscription("YOUR_SUBSCRIPTION_KEY", "YOUR_SUBSCRIPTION_REGION");
        }
    }
}

Créer une configuration Speech

Avant de pouvoir initialiser un objet IntentRecognizer, vous devez créer une configuration qui utilise la clé et la région Azure pour la ressource de prédiction de vos Azure AI Services.

  • Remplacez "YOUR_SUBSCRIPTION_KEY" par la clé de prédiction de vos services Azure AI.
  • Remplacez "YOUR_SUBSCRIPTION_REGION" par la région de ressource de vos services Azure AI.

Cet exemple utilise la méthode FromSubscription() pour générer la SpeechConfig. Pour obtenir la liste complète des méthodes disponibles, consultez la rubrique Classe SpeechConfig.

Initialiser IntentRecognizer

Créez maintenant un IntentRecognizer. Insérez ce code juste en dessous de votre configuration Speech.

using (var recognizer = new IntentRecognizer(config))
{
    
}

Ajouter des intentions

Vous devez associer des modèles à un PatternMatchingModel et l’appliquer à IntentRecognizer. Nous allons commencer par créer un PatternMatchingModel et y ajouter quelques intentions.

Notes

Nous pouvons ajouter plusieurs modèles à un PatternMatchingIntent.

Insérez ce code dans le bloc using :

// Creates a Pattern Matching model and adds specific intents from your model. The
// Id is used to identify this model from others in the collection.
var model = new PatternMatchingModel("YourPatternMatchingModelId");

// Creates a pattern that uses groups of optional words. "[Go | Take me]" will match either "Go", "Take me", or "".
var patternWithOptionalWords = "[Go | Take me] to [floor|level] {floorName}";

// Creates a pattern that uses an optional entity and group that could be used to tie commands together.
var patternWithOptionalEntity = "Go to parking [{parkingLevel}]";

// You can also have multiple entities of the same name in a single pattern by adding appending a unique identifier
// to distinguish between the instances. For example:
var patternWithTwoOfTheSameEntity = "Go to floor {floorName:1} [and then go to floor {floorName:2}]";
// NOTE: Both floorName:1 and floorName:2 are tied to the same list of entries. The identifier can be a string
//       and is separated from the entity name by a ':'

// Creates the pattern matching intents and adds them to the model
model.Intents.Add(new PatternMatchingIntent("ChangeFloors", patternWithOptionalWords, patternWithOptionalEntity, patternWithTwoOfTheSameEntity));
model.Intents.Add(new PatternMatchingIntent("DoorControl", "{action} the doors", "{action} doors", "{action} the door", "{action} door"));

Ajouter des entités personnalisées

Pour tirer pleinement parti de la correspondance de modèle, vous pouvez personnaliser vos entités. Nous allons faire de « floorName » une liste des étages disponibles. Nous allons également faire de « parkingLevel » une entité entière.

Insérez ce code sous vos intentions :

// Creates the "floorName" entity and set it to type list.
// Adds acceptable values. NOTE the default entity type is Any and so we do not need
// to declare the "action" entity.
model.Entities.Add(PatternMatchingEntity.CreateListEntity("floorName", EntityMatchMode.Strict, "ground floor", "lobby", "1st", "first", "one", "1", "2nd", "second", "two", "2"));

// Creates the "parkingLevel" entity as a pre-built integer
model.Entities.Add(PatternMatchingEntity.CreateIntegerEntity("parkingLevel"));

Appliquer notre modèle au module de reconnaissance

À présent, il est nécessaire d’appliquer le modèle à IntentRecognizer. Il est possible d’utiliser plusieurs modèles à la fois afin que l’API prenne une collection de modèles.

Insérez ce code sous vos entités :

var modelCollection = new LanguageUnderstandingModelCollection();
modelCollection.Add(model);

recognizer.ApplyLanguageModels(modelCollection);

Reconnaître une intention

À partir de l’objet IntentRecognizer, vous devez appeler la méthode RecognizeOnceAsync(). Cette méthode demande au service Speech de reconnaître la parole en une seule phrase et d’arrêter la reconnaissance vocale une fois que l’expression est identifiée.

Insérez ce code après l’application des modèles de langage :

Console.WriteLine("Say something...");

var result = await recognizer.RecognizeOnceAsync();

Afficher les résultats de la reconnaissance (ou les erreurs)

Lorsque le résultat de la reconnaissance est retourné par le service Speech, nous allons imprimer le résultat.

Insérez ce code en dessous de var result = await recognizer.RecognizeOnceAsync(); :

if (result.Reason == ResultReason.RecognizedIntent)
{
    Console.WriteLine($"RECOGNIZED: Text={result.Text}");
    Console.WriteLine($"       Intent Id={result.IntentId}.");

    var entities = result.Entities;
    switch (result.IntentId)
    {
        case "ChangeFloors":
            if (entities.TryGetValue("floorName", out string floorName))
            {
                Console.WriteLine($"       FloorName={floorName}");
            }

            if (entities.TryGetValue("floorName:1", out floorName))
            {
                Console.WriteLine($"     FloorName:1={floorName}");
            }

            if (entities.TryGetValue("floorName:2", out floorName))
            {
                Console.WriteLine($"     FloorName:2={floorName}");
            }

            if (entities.TryGetValue("parkingLevel", out string parkingLevel))
            {
                Console.WriteLine($"    ParkingLevel={parkingLevel}");
            }

            break;

        case "DoorControl":
            if (entities.TryGetValue("action", out string action))
            {
                Console.WriteLine($"          Action={action}");
            }
            break;
    }
}
else if (result.Reason == ResultReason.RecognizedSpeech)
{
    Console.WriteLine($"RECOGNIZED: Text={result.Text}");
    Console.WriteLine($"    Intent not recognized.");
}
else if (result.Reason == ResultReason.NoMatch)
{
    Console.WriteLine($"NOMATCH: Speech could not be recognized.");
}
else if (result.Reason == ResultReason.Canceled)
{
    var cancellation = CancellationDetails.FromResult(result);
    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

    if (cancellation.Reason == CancellationReason.Error)
    {
        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
        Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
        Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
    }
}

Vérifier votre code

À ce stade, votre code doit ressembler à ceci :

using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Intent;

namespace helloworld
{
    class Program
    {
        static void Main(string[] args)
        {
            IntentPatternMatchingWithMicrophoneAsync().Wait();
        }

        private static async Task IntentPatternMatchingWithMicrophoneAsync()
        {
            var config = SpeechConfig.FromSubscription("YOUR_SUBSCRIPTION_KEY", "YOUR_SUBSCRIPTION_REGION");

            using (var recognizer = new IntentRecognizer(config))
            {
                // Creates a Pattern Matching model and adds specific intents from your model. The
                // Id is used to identify this model from others in the collection.
                var model = new PatternMatchingModel("YourPatternMatchingModelId");

                // Creates a pattern that uses groups of optional words. "[Go | Take me]" will match either "Go", "Take me", or "".
                var patternWithOptionalWords = "[Go | Take me] to [floor|level] {floorName}";

                // Creates a pattern that uses an optional entity and group that could be used to tie commands together.
                var patternWithOptionalEntity = "Go to parking [{parkingLevel}]";

                // You can also have multiple entities of the same name in a single pattern by adding appending a unique identifier
                // to distinguish between the instances. For example:
                var patternWithTwoOfTheSameEntity = "Go to floor {floorName:1} [and then go to floor {floorName:2}]";
                // NOTE: Both floorName:1 and floorName:2 are tied to the same list of entries. The identifier can be a string
                //       and is separated from the entity name by a ':'

                // Adds some intents to look for specific patterns.
                model.Intents.Add(new PatternMatchingIntent("ChangeFloors", patternWithOptionalWords, patternWithOptionalEntity, patternWithTwoOfTheSameEntity));
                model.Intents.Add(new PatternMatchingIntent("DoorControl", "{action} the doors", "{action} doors", "{action} the door", "{action} door"));

                // Creates the "floorName" entity and set it to type list.
                // Adds acceptable values. NOTE the default entity type is Any and so we do not need
                // to declare the "action" entity.
                model.Entities.Add(PatternMatchingEntity.CreateListEntity("floorName", EntityMatchMode.Strict, "ground floor", "lobby", "1st", "first", "one", "1", "2nd", "second", "two", "2"));

                // Creates the "parkingLevel" entity as a pre-built integer
                model.Entities.Add(PatternMatchingEntity.CreateIntegerEntity("parkingLevel"));

                var modelCollection = new LanguageUnderstandingModelCollection();
                modelCollection.Add(model);

                recognizer.ApplyLanguageModels(modelCollection);

                Console.WriteLine("Say something...");

                var result = await recognizer.RecognizeOnceAsync();

                if (result.Reason == ResultReason.RecognizedIntent)
                {
                    Console.WriteLine($"RECOGNIZED: Text={result.Text}");
                    Console.WriteLine($"       Intent Id={result.IntentId}.");

                    var entities = result.Entities;
                    switch (result.IntentId)
                    {
                        case "ChangeFloors":
                            if (entities.TryGetValue("floorName", out string floorName))
                            {
                                Console.WriteLine($"       FloorName={floorName}");
                            }

                            if (entities.TryGetValue("floorName:1", out floorName))
                            {
                                Console.WriteLine($"     FloorName:1={floorName}");
                            }

                            if (entities.TryGetValue("floorName:2", out floorName))
                            {
                                Console.WriteLine($"     FloorName:2={floorName}");
                            }

                            if (entities.TryGetValue("parkingLevel", out string parkingLevel))
                            {
                                Console.WriteLine($"    ParkingLevel={parkingLevel}");
                            }

                            break;

                        case "DoorControl":
                            if (entities.TryGetValue("action", out string action))
                            {
                                Console.WriteLine($"          Action={action}");
                            }
                            break;
                    }
                }
                else if (result.Reason == ResultReason.RecognizedSpeech)
                {
                    Console.WriteLine($"RECOGNIZED: Text={result.Text}");
                    Console.WriteLine($"    Intent not recognized.");
                }
                else if (result.Reason == ResultReason.NoMatch)
                {
                    Console.WriteLine($"NOMATCH: Speech could not be recognized.");
                }
                else if (result.Reason == ResultReason.Canceled)
                {
                    var cancellation = CancellationDetails.FromResult(result);
                    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                    if (cancellation.Reason == CancellationReason.Error)
                    {
                        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                        Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}");
                        Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
                    }
                }
            }
        }
    }
}

Générer et exécuter votre application

Vous êtes maintenant prêt à créer votre application et à tester la reconnaissance vocale à l’aide du service de reconnaissance vocale.

  1. Compiler le code : à partir de la barre de menus de Visual Studio, choisissez Générer>Générer la solution.
  2. Démarrer votre application : dans la barre de menus, choisissez Déboguer>Démarrer le débogage, ou appuyez sur F5.
  3. Démarrer la reconnaissance : vous êtes invité à prononcer une phrase. La langue par défaut est l'anglais. Celle-ci est envoyée au service de reconnaissance vocale, transcrite sous forme de texte, puis affichée sur la console.

Par exemple, si vous dites « me faire passer à l’étage 2 », il doit s’agir de la sortie suivante :

Say something...
RECOGNIZED: Text=Take me to floor 2.
       Intent Id=ChangeFloors.
       FloorName=2

Autre exemple : si vous dites « me faire passer à l’étage 7 », il doit s’agir de la sortie suivante :

Say something...
RECOGNIZED: Text=Take me to floor 7.
    Intent not recognized.

Aucune intention n’a été reconnue, car 7 n’était pas dans notre liste de valeurs valides pour floorName.

Création d’un projet

Créez un projet d’application console C++ dans Visual Studio 2019 et installez le Kit de développement logiciel (SDK) Speech.

Commencer avec du code réutilisable

Nous allons ouvrir helloworld.cpp et ajouter du code qui servira de squelette à notre projet.

#include <iostream>
#include <speechapi_cxx.h>

using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Intent;

int main()
{
    std::cout << "Hello World!\n";

    auto config = SpeechConfig::FromSubscription("YOUR_SUBSCRIPTION_KEY", "YOUR_SUBSCRIPTION_REGION");
}

Créer une configuration Speech

Avant de pouvoir initialiser un objet IntentRecognizer, vous devez créer une configuration qui utilise la clé et la région Azure pour la ressource de prédiction de vos Azure AI Services.

  • Remplacez "YOUR_SUBSCRIPTION_KEY" par la clé de prédiction de vos services Azure AI.
  • Remplacez "YOUR_SUBSCRIPTION_REGION" par la région de ressource de vos services Azure AI.

Cet exemple utilise la méthode FromSubscription() pour générer la SpeechConfig. Pour obtenir la liste complète des méthodes disponibles, consultez la rubrique Classe SpeechConfig.

Initialiser IntentRecognizer

Créez maintenant un IntentRecognizer. Insérez ce code juste en dessous de votre configuration Speech.

    auto intentRecognizer = IntentRecognizer::FromConfig(config);

Ajouter des intentions

Vous devez associer des modèles à un PatternMatchingModel et l’appliquer à IntentRecognizer. Nous allons commencer par créer un PatternMatchingModel et y ajouter quelques intentions. Un PatternMatchingIntent est un struct, c’est pourquoi nous utilisons simplement la syntaxe en ligne.

Notes

Nous pouvons ajouter plusieurs modèles à un PatternMatchingIntent.

auto model = PatternMatchingModel::FromId("myNewModel");

model->Intents.push_back({"Take me to floor {floorName}.", "Go to floor {floorName}."} , "ChangeFloors");
model->Intents.push_back({"{action} the door."}, "OpenCloseDoor");

Ajouter des entités personnalisées

Pour tirer pleinement parti de la correspondance de modèle, vous pouvez personnaliser vos entités. Nous allons faire de « floorName » une liste des étages disponibles.

model->Entities.push_back({ "floorName" , Intent::EntityType::List, Intent::EntityMatchMode::Strict, {"one", "1", "two", "2", "lobby", "ground floor"} });

Appliquer notre modèle au module de reconnaissance

À présent, il est nécessaire d’appliquer le modèle à IntentRecognizer. Il est possible d’utiliser plusieurs modèles à la fois afin que l’API prenne une collection de modèles.

std::vector<std::shared_ptr<LanguageUnderstandingModel>> collection;

collection.push_back(model);
intentRecognizer->ApplyLanguageModels(collection);

Reconnaître une intention

À partir de l’objet IntentRecognizer, vous devez appeler la méthode RecognizeOnceAsync(). Cette méthode demande au service Speech de reconnaître la parole en une seule phrase et d’arrêter la reconnaissance vocale une fois que l’expression est identifiée. Pour faire simple, nous attendons la fin des prochains retours.

Insérez ce code sous vos intentions :

std::cout << "Say something ..." << std::endl;
auto result = intentRecognizer->RecognizeOnceAsync().get();

Afficher les résultats de la reconnaissance (ou les erreurs)

Lorsque le résultat de la reconnaissance est retourné par le service Speech, nous allons imprimer le résultat.

Insérez ce code en dessous de auto result = intentRecognizer->RecognizeOnceAsync().get(); :

switch (result->Reason)
{
case ResultReason::RecognizedSpeech:
        std::cout << "RECOGNIZED: Text = " << result->Text.c_str() << std::endl;
        std::cout << "NO INTENT RECOGNIZED!" << std::endl;
        break;
case ResultReason::RecognizedIntent:
    std::cout << "RECOGNIZED: Text = " << result->Text.c_str() << std::endl;
    std::cout << "  Intent Id = " << result->IntentId.c_str() << std::endl;
    auto entities = result->GetEntities();
    if (entities.find("floorName") != entities.end())
    {
        std::cout << "  Floor name: = " << entities["floorName"].c_str() << std::endl;
    }

    if (entities.find("action") != entities.end())
    {
        std::cout << "  Action: = " << entities["action"].c_str() << std::endl;
    }

    break;
case ResultReason::NoMatch:
{
    auto noMatch = NoMatchDetails::FromResult(result);
    switch (noMatch->Reason)
    {
    case NoMatchReason::NotRecognized:
        std::cout << "NOMATCH: Speech was detected, but not recognized." << std::endl;
        break;
    case NoMatchReason::InitialSilenceTimeout:
        std::cout << "NOMATCH: The start of the audio stream contains only silence, and the service timed out waiting for speech." << std::endl;
        break;
    case NoMatchReason::InitialBabbleTimeout:
        std::cout << "NOMATCH: The start of the audio stream contains only noise, and the service timed out waiting for speech." << std::endl;
        break;
    case NoMatchReason::KeywordNotRecognized:
        std::cout << "NOMATCH: Keyword not recognized" << std::endl;
        break;
    }
    break;
}
case ResultReason::Canceled:
{
    auto cancellation = CancellationDetails::FromResult(result);

    if (!cancellation->ErrorDetails.empty())
    {
        std::cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails.c_str() << std::endl;
        std::cout << "CANCELED: Did you set the speech resource key and region values?" << std::endl;
    }
}
default:
    break;
}

Vérifier votre code

À ce stade, votre code doit ressembler à ceci :

#include <iostream>
#include <speechapi_cxx.h>

using namespace Microsoft::CognitiveServices::Speech;
using namespace Microsoft::CognitiveServices::Speech::Intent;

int main()
{
    auto config = SpeechConfig::FromSubscription("YOUR_SUBSCRIPTION_KEY", "YOUR_SUBSCRIPTION_REGION");
    auto intentRecognizer = IntentRecognizer::FromConfig(config);

    auto model = PatternMatchingModel::FromId("myNewModel");

    model->Intents.push_back({"Take me to floor {floorName}.", "Go to floor {floorName}."} , "ChangeFloors");
    model->Intents.push_back({"{action} the door."}, "OpenCloseDoor");

    model->Entities.push_back({ "floorName" , Intent::EntityType::List, Intent::EntityMatchMode::Strict, {"one", "1", "two", "2", "lobby", "ground floor"} });

    std::vector<std::shared_ptr<LanguageUnderstandingModel>> collection;

    collection.push_back(model);
    intentRecognizer->ApplyLanguageModels(collection);

    std::cout << "Say something ..." << std::endl;

    auto result = intentRecognizer->RecognizeOnceAsync().get();

    switch (result->Reason)
    {
    case ResultReason::RecognizedSpeech:
        std::cout << "RECOGNIZED: Text = " << result->Text.c_str() << std::endl;
        std::cout << "NO INTENT RECOGNIZED!" << std::endl;
        break;
    case ResultReason::RecognizedIntent:
        std::cout << "RECOGNIZED: Text = " << result->Text.c_str() << std::endl;
        std::cout << "  Intent Id = " << result->IntentId.c_str() << std::endl;
        auto entities = result->GetEntities();
        if (entities.find("floorName") != entities.end())
        {
            std::cout << "  Floor name: = " << entities["floorName"].c_str() << std::endl;
        }

        if (entities.find("action") != entities.end())
        {
            std::cout << "  Action: = " << entities["action"].c_str() << std::endl;
        }

        break;
    case ResultReason::NoMatch:
    {
        auto noMatch = NoMatchDetails::FromResult(result);
        switch (noMatch->Reason)
        {
        case NoMatchReason::NotRecognized:
            std::cout << "NOMATCH: Speech was detected, but not recognized." << std::endl;
            break;
        case NoMatchReason::InitialSilenceTimeout:
            std::cout << "NOMATCH: The start of the audio stream contains only silence, and the service timed out waiting for speech." << std::endl;
            break;
        case NoMatchReason::InitialBabbleTimeout:
            std::cout << "NOMATCH: The start of the audio stream contains only noise, and the service timed out waiting for speech." << std::endl;
            break;
        case NoMatchReason::KeywordNotRecognized:
            std::cout << "NOMATCH: Keyword not recognized." << std::endl;
            break;
        }
        break;
    }
    case ResultReason::Canceled:
    {
        auto cancellation = CancellationDetails::FromResult(result);

        if (!cancellation->ErrorDetails.empty())
        {
            std::cout << "CANCELED: ErrorDetails=" << cancellation->ErrorDetails.c_str() << std::endl;
            std::cout << "CANCELED: Did you set the speech resource key and region values?" << std::endl;
        }
    }
    default:
        break;
    }
}

Générer et exécuter votre application

Vous êtes maintenant prêt à créer votre application et à tester la reconnaissance vocale à l’aide du service de reconnaissance vocale.

  1. Compiler le code : à partir de la barre de menus de Visual Studio, choisissez Générer>Générer la solution.
  2. Démarrer votre application : dans la barre de menus, choisissez Déboguer>Démarrer le débogage, ou appuyez sur F5.
  3. Démarrer la reconnaissance : vous êtes invité à prononcer une phrase. La langue par défaut est l'anglais. Celle-ci est envoyée au service de reconnaissance vocale, transcrite sous forme de texte, puis affichée sur la console.

Par exemple, si vous dites « me faire passer à l’étage 2 », il doit s’agir de la sortie suivante :

Say something ...
RECOGNIZED: Text = Take me to floor 2.
  Intent Id = ChangeFloors
  Floor name: = 2

Autre exemple : si vous dites « me faire passer à l’étage 7 », il doit s’agir de la sortie suivante :

Say something ...
RECOGNIZED: Text = Take me to floor 7.
NO INTENT RECOGNIZED!

L’ID d’intention est vide, car 7 ne figure pas dans notre liste.

Documentation de référence | Exemples supplémentaires sur GitHub

Dans ce guide de démarrage rapide, vous installez le SDK Speech pour Java.

Plateforme requise

Choisissez votre environnement cible :

Le Kit de développement logiciel (SDK) Speech pour Java est compatible avec Windows, Linux et macOS.

Sur Windows, vous devez utiliser l’architecture cible 64 bits. Vous avez besoin de Windows 10 ou une version ultérieure.

Installez le Redistribuable Microsoft Visual C++ pour Visual Studio 2015, 2017, 2019 et 2022 pour votre plateforme. La toute première installation de ce package peut nécessiter un redémarrage.

Le SDK Speech pour Java ne prend pas en charge Windows sur ARM64.

Installez un kit de développement Java tel que Azul Zulu OpenJDK. La build Microsoft d’OpenJDK ou le JDK de votre choix doivent également fonctionner.

Installer le Kit de développement logiciel (SDK) Speech pour Java

Certaines instructions utilisent une version spécifique du Kit de développement logiciel (SDK) comme 1.24.2. Pour vérifier la dernière version, recherchez dans notre dépôt GitHub.

Choisissez votre environnement cible :

Ce guide explique comment installer le Kit de développement logiciel (SDK) Speech pour Java sur le runtime Java.

Systèmes d’exploitation pris en charge

Le Kit de développement logiciel (SDK) Speech pour le package Java est disponible pour les systèmes d’exploitation suivants :

Procédez comme suit pour installer le Kit de développement logiciel (SDK) Speech pour Java à l’aide d’Apache Maven :

  1. Installez Apache Maven.

  2. Ouvrez une invite de commandes à l’emplacement où vous souhaitez placer le nouveau projet, puis créez un fichier pom.xml.

  3. Copiez le contenu XML suivant dans pom.xml :

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.microsoft.cognitiveservices.speech.samples</groupId>
        <artifactId>quickstart-eclipse</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <build>
            <sourceDirectory>src</sourceDirectory>
            <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                <source>1.8</source>
                <target>1.8</target>
                </configuration>
            </plugin>
            </plugins>
        </build>
        <dependencies>
            <dependency>
            <groupId>com.microsoft.cognitiveservices.speech</groupId>
            <artifactId>client-sdk</artifactId>
            <version>1.37.0</version>
            </dependency>
        </dependencies>
    </project>
    
  4. Exécutez la commande Maven suivante pour installer le kit de développement logiciel (SDK) Speech et les dépendances.

    mvn clean dependency:copy-dependencies
    

Commencer avec du code réutilisable

  1. Ouvrez Main.java à partir du dir src.

  2. Remplacez le contenu du fichier par ce qui suit :

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.concurrent.ExecutionException;


import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.intent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        IntentPatternMatchingWithMicrophone();
    }

    public static void IntentPatternMatchingWithMicrophone() throws InterruptedException, ExecutionException {
        SpeechConfig config = SpeechConfig.fromSubscription("YOUR_SUBSCRIPTION_KEY", "YOUR_SUBSCRIPTION_REGION");
    }
}

Créer une configuration Speech

Avant de pouvoir initialiser un objet IntentRecognizer, vous devez créer une configuration qui utilise la clé et la région Azure pour la ressource de prédiction de vos Azure AI Services.

  • Remplacez "YOUR_SUBSCRIPTION_KEY" par la clé de prédiction de vos services Azure AI.
  • Remplacez "YOUR_SUBSCRIPTION_REGION" par la région de ressource de vos services Azure AI.

Cet exemple utilise la méthode fromSubscription() pour générer la SpeechConfig. Pour obtenir la liste complète des méthodes disponibles, consultez la rubrique Classe SpeechConfig.

Initialiser IntentRecognizer

Créez maintenant un IntentRecognizer. Insérez ce code juste en dessous de votre configuration Speech. Nous procédons ainsi pour tâcher de tirer parti de l’interface à fermeture automatique.

try (IntentRecognizer recognizer = new IntentRecognizer(config)) {

}

Ajouter des intentions

Vous devez associer des modèles à un PatternMatchingModel et l’appliquer à IntentRecognizer. Nous allons commencer par créer un PatternMatchingModel et y ajouter quelques intentions.

Notes

Nous pouvons ajouter plusieurs modèles à un PatternMatchingIntent.

Insérez ce code dans le bloc try :

// Creates a Pattern Matching model and adds specific intents from your model. The
// Id is used to identify this model from others in the collection.
PatternMatchingModel model = new PatternMatchingModel("YourPatternMatchingModelId");

// Creates a pattern that uses groups of optional words. "[Go | Take me]" will match either "Go", "Take me", or "".
String patternWithOptionalWords = "[Go | Take me] to [floor|level] {floorName}";

// Creates a pattern that uses an optional entity and group that could be used to tie commands together.
String patternWithOptionalEntity = "Go to parking [{parkingLevel}]";

// You can also have multiple entities of the same name in a single pattern by adding appending a unique identifier
// to distinguish between the instances. For example:
String patternWithTwoOfTheSameEntity = "Go to floor {floorName:1} [and then go to floor {floorName:2}]";
// NOTE: Both floorName:1 and floorName:2 are tied to the same list of entries. The identifier can be a string
//       and is separated from the entity name by a ':'

// Creates the pattern matching intents and adds them to the model
model.getIntents().put(new PatternMatchingIntent("ChangeFloors", patternWithOptionalWords, patternWithOptionalEntity, patternWithTwoOfTheSameEntity));
model.getIntents().put(new PatternMatchingIntent("DoorControl", "{action} the doors", "{action} doors", "{action} the door", "{action} door"));

Ajouter des entités personnalisées

Pour tirer pleinement parti de la correspondance de modèle, vous pouvez personnaliser vos entités. Nous allons faire de « floorName » une liste des étages disponibles. Nous allons également faire de « parkingLevel » une entité entière.

Insérez ce code sous vos intentions :

// Creates the "floorName" entity and set it to type list.
// Adds acceptable values. NOTE the default entity type is Any and so we do not need
// to declare the "action" entity.
model.getEntities().put(PatternMatchingEntity.CreateListEntity("floorName", PatternMatchingEntity.EntityMatchMode.Strict, "ground floor", "lobby", "1st", "first", "one", "1", "2nd", "second", "two", "2"));

// Creates the "parkingLevel" entity as a pre-built integer
model.getEntities().put(PatternMatchingEntity.CreateIntegerEntity("parkingLevel"));

Appliquer notre modèle au module de reconnaissance

À présent, il est nécessaire d’appliquer le modèle à IntentRecognizer. Il est possible d’utiliser plusieurs modèles à la fois afin que l’API prenne une collection de modèles.

Insérez ce code sous vos entités :

ArrayList<LanguageUnderstandingModel> modelCollection = new ArrayList<LanguageUnderstandingModel>();
modelCollection.add(model);

recognizer.applyLanguageModels(modelCollection);

Reconnaître une intention

À partir de l’objet IntentRecognizer, vous devez appeler la méthode RecognizeOnceAsync(). Cette méthode demande au service Speech de reconnaître la parole en une seule phrase et d’arrêter la reconnaissance vocale une fois que l’expression est identifiée.

Insérez ce code après l’application des modèles de langage :

System.out.println("Say something...");

IntentRecognitionResult result = recognizer.recognizeOnceAsync().get();

Afficher les résultats de la reconnaissance (ou les erreurs)

Lorsque le résultat de la reconnaissance est retourné par le service Speech, nous allons imprimer le résultat.

Insérez ce code en dessous de IntentRecognitionResult result = recognizer.recognizeOnceAsync.get(); :

if (result.getReason() == ResultReason.RecognizedSpeech) {
    System.out.println("RECOGNIZED: Text= " + result.getText());
    System.out.println(String.format("%17s", "Intent not recognized."));
}
else if (result.getReason() == ResultReason.RecognizedIntent)
{
    System.out.println("RECOGNIZED: Text= " + result.getText());
    System.out.println(String.format("%17s %s", "Intent Id=", result.getIntentId() + "."));
    Dictionary<String, String> entities = result.getEntities();

    switch (result.getIntentId())
    {
        case "ChangeFloors":
            if (entities.get("floorName") != null) {
                System.out.println(String.format("%17s %s", "FloorName=", entities.get("floorName")));
            }
            if (entities.get("floorName:1") != null) {
                System.out.println(String.format("%17s %s", "FloorName:1=", entities.get("floorName:1")));
            }
            if (entities.get("floorName:2") != null) {
                System.out.println(String.format("%17s %s", "FloorName:2=", entities.get("floorName:2")));
            }
            if (entities.get("parkingLevel") != null) {
                System.out.println(String.format("%17s %s", "ParkingLevel=", entities.get("parkingLevel")));
            }
            break;
        case "DoorControl":
            if (entities.get("action") != null) {
                System.out.println(String.format("%17s %s", "Action=", entities.get("action")));
            }
            break;
    }
}
else if (result.getReason() == ResultReason.NoMatch) {
    System.out.println("NOMATCH: Speech could not be recognized.");
}
else if (result.getReason() == ResultReason.Canceled) {
    CancellationDetails cancellation = CancellationDetails.fromResult(result);
    System.out.println("CANCELED: Reason=" + cancellation.getReason());

    if (cancellation.getReason() == CancellationReason.Error)
    {
        System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
        System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
        System.out.println("CANCELED: Did you update the subscription info?");
    }
}

Vérifier votre code

À ce stade, votre code doit ressembler à ceci :

package quickstart;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.Dictionary;

import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.intent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        IntentPatternMatchingWithMicrophone();
    }

    public static void IntentPatternMatchingWithMicrophone() throws InterruptedException, ExecutionException {
        SpeechConfig config = SpeechConfig.fromSubscription("YOUR_SUBSCRIPTION_KEY", "YOUR_SUBSCRIPTION_REGION");
        try (IntentRecognizer recognizer = new IntentRecognizer(config)) {
            // Creates a Pattern Matching model and adds specific intents from your model. The
            // Id is used to identify this model from others in the collection.
            PatternMatchingModel model = new PatternMatchingModel("YourPatternMatchingModelId");

            // Creates a pattern that uses groups of optional words. "[Go | Take me]" will match either "Go", "Take me", or "".
            String patternWithOptionalWords = "[Go | Take me] to [floor|level] {floorName}";

            // Creates a pattern that uses an optional entity and group that could be used to tie commands together.
            String patternWithOptionalEntity = "Go to parking [{parkingLevel}]";

            // You can also have multiple entities of the same name in a single pattern by adding appending a unique identifier
            // to distinguish between the instances. For example:
            String patternWithTwoOfTheSameEntity = "Go to floor {floorName:1} [and then go to floor {floorName:2}]";
            // NOTE: Both floorName:1 and floorName:2 are tied to the same list of entries. The identifier can be a string
            // and is separated from the entity name by a ':'

            // Creates the pattern matching intents and adds them to the model
            model.getIntents().put(new PatternMatchingIntent("ChangeFloors", patternWithOptionalWords, patternWithOptionalEntity, patternWithTwoOfTheSameEntity));
            model.getIntents().put(new PatternMatchingIntent("DoorControl", "{action} the doors", "{action} doors", "{action} the door", "{action} door"));

            // Creates the "floorName" entity and set it to type list.
            // Adds acceptable values. NOTE the default entity type is Any and so we do not need
            // to declare the "action" entity.
            model.getEntities().put(PatternMatchingEntity.CreateListEntity("floorName", PatternMatchingEntity.EntityMatchMode.Strict, "ground floor", "lobby", "1st", "first", "one", "1", "2nd", "second", "two", "2"));

            // Creates the "parkingLevel" entity as a pre-built integer
            model.getEntities().put(PatternMatchingEntity.CreateIntegerEntity("parkingLevel"));

            ArrayList<LanguageUnderstandingModel> modelCollection = new ArrayList<LanguageUnderstandingModel>();
            modelCollection.add(model);

            recognizer.applyLanguageModels(modelCollection);

            System.out.println("Say something...");

            IntentRecognitionResult result = recognizer.recognizeOnceAsync().get();

            if (result.getReason() == ResultReason.RecognizedSpeech) {
                System.out.println("RECOGNIZED: Text= " + result.getText());
                System.out.println(String.format("%17s", "Intent not recognized."));
            }
            else if (result.getReason() == ResultReason.RecognizedIntent)
            {
                System.out.println("RECOGNIZED: Text= " + result.getText());
                System.out.println(String.format("%17s %s", "Intent Id=", result.getIntentId() + "."));
                Dictionary<String, String> entities = result.getEntities();

                switch (result.getIntentId())
                {
                    case "ChangeFloors":
                        if (entities.get("floorName") != null) {
                            System.out.println(String.format("%17s %s", "FloorName=", entities.get("floorName")));
                        }
                        if (entities.get("floorName:1") != null) {
                            System.out.println(String.format("%17s %s", "FloorName:1=", entities.get("floorName:1")));
                        }
                        if (entities.get("floorName:2") != null) {
                            System.out.println(String.format("%17s %s", "FloorName:2=", entities.get("floorName:2")));
                        }
                        if (entities.get("parkingLevel") != null) {
                            System.out.println(String.format("%17s %s", "ParkingLevel=", entities.get("parkingLevel")));
                        }
                        break;

                    case "DoorControl":
                        if (entities.get("action") != null) {
                            System.out.println(String.format("%17s %s", "Action=", entities.get("action")));
                        }
                        break;
                }
            }
            else if (result.getReason() == ResultReason.NoMatch) {
                System.out.println("NOMATCH: Speech could not be recognized.");
            }
            else if (result.getReason() == ResultReason.Canceled) {
                CancellationDetails cancellation = CancellationDetails.fromResult(result);
                System.out.println("CANCELED: Reason=" + cancellation.getReason());

                if (cancellation.getReason() == CancellationReason.Error)
                {
                    System.out.println("CANCELED: ErrorCode=" + cancellation.getErrorCode());
                    System.out.println("CANCELED: ErrorDetails=" + cancellation.getErrorDetails());
                    System.out.println("CANCELED: Did you update the subscription info?");
                }
            }
        }
    }
}

Générer et exécuter votre application

Vous êtes maintenant prêt à créer votre application et à tester notre reconnaissance d’intention à l’aide du service speech et de la correspondance de modèle incorporé.

Sélectionnez le bouton exécuter dans Eclipse ou appuyez sur Ctrl+F11, puis attendez la sortie pour l’invite « Dire quelque chose... » . Une fois qu’elle apparaît, prononcez votre énoncé et attendez la sortie.

Par exemple, si vous dites « me faire passer à l’étage 2 », il doit s’agir de la sortie suivante :

Say something...
RECOGNIZED: Text=Take me to floor 2.
       Intent Id=ChangeFloors.
       FloorName=2

Autre exemple : si vous dites « me faire passer à l’étage 7 », il doit s’agir de la sortie suivante :

Say something...
RECOGNIZED: Text=Take me to floor 7.
    Intent not recognized.

Aucune intention n’a été reconnue, car 7 n’était pas dans notre liste de valeurs valides pour floorName.