Rozpoznávání záměrů pomocí porovnávání vlastních vzorů entit

Sada Speech SDK služeb Azure AI má integrovanou funkci, která poskytuje rozpoznávání záměrů pomocí jednoduchého porovnávání vzorů jazyka. Záměr je něco, co chce uživatel udělat: zavřete okno, označte zaškrtávací políčko, vložte nějaký text atd.

V této příručce použijete sadu Speech SDK k vývoji konzolové aplikace, která odvozuje záměry z promluv řeči mluvených prostřednictvím mikrofonu vašeho zařízení. Získáte informace pro:

  • Vytvořit projekt sady Visual Studio odkazující na balíček NuGet sady Speech SDK
  • Vytvoření konfigurace řeči a získání rozpoznávání záměru
  • Přidání záměrů a vzorů prostřednictvím rozhraní SPEECH SDK API
  • Přidání vlastních entit prostřednictvím rozhraní API sady Speech SDK
  • Používat asynchronní událostmi řízené průběžné rozpoznávání

Kdy použít porovnávání vzorů

Porovnávání vzorů použijte v následujících případech:

Další informace najdete v přehledu porovnávání vzorů.

Požadavky

Než začnete s tímto průvodcem, ujistěte se, že máte následující položky:

Vytvoření projektu

V sadě Visual Studio 2019 vytvořte nový projekt konzolové aplikace jazyka C# a nainstalujte sadu Speech SDK.

Začněte s některými často používanými kódy

Pojďme otevřít Program.cs a přidat kód, který funguje jako kostra našeho 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");
        }
    }
}

Vytvoření konfigurace služby Speech

Než budete moct inicializovat IntentRecognizer objekt, musíte vytvořit konfiguraci, která pro prostředek predikce služeb Azure AI používá klíč a oblast Azure.

  • Nahraďte "YOUR_SUBSCRIPTION_KEY" prediktivním klíčem služeb Azure AI.
  • Nahraďte "YOUR_SUBSCRIPTION_REGION" oblastí prostředků služeb Azure AI.

Tato ukázka používá metodu FromSubscription()SpeechConfigk sestavení . Úplný seznam dostupných metod naleznete v tématu SpeechConfig – třída.

Inicializace objektu IntentRecognizer

Teď vytvořte .IntentRecognizer Vložte tento kód přímo pod konfiguraci služby Speech.

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

Přidání některých záměrů

Je třeba přidružit některé vzory k PatternMatchingModel a použít ho IntentRecognizerna . Začneme vytvořením PatternMatchingModel a přidáním několika záměrů.

Poznámka:

Do souboru PatternMatchingIntentmůžeme přidat více vzorů .

Vložte tento kód do 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"));

Přidání některých vlastních entit

Pokud chcete plně využít výhod porovnávání vzorů, můžete přizpůsobit entity. "floorName" vytvoříme seznam dostupných podlah. Vytvoříme také "parkingLevel" celočíselnou entitu.

Vložte tento kód pod záměry:

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

Použití našeho modelu na rozpoznávání

Nyní je nutné použít model na IntentRecognizer. Je možné použít více modelů najednou, takže rozhraní API přebírá kolekci modelů.

Vložte tento kód pod entity:

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

recognizer.ApplyLanguageModels(modelCollection);

Rozpoznávání záměru

Z objektu IntentRecognizer zavoláte metodu RecognizeOnceAsync() . Tato metoda požádá službu Speech, aby rozpoznala řeč v jedné frázi a přestala rozpoznávat řeč po identifikaci fráze.

Po použití jazykových modelů vložte tento kód:

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

var result = await recognizer.RecognizeOnceAsync();

Zobrazení výsledků rozpoznávání (nebo chyb)

Když služba Speech vrátí výsledek rozpoznávání, vytiskneme výsledek.

Vložte následující kód 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?");
    }
}

Kontrola kódu

V tomto okamžiku by váš kód měl vypadat takto:

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

Sestavení a spuštění aplikace

Teď jste připraveni sestavit aplikaci a otestovat rozpoznávání řeči pomocí služby Speech.

  1. Zkompilujte kód – Na řádku nabídek sady Visual Studio zvolte Sestavit>řešení sestavení.
  2. Spusťte aplikaci – na řádku nabídek zvolte> Spustit ladění nebo stiskněte klávesu F5.
  3. Spusťte rozpoznávání – zobrazí se výzva k tomu, abyste něco řekli. Výchozí jazyk je angličtina. Vaše řeč se odešle do služby Speech, přepíše se jako text a v konzole se vykreslí.

Pokud třeba řeknete "Take me to floor 2", měl by to být výstup:

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

Jako další příklad, pokud říkáte "Take me to floor 7", to by měl být výstup:

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

Nebyl rozpoznán žádný záměr, protože 7 nebylo v našem seznamu platných hodnot pro floorName.

Vytvoření projektu

Vytvořte nový projekt konzolové aplikace C++ v sadě Visual Studio 2019 a nainstalujte sadu Speech SDK.

Začněte s některými často používanými kódy

Pojďme otevřít helloworld.cpp a přidat kód, který funguje jako kostra našeho 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");
}

Vytvoření konfigurace služby Speech

Než budete moct inicializovat IntentRecognizer objekt, musíte vytvořit konfiguraci, která pro prostředek predikce služeb Azure AI používá klíč a oblast Azure.

  • Nahraďte "YOUR_SUBSCRIPTION_KEY" prediktivním klíčem služeb Azure AI.
  • Nahraďte "YOUR_SUBSCRIPTION_REGION" oblastí prostředků služeb Azure AI.

Tato ukázka používá metodu FromSubscription()SpeechConfigk sestavení . Úplný seznam dostupných metod naleznete v tématu SpeechConfig – třída.

Inicializace objektu IntentRecognizer

Teď vytvořte .IntentRecognizer Vložte tento kód přímo pod konfiguraci služby Speech.

    auto intentRecognizer = IntentRecognizer::FromConfig(config);

Přidání některých záměrů

Je třeba přidružit některé vzory k PatternMatchingModel a použít ho IntentRecognizerna . Začneme vytvořením PatternMatchingModel a přidáním několika záměrů. PatternMatchingIntent je struktura, takže použijeme pouze vloženou syntaxi.

Poznámka:

Do souboru PatternMatchingIntentmůžeme přidat více vzorů .

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

Přidání některých vlastních entit

Pokud chcete plně využít výhod porovnávání vzorů, můžete přizpůsobit entity. "floorName" vytvoříme seznam dostupných podlah.

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

Použití našeho modelu na rozpoznávání

Nyní je nutné použít model na IntentRecognizer. Je možné použít více modelů najednou, takže rozhraní API přebírá kolekci modelů.

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

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

Rozpoznávání záměru

Z objektu IntentRecognizer zavoláte metodu RecognizeOnceAsync() . Tato metoda požádá službu Speech, aby rozpoznala řeč v jedné frázi a přestala rozpoznávat řeč po identifikaci fráze. Pro zjednodušení počkáme na dokončení budoucnosti.

Vložte tento kód pod záměry:

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

Zobrazení výsledků rozpoznávání (nebo chyb)

Když služba Speech vrátí výsledek rozpoznávání, vytiskneme výsledek.

Vložte následující kód 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;
}

Kontrola kódu

V tomto okamžiku by váš kód měl vypadat takto:

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

Sestavení a spuštění aplikace

Teď jste připraveni sestavit aplikaci a otestovat rozpoznávání řeči pomocí služby Speech.

  1. Zkompilujte kód – Na řádku nabídek sady Visual Studio zvolte Sestavit>řešení sestavení.
  2. Spusťte aplikaci – na řádku nabídek zvolte> Spustit ladění nebo stiskněte klávesu F5.
  3. Spusťte rozpoznávání – zobrazí se výzva k tomu, abyste něco řekli. Výchozí jazyk je angličtina. Vaše řeč se odešle do služby Speech, přepíše se jako text a v konzole se vykreslí.

Pokud třeba řeknete "Take me to floor 2", měl by to být výstup:

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

Další příklad, pokud říkáte "Take me to floor 7", to by měl být výstup:

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

ID záměru je prázdné, protože 7 nebylo v našem seznamu.

Referenční dokumentace | Další ukázky na GitHubu

V tomto rychlém startu nainstalujete sadu Speech SDK pro Javu.

Požadavky platformy

Zvolte cílové prostředí:

Sada Speech SDK pro Javu je kompatibilní s Windows, Linuxem a macOS.

Ve Windows musíte použít 64bitovou cílovou architekturu. Vyžaduje se Windows 10 nebo novější.

Nainstalujte microsoft Distribuovatelné součásti Visual C++ pro Visual Studio 2015, 2017, 2019 a 2022 pro vaši platformu. První instalace tohoto balíčku může vyžadovat restartování.

Sada Speech SDK pro Javu nepodporuje Windows v ARM64.

Nainstalujte sadu Java Development Kit, jako je Azul Zulu OpenJDK. Měl by fungovat také microsoft build OpenJDK nebo upřednostňovaná sada JDK.

Instalace sady Speech SDK pro Javu

Některé pokyny používají konkrétní verzi sady SDK, například 1.24.2. Pokud chcete zkontrolovat nejnovější verzi, vyhledejte úložiště GitHub.

Zvolte cílové prostředí:

Tento průvodce ukazuje, jak nainstalovat sadu Speech SDK pro Javu v prostředí Java Runtime.

Podporované operační systémy

Balíček Speech SDK pro Javu je k dispozici pro tyto operační systémy:

Pokud chcete nainstalovat sadu Speech SDK pro Javu pomocí Apache Mavenu, postupujte takto:

  1. Nainstalujte Apache Maven.

  2. Otevřete příkazový řádek, na kterém chcete nový projekt, a vytvořte nový soubor pom.xml .

  3. Do pom.xml zkopírujte následující obsah 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. Spuštěním následujícího příkazu Mavenu nainstalujte sadu Speech SDK a závislosti.

    mvn clean dependency:copy-dependencies
    

Začněte s některými často používanými kódy

  1. Otevřete Main.java z nástroje src dir.

  2. Obsah souboru nahraďte následujícím kódem:

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

Vytvoření konfigurace služby Speech

Než budete moct inicializovat IntentRecognizer objekt, musíte vytvořit konfiguraci, která pro prostředek predikce služeb Azure AI používá klíč a oblast Azure.

  • Nahraďte "YOUR_SUBSCRIPTION_KEY" prediktivním klíčem služeb Azure AI.
  • Nahraďte "YOUR_SUBSCRIPTION_REGION" oblastí prostředků služeb Azure AI.

Tato ukázka používá metodu fromSubscription()SpeechConfigk sestavení . Úplný seznam dostupných metod naleznete v tématu SpeechConfig – třída.

Inicializace objektu IntentRecognizer

Teď vytvořte .IntentRecognizer Vložte tento kód přímo pod konfiguraci služby Speech. Provedeme to při pokusu, abychom využili výhod rozhraní s automatickým seznamem.

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

}

Přidání některých záměrů

Je třeba přidružit některé vzory k PatternMatchingModel a použít ho IntentRecognizerna . Začneme vytvořením PatternMatchingModel a přidáním několika záměrů.

Poznámka:

Do souboru PatternMatchingIntentmůžeme přidat více vzorů .

Vložte tento kód do 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"));

Přidání některých vlastních entit

Pokud chcete plně využít výhod porovnávání vzorů, můžete přizpůsobit entity. "floorName" vytvoříme seznam dostupných podlah. Vytvoříme také "parkingLevel" celočíselnou entitu.

Vložte tento kód pod záměry:

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

Použití našeho modelu na rozpoznávání

Nyní je nutné použít model na IntentRecognizer. Je možné použít více modelů najednou, takže rozhraní API přebírá kolekci modelů.

Vložte tento kód pod entity:

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

recognizer.applyLanguageModels(modelCollection);

Rozpoznávání záměru

Z objektu IntentRecognizer zavoláte metodu RecognizeOnceAsync() . Tato metoda požádá službu Speech, aby rozpoznala řeč v jedné frázi a přestala rozpoznávat řeč po identifikaci fráze.

Po použití jazykových modelů vložte tento kód:

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

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

Zobrazení výsledků rozpoznávání (nebo chyb)

Když služba Speech vrátí výsledek rozpoznávání, vytiskneme výsledek.

Vložte následující kód 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?");
    }
}

Kontrola kódu

V tomto okamžiku by váš kód měl vypadat takto:

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

Sestavení a spuštění aplikace

Teď jste připraveni sestavit aplikaci a otestovat rozpoznávání záměru pomocí služby Speech a nástroje pro porovnávání vložených vzorů.

Vyberte tlačítko Spustit v Eclipse nebo stiskněte ctrl+F11 a pak sledujte výstup "Řekněte něco..." Výzva. Jakmile se zobrazí promluva a podívejte se na výstup.

Pokud třeba řeknete "Take me to floor 2", měl by to být výstup:

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

Jako další příklad, pokud říkáte "Take me to floor 7", to by měl být výstup:

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

Nebyl rozpoznán žádný záměr, protože 7 nebylo v našem seznamu platných hodnot pro floorName.