Jak rozpoznawać intencje z dopasowaniem niestandardowego wzorca jednostki

Zestaw SDK rozpoznawania mowy usług Azure AI ma wbudowaną funkcję umożliwiającą rozpoznawanie intencji z prostym dopasowaniem wzorca języka. Intencją jest coś, co użytkownik chce zrobić: zamknij okno, zaznacz pole wyboru, wstaw jakiś tekst itp.

W tym przewodniku użyjesz zestawu SDK usługi Mowa, aby opracować aplikację konsolową, która wyprowadza intencje z wypowiedzi mowy wypowiadanych za pośrednictwem mikrofonu urządzenia. Dowiedz się, jak odbywa się:

  • Tworzenie projektu programu Visual Studio odwołującego się do pakietu NuGet zestawu Speech SDK
  • Tworzenie konfiguracji mowy i uzyskiwanie rozpoznawania intencji
  • Dodawanie intencji i wzorców za pomocą interfejsu API zestawu SPEECH SDK
  • Dodawanie jednostek niestandardowych za pomocą interfejsu API zestawu SPEECH SDK
  • Używanie asynchronicznego, opartego na zdarzeniach rozpoznawania ciągłego

Kiedy należy używać dopasowywania wzorców

Użyj dopasowania wzorca, jeśli:

  • Interesuje Cię tylko dopasowanie dokładnie tego, co powiedział użytkownik. Wzorce te są bardziej agresywne niż zrozumienie języka konwersacyjnego (CLU).
  • Nie masz dostępu do modelu CLU, ale nadal chcesz użyć intencji.

Aby uzyskać więcej informacji, zobacz omówienie dopasowywania wzorca.

Wymagania wstępne

Przed rozpoczęciem tego przewodnika upewnij się, że masz następujące elementy:

Tworzenie projektu

Utwórz nowy projekt aplikacji konsolowej języka C# w programie Visual Studio 2019 i zainstaluj zestaw Speech SDK.

Zacznij od kodu kociołowego

Otwórzmy Program.cs i dodajmy kod, który działa jako szkielet naszego projektu.

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");
        }
    }
}

Tworzenie konfiguracji mowy

Przed zainicjowaniem IntentRecognizer obiektu należy utworzyć konfigurację, która używa klucza i regionu platformy Azure dla zasobu przewidywania usług Azure AI.

  • Zastąp "YOUR_SUBSCRIPTION_KEY" element kluczem przewidywania usług Azure AI.
  • Zastąp "YOUR_SUBSCRIPTION_REGION" element regionem zasobów usług Azure AI.

W tym przykładzie użyto FromSubscription() metody do skompilowania klasy SpeechConfig. Aby uzyskać pełną listę dostępnych metod, zobacz SpeechConfig Class (Klasa SpeechConfig).

Inicjowanie intencjiRecognizer

Teraz utwórz element IntentRecognizer. Wstaw ten kod bezpośrednio poniżej konfiguracji usługi Mowa.

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

Dodawanie niektórych intencji

Należy skojarzyć pewne wzorce z elementem PatternMatchingModel i zastosować je do .IntentRecognizer Zaczniemy od utworzenia i dodania PatternMatchingModel do niego kilku intencji.

Uwaga

Możemy dodać wiele wzorców do elementu PatternMatchingIntent.

Wstaw ten kod wewnątrz using bloku:

// 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"));

Dodawanie niektórych jednostek niestandardowych

Aby w pełni wykorzystać dopasowanie wzorca, możesz dostosować jednostki. Udostępnimy "floorName" listę dostępnych podłóg. Ustawimy również jednostkę "parkingLevel" jako liczbę całkowitą.

Wstaw ten kod poniżej swoich intencji:

// 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"));

Stosowanie naszego modelu do rozpoznawania

Teraz należy zastosować model do .IntentRecognizer Istnieje możliwość jednoczesnego używania wielu modeli, aby interfejs API pobierał kolekcję modeli.

Wstaw ten kod poniżej jednostek:

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

recognizer.ApplyLanguageModels(modelCollection);

Rozpoznawanie intencji

IntentRecognizer Z obiektu wywołasz metodę RecognizeOnceAsync() . Ta metoda prosi usługę rozpoznawania mowy o rozpoznawanie mowy w jednej frazie i zaprzestanie rozpoznawania mowy po zidentyfikowaniu frazy.

Wstaw ten kod po zastosowaniu modeli językowych:

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

var result = await recognizer.RecognizeOnceAsync();

Wyświetlanie wyników rozpoznawania (lub błędów)

Gdy wynik rozpoznawania zostanie zwrócony przez usługę Rozpoznawanie mowy, wyświetlimy wynik.

Wstaw poniższy kod 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?");
    }
}

Sprawdzanie kodu

Na tym etapie kod powinien wyglądać następująco:

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?");
                    }
                }
            }
        }
    }
}

Kompilowanie i uruchamianie aplikacji

Teraz możesz przystąpić do kompilowania aplikacji i testowania rozpoznawania mowy przy użyciu usługi Mowa.

  1. Skompiluj kod — na pasku menu programu Visual Studio wybierz pozycję Kompiluj rozwiązanie kompilacji>.
  2. Uruchom aplikację — na pasku menu wybierz pozycję Debuguj>rozpocznij debugowanie lub naciśnij klawisz F5.
  3. Rozpocznij rozpoznawanie — spowoduje to wyświetlenie monitu o coś. Domyślnym językiem jest angielski. Twoja mowa jest wysyłana do usługi rozpoznawania mowy, transkrybowana jako tekst i renderowana w konsoli programu .

Jeśli na przykład zostanie wyświetlony komunikat "Take me to floor 2", powinny to być dane wyjściowe:

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

W innym przykładzie, jeśli mówisz "Take me to floor 7", powinny to być dane wyjściowe:

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

Nie rozpoznano intencji, ponieważ 7 nie znajduje się na naszej liście prawidłowych wartości dla floorName.

Tworzenie projektu

Utwórz nowy projekt aplikacji konsolowej języka C++ w programie Visual Studio 2019 i zainstaluj zestaw Speech SDK.

Zacznij od kodu kociołowego

Otwórzmy helloworld.cpp i dodajmy kod, który działa jako szkielet naszego projektu.

#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");
}

Tworzenie konfiguracji mowy

Przed zainicjowaniem IntentRecognizer obiektu należy utworzyć konfigurację, która używa klucza i regionu platformy Azure dla zasobu przewidywania usług Azure AI.

  • Zastąp "YOUR_SUBSCRIPTION_KEY" element kluczem przewidywania usług Azure AI.
  • Zastąp "YOUR_SUBSCRIPTION_REGION" element regionem zasobów usług Azure AI.

W tym przykładzie użyto FromSubscription() metody do skompilowania klasy SpeechConfig. Aby uzyskać pełną listę dostępnych metod, zobacz SpeechConfig Class (Klasa SpeechConfig).

Inicjowanie intencjiRecognizer

Teraz utwórz element IntentRecognizer. Wstaw ten kod bezpośrednio poniżej konfiguracji usługi Mowa.

    auto intentRecognizer = IntentRecognizer::FromConfig(config);

Dodawanie niektórych intencji

Należy skojarzyć pewne wzorce z elementem PatternMatchingModel i zastosować je do .IntentRecognizer Zaczniemy od utworzenia i dodania PatternMatchingModel do niego kilku intencji. PatternMatchingIntent jest strukturą, więc po prostu użyjemy składni w wierszu.

Uwaga

Możemy dodać wiele wzorców do elementu 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");

Dodawanie niektórych jednostek niestandardowych

Aby w pełni wykorzystać dopasowanie wzorca, możesz dostosować jednostki. Udostępnimy "floorName" listę dostępnych podłóg.

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

Stosowanie naszego modelu do rozpoznawania

Teraz należy zastosować model do .IntentRecognizer Istnieje możliwość jednoczesnego używania wielu modeli, aby interfejs API pobierał kolekcję modeli.

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

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

Rozpoznawanie intencji

IntentRecognizer Z obiektu wywołasz metodę RecognizeOnceAsync() . Ta metoda prosi usługę rozpoznawania mowy o rozpoznawanie mowy w jednej frazie i zaprzestanie rozpoznawania mowy po zidentyfikowaniu frazy. Dla uproszczenia zaczekamy na zakończenie przyszłego powrotu.

Wstaw ten kod poniżej swoich intencji:

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

Wyświetlanie wyników rozpoznawania (lub błędów)

Gdy wynik rozpoznawania zostanie zwrócony przez usługę Rozpoznawanie mowy, wyświetlimy wynik.

Wstaw poniższy kod 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;
}

Sprawdzanie kodu

Na tym etapie kod powinien wyglądać następująco:

#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;
    }
}

Kompilowanie i uruchamianie aplikacji

Teraz możesz przystąpić do kompilowania aplikacji i testowania rozpoznawania mowy przy użyciu usługi Mowa.

  1. Skompiluj kod — na pasku menu programu Visual Studio wybierz pozycję Kompiluj rozwiązanie kompilacji>.
  2. Uruchom aplikację — na pasku menu wybierz pozycję Debuguj>rozpocznij debugowanie lub naciśnij klawisz F5.
  3. Rozpocznij rozpoznawanie — spowoduje to wyświetlenie monitu o coś. Domyślnym językiem jest angielski. Twoja mowa jest wysyłana do usługi rozpoznawania mowy, transkrybowana jako tekst i renderowana w konsoli programu .

Jeśli na przykład zostanie wyświetlony komunikat "Take me to floor 2", powinny to być dane wyjściowe:

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

Innym przykładem może być komunikat "Take me to floor 7", powinny to być dane wyjściowe:

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

Identyfikator intencji jest pusty, ponieważ 7 nie znajdowało się na naszej liście.

| Dokumentacja referencyjna — dodatkowe przykłady w usłudze GitHub

W tym przewodniku Szybki start zainstalujesz zestaw SPEECH SDK dla języka Java.

Wymagania dotyczące platformy

Wybierz środowisko docelowe:

Zestaw SPEECH SDK dla języka Java jest zgodny z systemami Windows, Linux i macOS.

W systemie Windows należy użyć architektury docelowej 64-bitowej. Wymagany jest system Windows 10 lub nowszy.

Zainstaluj platformę Microsoft Pakiet redystrybucyjny Visual C++ dla Visual Studio 2015, 2017, 2019 i 2022. Zainstalowanie tego pakietu po raz pierwszy może wymagać ponownego uruchomienia.

Zestaw SPEECH SDK dla języka Java nie obsługuje systemu Windows w usłudze ARM64.

Zainstaluj zestaw Java Development Kit, taki jak Azul Zulu OpenJDK. Pakiet Microsoft Build zestawu OpenJDK lub preferowany zestaw JDK powinien również działać.

Instalowanie zestawu SPEECH SDK dla języka Java

Niektóre instrukcje używają określonej wersji zestawu SDK, takiej jak 1.24.2. Aby sprawdzić najnowszą wersję, wyszukaj nasze repozytorium GitHub.

Wybierz środowisko docelowe:

W tym przewodniku pokazano, jak zainstalować zestaw SPEECH SDK dla języka Java w środowisku uruchomieniowym Języka Java.

Obsługiwane systemy operacyjne

Pakiet Speech SDK dla języka Java jest dostępny dla następujących systemów operacyjnych:

Wykonaj następujące kroki, aby zainstalować zestaw SPEECH SDK dla języka Java przy użyciu narzędzia Apache Maven:

  1. Zainstaluj narzędzie Apache Maven.

  2. Otwórz wiersz polecenia, w którym chcesz utworzyć nowy projekt, i utwórz nowy plik pom.xml .

  3. Skopiuj następującą zawartość XML do 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. Uruchom następujące polecenie narzędzia Maven, aby zainstalować zestaw SPEECH SDK i zależności.

    mvn clean dependency:copy-dependencies
    

Zacznij od kodu kociołowego

  1. Otwórz Main.java z dir src.

  2. Zastąp zawartość pliku następującym kodem:

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");
    }
}

Tworzenie konfiguracji mowy

Przed zainicjowaniem IntentRecognizer obiektu należy utworzyć konfigurację, która używa klucza i regionu platformy Azure dla zasobu przewidywania usług Azure AI.

  • Zastąp "YOUR_SUBSCRIPTION_KEY" element kluczem przewidywania usług Azure AI.
  • Zastąp "YOUR_SUBSCRIPTION_REGION" element regionem zasobów usług Azure AI.

W tym przykładzie użyto fromSubscription() metody do skompilowania klasy SpeechConfig. Aby uzyskać pełną listę dostępnych metod, zobacz SpeechConfig Class (Klasa SpeechConfig).

Inicjowanie intencjiRecognizer

Teraz utwórz element IntentRecognizer. Wstaw ten kod bezpośrednio poniżej konfiguracji usługi Mowa. Robimy to w ramach próby, dzięki czemu korzystamy z interfejsu z możliwością automatycznego losowania.

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

}

Dodawanie niektórych intencji

Należy skojarzyć pewne wzorce z elementem PatternMatchingModel i zastosować je do .IntentRecognizer Zaczniemy od utworzenia i dodania PatternMatchingModel do niego kilku intencji.

Uwaga

Możemy dodać wiele wzorców do elementu PatternMatchingIntent.

Wstaw ten kod wewnątrz try bloku:

// 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"));

Dodawanie niektórych jednostek niestandardowych

Aby w pełni wykorzystać dopasowanie wzorca, możesz dostosować jednostki. Udostępnimy "floorName" listę dostępnych podłóg. Ustawimy również jednostkę "parkingLevel" jako liczbę całkowitą.

Wstaw ten kod poniżej swoich intencji:

// 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"));

Stosowanie naszego modelu do rozpoznawania

Teraz należy zastosować model do .IntentRecognizer Istnieje możliwość jednoczesnego używania wielu modeli, aby interfejs API pobierał kolekcję modeli.

Wstaw ten kod poniżej jednostek:

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

recognizer.applyLanguageModels(modelCollection);

Rozpoznawanie intencji

IntentRecognizer Z obiektu wywołasz metodę RecognizeOnceAsync() . Ta metoda prosi usługę rozpoznawania mowy o rozpoznawanie mowy w jednej frazie i zaprzestanie rozpoznawania mowy po zidentyfikowaniu frazy.

Wstaw ten kod po zastosowaniu modeli językowych:

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

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

Wyświetlanie wyników rozpoznawania (lub błędów)

Gdy wynik rozpoznawania zostanie zwrócony przez usługę Rozpoznawanie mowy, wyświetlimy wynik.

Wstaw poniższy kod 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?");
    }
}

Sprawdzanie kodu

Na tym etapie kod powinien wyglądać następująco:

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?");
                }
            }
        }
    }
}

Kompilowanie i uruchamianie aplikacji

Teraz możesz skompilować aplikację i przetestować rozpoznawanie intencji przy użyciu usługi rozpoznawania mowy i osadzonego dopasowania wzorca.

Wybierz przycisk uruchamiania w środowisku Eclipse lub naciśnij klawisze Ctrl+F11, a następnie obejrzyj dane wyjściowe polecenia "Powiedz coś..." Wierszu. Gdy pojawi się komunikat, powiedz swoją wypowiedź i obejrzyj dane wyjściowe.

Jeśli na przykład zostanie wyświetlony komunikat "Take me to floor 2", powinny to być dane wyjściowe:

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

W innym przykładzie, jeśli mówisz "Take me to floor 7", powinny to być dane wyjściowe:

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

Nie rozpoznano intencji, ponieważ 7 nie znajduje się na naszej liście prawidłowych wartości dla floorName.