2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.voice.mimic.internal;
15 import java.io.IOException;
16 import java.io.UnsupportedEncodingException;
17 import java.net.URLEncoder;
18 import java.nio.charset.StandardCharsets;
19 import java.util.HashSet;
20 import java.util.Locale;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.core.audio.AudioFormat;
27 import org.openhab.core.audio.AudioStream;
28 import org.openhab.core.audio.ByteArrayAudioStream;
29 import org.openhab.core.config.core.ConfigurableService;
30 import org.openhab.core.io.net.http.HttpRequestBuilder;
31 import org.openhab.core.io.net.http.HttpUtil;
32 import org.openhab.core.library.types.RawType;
33 import org.openhab.core.voice.TTSException;
34 import org.openhab.core.voice.TTSService;
35 import org.openhab.core.voice.Voice;
36 import org.openhab.voice.mimic.internal.dto.VoiceDto;
37 import org.osgi.framework.Constants;
38 import org.osgi.service.component.annotations.Activate;
39 import org.osgi.service.component.annotations.Component;
40 import org.osgi.service.component.annotations.Modified;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 import com.google.gson.Gson;
45 import com.google.gson.GsonBuilder;
46 import com.google.gson.JsonSyntaxException;
49 * Mimic Voice service implementation.
51 * @author Gwendal Roulleau - Initial contribution
53 @Component(configurationPid = MimicTTSService.SERVICE_PID, property = Constants.SERVICE_PID + "="
54 + MimicTTSService.SERVICE_PID)
55 @ConfigurableService(category = MimicTTSService.SERVICE_CATEGORY, label = MimicTTSService.SERVICE_NAME
56 + " Text-to-Speech", description_uri = MimicTTSService.SERVICE_CATEGORY + ":" + MimicTTSService.SERVICE_ID)
58 public class MimicTTSService implements TTSService {
60 static final String SERVICE_CATEGORY = "voice";
61 static final String SERVICE_ID = "mimictts";
62 static final String SERVICE_PID = "org.openhab." + SERVICE_CATEGORY + "." + SERVICE_ID;
63 static final String SERVICE_NAME = "Mimic";
66 * Configuration parameters
68 private static final String PARAM_URL = "url";
69 private static final String PARAM_SPEAKINGRATE = "speakingRate";
70 private static final String PARAM_AUDIOVOLATITLITY = "audioVolatility";
71 private static final String PARAM_PHONEMEVOLATITLITY = "phonemeVolatility";
76 private static final String LIST_VOICES_URL = "/api/voices";
77 private static final String SYNTHETIZE_URL = "/api/tts";
79 /** The only wave format supported */
80 private static final AudioFormat AUDIO_FORMAT = new AudioFormat(AudioFormat.CONTAINER_WAVE,
81 AudioFormat.CODEC_PCM_SIGNED, false, 16, 52000, 22050L, 1);
83 private Set<Voice> availableVoices = new HashSet<>();
88 private final Logger logger = LoggerFactory.getLogger(MimicTTSService.class);
90 private final MimicConfiguration config = new MimicConfiguration();
92 private final Gson gson = new GsonBuilder().create();
95 protected void activate(Map<String, Object> config) {
100 * Called by the framework when the configuration was updated.
102 * @param newConfig Updated configuration
105 private void updateConfig(Map<String, Object> newConfig) {
106 logger.debug("Updating configuration");
109 Object param = newConfig.get(PARAM_URL);
111 logger.warn("Missing URL to access Mimic TTS API. Using localhost");
113 config.url = param.toString();
118 param = newConfig.get(PARAM_AUDIOVOLATITLITY);
120 config.audioVolatility = Double.parseDouble(param.toString());
122 } catch (NumberFormatException e) {
123 logger.warn("Cannot parse audioVolatility parameter. Using default");
126 // phoneme volatility
128 param = newConfig.get(PARAM_PHONEMEVOLATITLITY);
130 config.phonemeVolatility = Double.parseDouble(param.toString());
132 } catch (NumberFormatException e) {
133 logger.warn("Cannot parse phonemeVolatility parameter. Using default");
138 param = newConfig.get(PARAM_SPEAKINGRATE);
140 config.speakingRate = Double.parseDouble(param.toString());
142 } catch (NumberFormatException e) {
143 logger.warn("Cannot parse speakingRate parameter. Using default");
150 public String getId() {
155 public String getLabel(@Nullable Locale locale) {
160 public Set<Voice> getAvailableVoices() {
161 return availableVoices;
164 public void refreshVoices() {
165 String url = config.url + LIST_VOICES_URL;
166 availableVoices.clear();
168 String responseVoices = HttpRequestBuilder.getFrom(url).getContentAsString();
169 VoiceDto[] mimicVoiceResponse = gson.fromJson(responseVoices, VoiceDto[].class);
170 if (mimicVoiceResponse == null) {
171 logger.warn("Cannot get mimic voices from the URL {}", url);
173 } else if (mimicVoiceResponse.length == 0) {
174 logger.debug("Voice set response from Mimic is empty ?!");
177 for (VoiceDto voiceDto : mimicVoiceResponse) {
178 if (voiceDto.speakers != null && voiceDto.speakers.size() > 0) {
179 for (String speaker : voiceDto.speakers) {
180 availableVoices.add(new MimicVoice(voiceDto.key, voiceDto.language, voiceDto.name, speaker));
183 availableVoices.add(new MimicVoice(voiceDto.key, voiceDto.language, voiceDto.name, null));
186 } catch (IOException | JsonSyntaxException e) {
187 logger.warn("Cannot get mimic voices from the URL {}, error {}", url, e.getMessage());
192 public Set<AudioFormat> getSupportedFormats() {
193 return Set.<AudioFormat> of(AUDIO_FORMAT);
197 * Checks parameters and calls the API to synthesize voice.
199 * @param text Input text.
200 * @param voice Selected voice.
201 * @param requestedFormat Format that is supported by the target sink as well.
202 * @return Output audio stream
203 * @throws TTSException in case the service is unavailable or a parameter is invalid.
206 public AudioStream synthesize(String text, Voice voice, AudioFormat requestedFormat) throws TTSException {
208 if (!availableVoices.contains(voice)) {
209 // let a chance for the service to update :
211 if (!availableVoices.contains(voice)) {
212 throw new TTSException("Voice " + voice.getUID() + " not available for MimicTTS");
216 logger.debug("Synthesize '{}' for voice '{}' in format {}", text, voice.getUID(), requestedFormat);
217 // Validate arguments
219 String trimmedText = text.trim();
220 if (trimmedText.isEmpty()) {
221 throw new TTSException("The passed text is empty");
223 if (!AUDIO_FORMAT.isCompatible(requestedFormat)) {
224 throw new TTSException("The passed AudioFormat is unsupported");
228 encodedText = URLEncoder.encode(text, StandardCharsets.UTF_8.toString());
229 } catch (UnsupportedEncodingException e) {
230 throw new IllegalArgumentException("Cannot encode text in URL " + text);
234 if (text.startsWith("<speak>")) {
238 // create the audio byte array for given text, locale, format
239 String urlTTS = config.url + SYNTHETIZE_URL + "?text=" + encodedText + "&voice="
240 + ((MimicVoice) voice).getTechnicalName() + ssml + "&noiseScale=" + config.audioVolatility + "&noiseW="
241 + config.phonemeVolatility + "&lengthScale=" + config.speakingRate + "&audioTarget=client";
242 logger.debug("Querying mimic with URL {}", urlTTS);
243 RawType responseWav = HttpUtil.downloadData(urlTTS, "audio/wav", false, -1);
244 if (responseWav == null) {
245 throw new TTSException("Cannot get wav from mimic url " + urlTTS);
247 return new ByteArrayAudioStream(responseWav.getBytes(), AUDIO_FORMAT);