Search in sources :

Example 1 with SpeechToText

use of com.ibm.watson.speech_to_text.v1.SpeechToText in project openhab-addons by openhab.

the class WatsonSTTService method recognize.

@Override
public STTServiceHandle recognize(STTListener sttListener, AudioStream audioStream, Locale locale, Set<String> set) throws STTException {
    if (config.apiKey.isBlank() || config.instanceUrl.isBlank()) {
        throw new STTException("service is not correctly configured");
    }
    String contentType = getContentType(audioStream);
    if (contentType == null) {
        throw new STTException("Unsupported format, unable to resolve audio content type");
    }
    logger.debug("Content-Type: {}", contentType);
    var speechToText = new SpeechToText(new IamAuthenticator.Builder().apikey(config.apiKey).build());
    speechToText.setServiceUrl(config.instanceUrl);
    if (config.optOutLogging) {
        speechToText.setDefaultHeaders(Map.of("X-Watson-Learning-Opt-Out", "1"));
    }
    RecognizeWithWebsocketsOptions wsOptions = new RecognizeWithWebsocketsOptions.Builder().audio(audioStream).contentType(contentType).redaction(config.redaction).smartFormatting(config.smartFormatting).model(locale.toLanguageTag() + "_BroadbandModel").interimResults(true).backgroundAudioSuppression(config.backgroundAudioSuppression).speechDetectorSensitivity(config.speechDetectorSensitivity).inactivityTimeout(config.inactivityTimeout).build();
    final AtomicReference<@Nullable WebSocket> socketRef = new AtomicReference<>();
    final AtomicBoolean aborted = new AtomicBoolean(false);
    executor.submit(() -> {
        int retries = 2;
        while (retries > 0) {
            try {
                socketRef.set(speechToText.recognizeUsingWebSocket(wsOptions, new TranscriptionListener(sttListener, config, aborted)));
                break;
            } catch (RuntimeException e) {
                var cause = e.getCause();
                if (cause instanceof SSLPeerUnverifiedException) {
                    logger.debug("Retrying on error: {}", cause.getMessage());
                    retries--;
                } else {
                    var errorMessage = e.getMessage();
                    logger.warn("Aborting on error: {}", errorMessage);
                    sttListener.sttEventReceived(new SpeechRecognitionErrorEvent(errorMessage != null ? errorMessage : "Unknown error"));
                    break;
                }
            }
        }
    });
    return new STTServiceHandle() {

        @Override
        public void abort() {
            if (!aborted.getAndSet(true)) {
                var socket = socketRef.get();
                if (socket != null) {
                    socket.close(1000, null);
                    socket.cancel();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }
    };
}
Also used : STTException(org.openhab.core.voice.STTException) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) AtomicReference(java.util.concurrent.atomic.AtomicReference) WebSocket(okhttp3.WebSocket) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SpeechRecognitionErrorEvent(org.openhab.core.voice.SpeechRecognitionErrorEvent) RecognizeWithWebsocketsOptions(com.ibm.watson.speech_to_text.v1.model.RecognizeWithWebsocketsOptions) SpeechToText(com.ibm.watson.speech_to_text.v1.SpeechToText) STTServiceHandle(org.openhab.core.voice.STTServiceHandle)

Example 2 with SpeechToText

use of com.ibm.watson.speech_to_text.v1.SpeechToText in project java-sdk by watson-developer-cloud.

the class RecognizeUsingWebSocketsExample method main.

public static void main(String[] args) throws FileNotFoundException, InterruptedException {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    SpeechToText service = new SpeechToText(authenticator);
    FileInputStream audio = new FileInputStream("src/test/resources/speech_to_text/sample1.wav");
    RecognizeWithWebsocketsOptions options = new RecognizeWithWebsocketsOptions.Builder().audio(audio).interimResults(true).contentType(HttpMediaType.AUDIO_WAV).build();
    service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() {

        @Override
        public void onTranscription(SpeechRecognitionResults speechResults) {
            System.out.println(speechResults);
        }

        @Override
        public void onDisconnected() {
            lock.countDown();
        }
    });
    lock.await(1, TimeUnit.MINUTES);
}
Also used : IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) BaseRecognizeCallback(com.ibm.watson.speech_to_text.v1.websocket.BaseRecognizeCallback) RecognizeWithWebsocketsOptions(com.ibm.watson.speech_to_text.v1.model.RecognizeWithWebsocketsOptions) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) FileInputStream(java.io.FileInputStream) SpeechRecognitionResults(com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResults)

Example 3 with SpeechToText

use of com.ibm.watson.speech_to_text.v1.SpeechToText in project java-sdk by watson-developer-cloud.

the class CustomizationExample method main.

/**
 * The main method.
 *
 * @param args the arguments
 * @throws InterruptedException the interrupted exception
 */
public static void main(String[] args) throws InterruptedException, FileNotFoundException {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    SpeechToText service = new SpeechToText(authenticator);
    // Create language model
    CreateLanguageModelOptions createOptions = new CreateLanguageModelOptions.Builder().name("IEEE-permanent").baseModelName("en-US_BroadbandModel").description("My customization").build();
    LanguageModel myModel = service.createLanguageModel(createOptions).execute().getResult();
    String id = myModel.getCustomizationId();
    try {
        // Add a corpus file to the model
        AddCorpusOptions addOptions = new AddCorpusOptions.Builder().customizationId(id).corpusName("corpus-1").corpusFile(new File(CORPUS_FILE)).allowOverwrite(false).build();
        service.addCorpus(addOptions).execute().getResult();
        // Get corpus status
        GetCorpusOptions getOptions = new GetCorpusOptions.Builder().customizationId(id).corpusName("corpus-1").build();
        for (int x = 0; x < 30 && !service.getCorpus(getOptions).execute().getResult().getStatus().equals(Corpus.Status.ANALYZED); x++) {
            Thread.sleep(5000);
        }
        // Get all corpora
        ListCorporaOptions listCorporaOptions = new ListCorporaOptions.Builder().customizationId(id).build();
        Corpora corpora = service.listCorpora(listCorporaOptions).execute().getResult();
        System.out.println(corpora);
        // Get specific corpus
        Corpus corpus = service.getCorpus(getOptions).execute().getResult();
        System.out.println(corpus);
        // Now add some user words to the custom model
        service.addWord(new AddWordOptions.Builder().customizationId(id).wordName("IEEE").word("IEEE").displayAs("IEEE").addSoundsLike("I. triple E.").build()).execute();
        service.addWord(new AddWordOptions.Builder().customizationId(id).wordName("hhonors").word("hhonors").displayAs("IEEE").addSoundsLike("H. honors").addSoundsLike("Hilton honors").build()).execute();
        // Display all words in the words resource (OOVs from the corpus and
        // new words just added) in ascending alphabetical order
        ListWordsOptions listWordsAlphabeticalOptions = new ListWordsOptions.Builder().customizationId(id).wordType(ListWordsOptions.WordType.ALL).build();
        Words words = service.listWords(listWordsAlphabeticalOptions).execute().getResult();
        System.out.println("\nASCENDING ALPHABETICAL ORDER:");
        System.out.println(words);
        // Then display all words in the words resource in descending order
        // by count
        ListWordsOptions listWordsCountOptions = new ListWordsOptions.Builder().customizationId(id).wordType(ListWordsOptions.WordType.ALL).sort("-" + ListWordsOptions.Sort.COUNT).build();
        words = service.listWords(listWordsCountOptions).execute().getResult();
        System.out.println("\nDESCENDING ORDER BY COUNT:");
        System.out.println(words);
        // Now start training of the model
        TrainLanguageModelOptions trainOptions = new TrainLanguageModelOptions.Builder().customizationId(id).wordTypeToAdd(TrainLanguageModelOptions.WordTypeToAdd.ALL).build();
        service.trainLanguageModel(trainOptions).execute();
        for (int x = 0; x < 30 && !myModel.getStatus().equals(LanguageModel.Status.AVAILABLE); x++) {
            GetLanguageModelOptions getLanguageModelOptions = new GetLanguageModelOptions.Builder().customizationId(id).build();
            myModel = service.getLanguageModel(getLanguageModelOptions).execute().getResult();
            Thread.sleep(10000);
        }
        File audio = new File(AUDIO_FILE);
        RecognizeOptions recognizeOptionsWithModel = new RecognizeOptions.Builder().model(RecognizeOptions.Model.EN_US_BROADBANDMODEL).customizationId(id).audio(audio).contentType(HttpMediaType.AUDIO_WAV).build();
        RecognizeOptions recognizeOptionsWithoutModel = new RecognizeOptions.Builder().model(RecognizeOptions.Model.EN_US_BROADBANDMODEL).audio(audio).contentType(HttpMediaType.AUDIO_WAV).build();
        // First decode WITHOUT the custom model
        SpeechRecognitionResults transcript = service.recognize(recognizeOptionsWithoutModel).execute().getResult();
        System.out.println(transcript);
        // Now decode with the custom model
        transcript = service.recognize(recognizeOptionsWithModel).execute().getResult();
        System.out.println(transcript);
    } finally {
        DeleteLanguageModelOptions deleteOptions = new DeleteLanguageModelOptions.Builder().customizationId(id).build();
        service.deleteLanguageModel(deleteOptions).execute();
    }
}
Also used : IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) CreateLanguageModelOptions(com.ibm.watson.speech_to_text.v1.model.CreateLanguageModelOptions) Corpus(com.ibm.watson.speech_to_text.v1.model.Corpus) DeleteLanguageModelOptions(com.ibm.watson.speech_to_text.v1.model.DeleteLanguageModelOptions) AddWordOptions(com.ibm.watson.speech_to_text.v1.model.AddWordOptions) LanguageModel(com.ibm.watson.speech_to_text.v1.model.LanguageModel) GetCorpusOptions(com.ibm.watson.speech_to_text.v1.model.GetCorpusOptions) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) AddCorpusOptions(com.ibm.watson.speech_to_text.v1.model.AddCorpusOptions) Corpora(com.ibm.watson.speech_to_text.v1.model.Corpora) GetLanguageModelOptions(com.ibm.watson.speech_to_text.v1.model.GetLanguageModelOptions) Words(com.ibm.watson.speech_to_text.v1.model.Words) ListWordsOptions(com.ibm.watson.speech_to_text.v1.model.ListWordsOptions) TrainLanguageModelOptions(com.ibm.watson.speech_to_text.v1.model.TrainLanguageModelOptions) File(java.io.File) ListCorporaOptions(com.ibm.watson.speech_to_text.v1.model.ListCorporaOptions) SpeechRecognitionResults(com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResults) RecognizeOptions(com.ibm.watson.speech_to_text.v1.model.RecognizeOptions)

Example 4 with SpeechToText

use of com.ibm.watson.speech_to_text.v1.SpeechToText in project java-sdk by watson-developer-cloud.

the class MicrophoneWithWebSocketsExample method main.

/**
 * The main method.
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(final String[] args) throws Exception {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    SpeechToText service = new SpeechToText(authenticator);
    // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
    int sampleRate = 16000;
    AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    if (!AudioSystem.isLineSupported(info)) {
        System.out.println("Line not supported");
        System.exit(0);
    }
    TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);
    line.start();
    AudioInputStream audio = new AudioInputStream(line);
    RecognizeWithWebsocketsOptions options = new RecognizeWithWebsocketsOptions.Builder().audio(audio).interimResults(true).timestamps(true).wordConfidence(true).contentType(HttpMediaType.AUDIO_RAW + ";rate=" + sampleRate).build();
    service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() {

        @Override
        public void onTranscription(SpeechRecognitionResults speechResults) {
            System.out.println(speechResults);
        }
    });
    System.out.println("Listening to your voice for the next 30s...");
    Thread.sleep(30 * 1000);
    // closing the WebSockets underlying InputStream will close the WebSocket itself.
    line.stop();
    line.close();
    System.out.println("Fin.");
}
Also used : IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) BaseRecognizeCallback(com.ibm.watson.speech_to_text.v1.websocket.BaseRecognizeCallback) TargetDataLine(javax.sound.sampled.TargetDataLine) DataLine(javax.sound.sampled.DataLine) TargetDataLine(javax.sound.sampled.TargetDataLine) AudioInputStream(javax.sound.sampled.AudioInputStream) AudioFormat(javax.sound.sampled.AudioFormat) RecognizeWithWebsocketsOptions(com.ibm.watson.speech_to_text.v1.model.RecognizeWithWebsocketsOptions) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) SpeechRecognitionResults(com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResults)

Example 5 with SpeechToText

use of com.ibm.watson.speech_to_text.v1.SpeechToText in project java-sdk by watson-developer-cloud.

the class RecognizeUsingWebSocketsWithSpeakerLabelsExample method main.

/**
 * The main method.
 *
 * @param args the arguments
 * @throws FileNotFoundException the file not found exception
 * @throws InterruptedException the interrupted exception
 */
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
    FileInputStream audio = new FileInputStream("src/test/resources/speech_to_text/twospeakers.wav");
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    SpeechToText service = new SpeechToText(authenticator);
    RecognizeWithWebsocketsOptions options = new RecognizeWithWebsocketsOptions.Builder().audio(audio).interimResults(true).speakerLabels(true).model(RecognizeOptions.Model.EN_US_NARROWBANDMODEL).contentType(HttpMediaType.AUDIO_WAV).build();
    RecoTokens recoTokens = new RecoTokens();
    service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() {

        @Override
        public void onTranscription(SpeechRecognitionResults speechResults) {
            recoTokens.add(speechResults);
        }

        @Override
        public void onDisconnected() {
            lock.countDown();
        }
    });
    lock.await(1, TimeUnit.MINUTES);
}
Also used : IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) BaseRecognizeCallback(com.ibm.watson.speech_to_text.v1.websocket.BaseRecognizeCallback) RecognizeWithWebsocketsOptions(com.ibm.watson.speech_to_text.v1.model.RecognizeWithWebsocketsOptions) FileInputStream(java.io.FileInputStream) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) SpeechRecognitionResults(com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResults)

Aggregations

IamAuthenticator (com.ibm.cloud.sdk.core.security.IamAuthenticator)6 Authenticator (com.ibm.cloud.sdk.core.security.Authenticator)5 SpeechRecognitionResults (com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResults)5 RecognizeWithWebsocketsOptions (com.ibm.watson.speech_to_text.v1.model.RecognizeWithWebsocketsOptions)4 BaseRecognizeCallback (com.ibm.watson.speech_to_text.v1.websocket.BaseRecognizeCallback)3 RecognizeOptions (com.ibm.watson.speech_to_text.v1.model.RecognizeOptions)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 SpeechToText (com.ibm.watson.speech_to_text.v1.SpeechToText)1 AddCorpusOptions (com.ibm.watson.speech_to_text.v1.model.AddCorpusOptions)1 AddWordOptions (com.ibm.watson.speech_to_text.v1.model.AddWordOptions)1 Corpora (com.ibm.watson.speech_to_text.v1.model.Corpora)1 Corpus (com.ibm.watson.speech_to_text.v1.model.Corpus)1 CreateLanguageModelOptions (com.ibm.watson.speech_to_text.v1.model.CreateLanguageModelOptions)1 DeleteLanguageModelOptions (com.ibm.watson.speech_to_text.v1.model.DeleteLanguageModelOptions)1 GetCorpusOptions (com.ibm.watson.speech_to_text.v1.model.GetCorpusOptions)1 GetLanguageModelOptions (com.ibm.watson.speech_to_text.v1.model.GetLanguageModelOptions)1 LanguageModel (com.ibm.watson.speech_to_text.v1.model.LanguageModel)1 ListCorporaOptions (com.ibm.watson.speech_to_text.v1.model.ListCorporaOptions)1 ListWordsOptions (com.ibm.watson.speech_to_text.v1.model.ListWordsOptions)1