]> git.basschouten.com Git - openhab-addons.git/blob
311ebb769c1882e98a9ccf18629b28e5aa968118
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.voice.watsonstt.internal;
14
15 import static org.openhab.voice.watsonstt.internal.WatsonSTTConstants.*;
16
17 import java.util.List;
18 import java.util.Locale;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.concurrent.ScheduledExecutorService;
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.concurrent.atomic.AtomicReference;
24 import java.util.stream.Collectors;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.core.audio.AudioFormat;
29 import org.openhab.core.audio.AudioStream;
30 import org.openhab.core.common.ThreadPoolManager;
31 import org.openhab.core.config.core.ConfigurableService;
32 import org.openhab.core.config.core.Configuration;
33 import org.openhab.core.voice.RecognitionStartEvent;
34 import org.openhab.core.voice.RecognitionStopEvent;
35 import org.openhab.core.voice.STTException;
36 import org.openhab.core.voice.STTListener;
37 import org.openhab.core.voice.STTService;
38 import org.openhab.core.voice.STTServiceHandle;
39 import org.openhab.core.voice.SpeechRecognitionErrorEvent;
40 import org.openhab.core.voice.SpeechRecognitionEvent;
41 import org.osgi.framework.Constants;
42 import org.osgi.service.component.annotations.Activate;
43 import org.osgi.service.component.annotations.Component;
44 import org.osgi.service.component.annotations.Modified;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.gson.JsonObject;
49 import com.ibm.cloud.sdk.core.http.HttpMediaType;
50 import com.ibm.cloud.sdk.core.security.IamAuthenticator;
51 import com.ibm.watson.speech_to_text.v1.SpeechToText;
52 import com.ibm.watson.speech_to_text.v1.model.RecognizeWithWebsocketsOptions;
53 import com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionAlternative;
54 import com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResult;
55 import com.ibm.watson.speech_to_text.v1.model.SpeechRecognitionResults;
56 import com.ibm.watson.speech_to_text.v1.websocket.RecognizeCallback;
57
58 import okhttp3.WebSocket;
59
60 /**
61  * The {@link WatsonSTTService} allows to use Watson as Speech-to-Text engine
62  *
63  * @author Miguel Álvarez - Initial contribution
64  */
65 @NonNullByDefault
66 @Component(configurationPid = SERVICE_PID, property = Constants.SERVICE_PID + "=" + SERVICE_PID)
67 @ConfigurableService(category = SERVICE_CATEGORY, label = SERVICE_NAME
68         + " Speech-to-Text", description_uri = SERVICE_CATEGORY + ":" + SERVICE_ID)
69 public class WatsonSTTService implements STTService {
70     private final Logger logger = LoggerFactory.getLogger(WatsonSTTService.class);
71     private final ScheduledExecutorService executor = ThreadPoolManager.getScheduledPool("OH-voice-watsonstt");
72     private final List<String> models = List.of("ar-AR_BroadbandModel", "de-DE_BroadbandModel", "en-AU_BroadbandModel",
73             "en-GB_BroadbandModel", "en-US_BroadbandModel", "es-AR_BroadbandModel", "es-CL_BroadbandModel",
74             "es-CO_BroadbandModel", "es-ES_BroadbandModel", "es-MX_BroadbandModel", "es-PE_BroadbandModel",
75             "fr-CA_BroadbandModel", "fr-FR_BroadbandModel", "it-IT_BroadbandModel", "ja-JP_BroadbandModel",
76             "ko-KR_BroadbandModel", "nl-NL_BroadbandModel", "pt-BR_BroadbandModel", "zh-CN_BroadbandModel");
77     private final Set<Locale> supportedLocales = models.stream().map(name -> name.split("_")[0])
78             .map(Locale::forLanguageTag).collect(Collectors.toSet());
79     private WatsonSTTConfiguration config = new WatsonSTTConfiguration();
80
81     @Activate
82     protected void activate(Map<String, Object> config) {
83         this.config = new Configuration(config).as(WatsonSTTConfiguration.class);
84     }
85
86     @Modified
87     protected void modified(Map<String, Object> config) {
88         this.config = new Configuration(config).as(WatsonSTTConfiguration.class);
89     }
90
91     @Override
92     public String getId() {
93         return SERVICE_ID;
94     }
95
96     @Override
97     public String getLabel(@Nullable Locale locale) {
98         return SERVICE_NAME;
99     }
100
101     @Override
102     public Set<Locale> getSupportedLocales() {
103         return supportedLocales;
104     }
105
106     @Override
107     public Set<AudioFormat> getSupportedFormats() {
108         return Set.of(AudioFormat.WAV, AudioFormat.OGG, new AudioFormat("OGG", "OPUS", null, null, null, null),
109                 AudioFormat.MP3);
110     }
111
112     @Override
113     public STTServiceHandle recognize(STTListener sttListener, AudioStream audioStream, Locale locale, Set<String> set)
114             throws STTException {
115         if (config.apiKey.isBlank() || config.instanceUrl.isBlank()) {
116             throw new STTException("service is not correctly configured");
117         }
118         String contentType = getContentType(audioStream);
119         if (contentType == null) {
120             throw new STTException("Unsupported format, unable to resolve audio content type");
121         }
122         logger.debug("Content-Type: {}", contentType);
123         var speechToText = new SpeechToText(new IamAuthenticator.Builder().apikey(config.apiKey).build());
124         speechToText.setServiceUrl(config.instanceUrl);
125         if (config.optOutLogging) {
126             speechToText.setDefaultHeaders(Map.of("X-Watson-Learning-Opt-Out", "1"));
127         }
128         RecognizeWithWebsocketsOptions wsOptions = new RecognizeWithWebsocketsOptions.Builder().audio(audioStream)
129                 .contentType(contentType).redaction(config.redaction).smartFormatting(config.smartFormatting)
130                 .model(locale.toLanguageTag() + "_BroadbandModel").interimResults(true)
131                 .backgroundAudioSuppression(config.backgroundAudioSuppression)
132                 .speechDetectorSensitivity(config.speechDetectorSensitivity).inactivityTimeout(config.maxSilenceSeconds)
133                 .build();
134         final AtomicReference<@Nullable WebSocket> socketRef = new AtomicReference<>();
135         final AtomicBoolean aborted = new AtomicBoolean(false);
136         executor.submit(() -> {
137             socketRef.set(speechToText.recognizeUsingWebSocket(wsOptions,
138                     new TranscriptionListener(socketRef, sttListener, config, aborted)));
139         });
140         return new STTServiceHandle() {
141             @Override
142             public void abort() {
143                 if (!aborted.getAndSet(true)) {
144                     var socket = socketRef.get();
145                     if (socket != null) {
146                         sendStopMessage(socket);
147                     }
148                 }
149             }
150         };
151     }
152
153     private @Nullable String getContentType(AudioStream audioStream) throws STTException {
154         AudioFormat format = audioStream.getFormat();
155         String container = format.getContainer();
156         String codec = format.getCodec();
157         if (container == null || codec == null) {
158             throw new STTException("Missing audio stream info");
159         }
160         Long frequency = format.getFrequency();
161         Integer bitDepth = format.getBitDepth();
162         switch (container) {
163             case AudioFormat.CONTAINER_WAVE:
164                 if (AudioFormat.CODEC_PCM_SIGNED.equals(codec)) {
165                     if (bitDepth == null || bitDepth != 16) {
166                         return "audio/wav";
167                     }
168                     // rate is a required parameter for this type
169                     if (frequency == null) {
170                         return null;
171                     }
172                     StringBuilder contentTypeL16 = new StringBuilder(HttpMediaType.AUDIO_PCM).append(";rate=")
173                             .append(frequency);
174                     // // those are optional
175                     Integer channels = format.getChannels();
176                     if (channels != null) {
177                         contentTypeL16.append(";channels=").append(channels);
178                     }
179                     Boolean bigEndian = format.isBigEndian();
180                     if (bigEndian != null) {
181                         contentTypeL16.append(";")
182                                 .append(bigEndian ? "endianness=big-endian" : "endianness=little-endian");
183                     }
184                     return contentTypeL16.toString();
185                 }
186             case AudioFormat.CONTAINER_OGG:
187                 switch (codec) {
188                     case AudioFormat.CODEC_VORBIS:
189                         return "audio/ogg;codecs=vorbis";
190                     case "OPUS":
191                         return "audio/ogg;codecs=opus";
192                 }
193                 break;
194             case AudioFormat.CONTAINER_NONE:
195                 if (AudioFormat.CODEC_MP3.equals(codec)) {
196                     return "audio/mp3";
197                 }
198                 break;
199         }
200         return null;
201     }
202
203     private static void sendStopMessage(WebSocket ws) {
204         JsonObject stopMessage = new JsonObject();
205         stopMessage.addProperty("action", "stop");
206         ws.send(stopMessage.toString());
207     }
208
209     private static class TranscriptionListener implements RecognizeCallback {
210         private final Logger logger = LoggerFactory.getLogger(TranscriptionListener.class);
211         private final StringBuilder transcriptBuilder = new StringBuilder();
212         private final STTListener sttListener;
213         private final WatsonSTTConfiguration config;
214         private final AtomicBoolean aborted;
215         private final AtomicReference<@Nullable WebSocket> socketRef;
216         private float confidenceSum = 0f;
217         private int responseCount = 0;
218         private boolean disconnected = false;
219
220         public TranscriptionListener(AtomicReference<@Nullable WebSocket> socketRef, STTListener sttListener,
221                 WatsonSTTConfiguration config, AtomicBoolean aborted) {
222             this.socketRef = socketRef;
223             this.sttListener = sttListener;
224             this.config = config;
225             this.aborted = aborted;
226         }
227
228         @Override
229         public void onTranscription(@Nullable SpeechRecognitionResults speechRecognitionResults) {
230             logger.debug("onTranscription");
231             if (speechRecognitionResults == null) {
232                 return;
233             }
234             speechRecognitionResults.getResults().stream().filter(SpeechRecognitionResult::isXFinal).forEach(result -> {
235                 SpeechRecognitionAlternative alternative = result.getAlternatives().stream().findFirst().orElse(null);
236                 if (alternative == null) {
237                     return;
238                 }
239                 logger.debug("onTranscription Final");
240                 Double confidence = alternative.getConfidence();
241                 transcriptBuilder.append(alternative.getTranscript());
242                 confidenceSum += confidence != null ? confidence.floatValue() : 0f;
243                 responseCount++;
244                 if (config.singleUtteranceMode) {
245                     var socket = socketRef.get();
246                     if (socket != null) {
247                         sendStopMessage(socket);
248                     }
249                 }
250             });
251         }
252
253         @Override
254         public void onConnected() {
255             logger.debug("onConnected");
256         }
257
258         @Override
259         public void onError(@Nullable Exception e) {
260             var errorMessage = e != null ? e.getMessage() : null;
261             if (errorMessage != null && disconnected && errorMessage.contains("Socket closed")) {
262                 logger.debug("Error ignored: {}", errorMessage);
263                 return;
264             }
265             logger.warn("TranscriptionError: {}", errorMessage);
266             if (!aborted.getAndSet(true)) {
267                 sttListener.sttEventReceived(
268                         new SpeechRecognitionErrorEvent(errorMessage != null ? errorMessage : "Unknown error"));
269             }
270         }
271
272         @Override
273         public void onDisconnected() {
274             logger.debug("onDisconnected");
275             disconnected = true;
276             if (!aborted.getAndSet(true)) {
277                 sttListener.sttEventReceived(new RecognitionStopEvent());
278                 float averageConfidence = confidenceSum / (float) responseCount;
279                 String transcript = transcriptBuilder.toString().trim();
280                 if (!transcript.isBlank()) {
281                     sttListener.sttEventReceived(new SpeechRecognitionEvent(transcript, averageConfidence));
282                 } else {
283                     if (!config.noResultsMessage.isBlank()) {
284                         sttListener.sttEventReceived(new SpeechRecognitionErrorEvent(config.noResultsMessage));
285                     } else {
286                         sttListener.sttEventReceived(new SpeechRecognitionErrorEvent("No results"));
287                     }
288                 }
289             }
290         }
291
292         @Override
293         public void onInactivityTimeout(@Nullable RuntimeException e) {
294             if (e != null) {
295                 logger.debug("InactivityTimeout: {}", e.getMessage());
296             }
297         }
298
299         @Override
300         public void onListening() {
301             logger.debug("onListening");
302             sttListener.sttEventReceived(new RecognitionStartEvent());
303         }
304
305         @Override
306         public void onTranscriptionComplete() {
307             logger.debug("onTranscriptionComplete");
308         }
309     }
310 }