Så här identifierar du avsikter med anpassad entitetsmönstermatchning

Speech SDK för Azure AI-tjänster har en inbyggd funktion som ger avsiktsigenkänning med enkel språkmönstermatchning. En avsikt är något som användaren vill göra: stänga ett fönster, markera en kryssruta, infoga text osv.

I den här guiden använder du Speech SDK för att utveckla ett konsolprogram som härleder avsikter från talyttranden som talas via enhetens mikrofon. Du lär dig att:

  • Skapa ett Visual Studio-projekt som refererar till Speech SDK NuGet-paketet
  • Skapa en talkonfiguration och få en avsiktsigenkänning
  • Lägga till avsikter och mönster via Speech SDK-API:et
  • Lägga till anpassade entiteter via Speech SDK-API:et
  • Använd asynkron, händelsedriven kontinuerlig igenkänning

När mönstermatchning ska användas

Använd mönstermatchning om:

  • Du är bara intresserad av att matcha strikt vad användaren sa. Dessa mönster matchar mer aggressivt än konversationell språkförst förstå (CLU).
  • Du har inte åtkomst till en CLU-modell, men vill ändå ha avsikter.

Mer information finns i översikten över mönstermatchning.

Förutsättningar

Se till att du har följande objekt innan du påbörjar den här guiden:

Skapa ett projekt

Skapa ett nytt C#-konsolprogramprojekt i Visual Studio 2019 och installera Speech SDK.

Börja med lite pannplåtskod

Nu ska vi öppna Program.cs och lägga till kod som fungerar som ett skelett för vårt projekt.

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

Skapa en Speech-konfiguration

Innan du kan initiera ett IntentRecognizer objekt måste du skapa en konfiguration som använder nyckeln och Azure-regionen för din Azure AI-tjänstförutsägelseresurs.

  • Ersätt "YOUR_SUBSCRIPTION_KEY" med förutsägelsenyckeln för Azure AI-tjänster.
  • Ersätt "YOUR_SUBSCRIPTION_REGION" med resursregionen för Azure AI-tjänster.

Det här exemplet använder FromSubscription() metoden för att skapa SpeechConfig. En fullständig lista över tillgängliga metoder finns i Klassen SpeechConfig.

Initiera en IntentRecognizer

Skapa nu en IntentRecognizer. Infoga den här koden precis under din Speech-konfiguration.

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

Lägg till några avsikter

Du måste associera vissa mönster med en PatternMatchingModel och tillämpa den på IntentRecognizer. Vi börjar med att skapa en PatternMatchingModel och lägga till några avsikter till den.

Kommentar

Vi kan lägga till flera mönster i en PatternMatchingIntent.

Infoga den här koden i using blocket:

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

Lägg till några anpassade entiteter

Om du vill dra full nytta av mönstermatcharen kan du anpassa dina entiteter. Vi kommer att göra "floorName" till en lista över tillgängliga våningar. Vi kommer också att göra "parkingLevel" till en heltalsentitet.

Infoga den här koden under dina avsikter:

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

Tillämpa vår modell på identifieraren

Nu är det nödvändigt att tillämpa modellen på IntentRecognizer. Det är möjligt att använda flera modeller samtidigt så att API:et tar en samling modeller.

Infoga den här koden under dina entiteter:

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

recognizer.ApplyLanguageModels(modelCollection);

Identifiera en avsikt

Från - IntentRecognizer objektet anropar RecognizeOnceAsync() du metoden. Den här metoden ber Speech-tjänsten att känna igen tal i en enda fras och sluta känna igen tal när frasen har identifierats.

Infoga den här koden när du har tillämpat språkmodellerna:

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

var result = await recognizer.RecognizeOnceAsync();

Visa igenkänningsresultaten (eller felen)

När igenkänningsresultatet returneras av Speech-tjänsten skriver vi ut resultatet.

Infoga den här koden nedan 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?");
    }
}

Kontrollera koden

Nu bör koden se ut så här:

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

Skapa och köra din app

Nu är du redo att skapa din app och testa vår taligenkänning med hjälp av Speech-tjänsten.

  1. Kompilera koden – Från menyraden i Visual Studio väljer du Skapa>bygglösning.
  2. Starta din app – Välj Felsök>Starta felsökning i menyraden eller tryck på F5.
  3. Starta igenkänning – Du uppmanas att säga något. Standardspråket är engelska. Ditt tal skickas till Speech-tjänsten, transkriberas som text och återges i konsolen.

Om du till exempel säger "Ta mig till våning 2" bör det här vara utdata:

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

Som ett annat exempel om du säger "Ta mig till våning 7" bör detta vara utdata:

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

Ingen avsikt identifierades eftersom 7 inte fanns med i vår lista över giltiga värden för floorName.

Skapa ett projekt

Skapa ett nytt C++-konsolprogramprojekt i Visual Studio 2019 och installera Speech SDK.

Börja med lite pannplåtskod

Nu ska vi öppna helloworld.cpp och lägga till kod som fungerar som ett skelett för vårt projekt.

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

Skapa en Speech-konfiguration

Innan du kan initiera ett IntentRecognizer objekt måste du skapa en konfiguration som använder nyckeln och Azure-regionen för din Azure AI-tjänstförutsägelseresurs.

  • Ersätt "YOUR_SUBSCRIPTION_KEY" med förutsägelsenyckeln för Azure AI-tjänster.
  • Ersätt "YOUR_SUBSCRIPTION_REGION" med resursregionen för Azure AI-tjänster.

Det här exemplet använder FromSubscription() metoden för att skapa SpeechConfig. En fullständig lista över tillgängliga metoder finns i Klassen SpeechConfig.

Initiera en IntentRecognizer

Skapa nu en IntentRecognizer. Infoga den här koden precis under din Speech-konfiguration.

    auto intentRecognizer = IntentRecognizer::FromConfig(config);

Lägg till några avsikter

Du måste associera vissa mönster med en PatternMatchingModel och tillämpa den på IntentRecognizer. Vi börjar med att skapa en PatternMatchingModel och lägga till några avsikter till den. En PatternMatchingIntent är en struct så vi använder bara den infogade syntaxen.

Kommentar

Vi kan lägga till flera mönster i en 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");

Lägg till några anpassade entiteter

Om du vill dra full nytta av mönstermatcharen kan du anpassa dina entiteter. Vi kommer att göra "floorName" till en lista över tillgängliga våningar.

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

Tillämpa vår modell på identifieraren

Nu är det nödvändigt att tillämpa modellen på IntentRecognizer. Det är möjligt att använda flera modeller samtidigt så att API:et tar en samling modeller.

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

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

Identifiera en avsikt

Från - IntentRecognizer objektet anropar RecognizeOnceAsync() du metoden. Den här metoden ber Speech-tjänsten att känna igen tal i en enda fras och sluta känna igen tal när frasen har identifierats. För enkelhetens skull väntar vi på att framtiden ska slutföras.

Infoga den här koden under dina avsikter:

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

Visa igenkänningsresultaten (eller felen)

När igenkänningsresultatet returneras av Speech-tjänsten skriver vi ut resultatet.

Infoga den här koden nedan 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;
}

Kontrollera koden

Nu bör koden se ut så här:

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

Skapa och köra din app

Nu är du redo att skapa din app och testa vår taligenkänning med hjälp av Speech-tjänsten.

  1. Kompilera koden – Från menyraden i Visual Studio väljer du Skapa>bygglösning.
  2. Starta din app – Välj Felsök>Starta felsökning i menyraden eller tryck på F5.
  3. Starta igenkänning – Du uppmanas att säga något. Standardspråket är engelska. Ditt tal skickas till Speech-tjänsten, transkriberas som text och återges i konsolen.

Om du till exempel säger "Ta mig till våning 2" bör det här vara utdata:

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

Ett annat exempel om du säger "Ta mig till våning 7" bör detta vara utdata:

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

Avsikts-ID:t är tomt eftersom 7 inte fanns med i listan.

Referensdokumentation | Ytterligare exempel på GitHub

I den här snabbstarten installerar du Speech SDK för Java.

Plattformskrav

Välj målmiljö:

Speech SDK för Java är kompatibelt med Windows, Linux och macOS.

I Windows måste du använda 64-bitars målarkitekturen. Windows 10 eller senare krävs.

Installera Microsoft Visual C++ Redistributable för Visual Studio 2015, 2017, 2019 och 2022 för din plattform. Att installera det här paketet för första gången kan kräva en omstart.

Speech SDK för Java stöder inte Windows på ARM64.

Installera ett Java Development Kit, till exempel Azul Zulu OpenJDK. Microsoft Build of OpenJDK eller din önskade JDK bör också fungera.

Installera Speech SDK för Java

Vissa av instruktionerna använder en specifik SDK-version, till exempel 1.24.2. Om du vill kontrollera den senaste versionen söker du på vår GitHub-lagringsplats.

Välj målmiljö:

Den här guiden visar hur du installerar Speech SDK för Java på Java Runtime.

Operativsystem som stöds

Speech SDK för Java-paketet är tillgängligt för dessa operativsystem:

Följ de här stegen för att installera Speech SDK för Java med Apache Maven:

  1. Installera Apache Maven.

  2. Öppna en kommandotolk där du vill ha det nya projektet och skapa en ny pom.xml fil.

  3. Kopiera följande XML-innehåll till 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. Kör följande Maven-kommando för att installera Speech SDK och beroenden.

    mvn clean dependency:copy-dependencies
    

Börja med lite pannplåtskod

  1. Öppna Main.java från src dir.

  2. Ersätt innehållet i filen med följande:

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

Skapa en Speech-konfiguration

Innan du kan initiera ett IntentRecognizer objekt måste du skapa en konfiguration som använder nyckeln och Azure-regionen för din Azure AI-tjänstförutsägelseresurs.

  • Ersätt "YOUR_SUBSCRIPTION_KEY" med förutsägelsenyckeln för Azure AI-tjänster.
  • Ersätt "YOUR_SUBSCRIPTION_REGION" med resursregionen för Azure AI-tjänster.

Det här exemplet använder fromSubscription() metoden för att skapa SpeechConfig. En fullständig lista över tillgängliga metoder finns i Klassen SpeechConfig.

Initiera en IntentRecognizer

Skapa nu en IntentRecognizer. Infoga den här koden precis under din Speech-konfiguration. Vi gör detta i ett försök så att vi drar nytta av det autoklosbara gränssnittet.

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

}

Lägg till några avsikter

Du måste associera vissa mönster med en PatternMatchingModel och tillämpa den på IntentRecognizer. Vi börjar med att skapa en PatternMatchingModel och lägga till några avsikter till den.

Kommentar

Vi kan lägga till flera mönster i en PatternMatchingIntent.

Infoga den här koden i try blocket:

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

Lägg till några anpassade entiteter

Om du vill dra full nytta av mönstermatcharen kan du anpassa dina entiteter. Vi kommer att göra "floorName" till en lista över tillgängliga våningar. Vi kommer också att göra "parkingLevel" till en heltalsentitet.

Infoga den här koden under dina avsikter:

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

Tillämpa vår modell på identifieraren

Nu är det nödvändigt att tillämpa modellen på IntentRecognizer. Det är möjligt att använda flera modeller samtidigt så att API:et tar en samling modeller.

Infoga den här koden under dina entiteter:

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

recognizer.applyLanguageModels(modelCollection);

Identifiera en avsikt

Från - IntentRecognizer objektet anropar RecognizeOnceAsync() du metoden. Den här metoden ber Speech-tjänsten att känna igen tal i en enda fras och sluta känna igen tal när frasen har identifierats.

Infoga den här koden när du har tillämpat språkmodellerna:

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

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

Visa igenkänningsresultaten (eller felen)

När igenkänningsresultatet returneras av Speech-tjänsten skriver vi ut resultatet.

Infoga den här koden nedan 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?");
    }
}

Kontrollera koden

Nu bör koden se ut så här:

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

Skapa och köra din app

Nu är du redo att skapa din app och testa vår avsiktsigenkänning med hjälp av taltjänsten och den inbäddade mönstermatchningen.

Välj knappen Kör i Eclipse eller tryck på ctrl+F11 och titta sedan på utdata för "Säg något..." Snabb. När det visas talar du om ditt yttrande och tittar på utdata.

Om du till exempel säger "Ta mig till våning 2" bör det här vara utdata:

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

Som ett annat exempel om du säger "Ta mig till våning 7" bör detta vara utdata:

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

Ingen avsikt identifierades eftersom 7 inte fanns med i vår lista över giltiga värden för floorName.