|
25 | 25 | from __future__ import absolute_import |
26 | 26 |
|
27 | 27 | import json |
28 | | -from .watson_service import WatsonService |
| 28 | +from .watson_service import WatsonService, _remove_null_values |
29 | 29 | from .utils import deprecated |
30 | | - |
| 30 | +from watson_developer_cloud.websocket import RecognizeCallback, RecognizeListener |
| 31 | +from os.path import isfile |
| 32 | +import base64 |
| 33 | +import urllib |
31 | 34 | ############################################################################## |
32 | 35 | # Service |
33 | 36 | ############################################################################## |
@@ -183,6 +186,96 @@ def recognize(self, |
183 | 186 | accept_json=True) |
184 | 187 | return response |
185 | 188 |
|
| 189 | + def recognize_with_websocket(self, |
| 190 | + audio=None, |
| 191 | + content_type='audio/l16; rate=44100', |
| 192 | + model='en-US_BroadbandModel', |
| 193 | + recognize_callback=None, |
| 194 | + customization_id=None, |
| 195 | + acoustic_customization_id=None, |
| 196 | + customization_weight=None, |
| 197 | + version=None, |
| 198 | + inactivity_timeout=None, |
| 199 | + interim_results=True, |
| 200 | + keywords=None, |
| 201 | + keywords_threshold=None, |
| 202 | + max_alternatives=1, |
| 203 | + word_alternatives_threshold=None, |
| 204 | + word_confidence=False, |
| 205 | + timestamps=False, |
| 206 | + profanity_filter=None, |
| 207 | + smart_formatting=False, |
| 208 | + speaker_labels=None): |
| 209 | + """ |
| 210 | + Sends audio for speech recognition using web sockets. |
| 211 | +
|
| 212 | + :param str audio: Audio to transcribe in the format specified by the `Content-Type` header. |
| 213 | + :param str content_type: The type of the input: audio/basic, audio/flac, audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg, audio/ogg;codecs=opus, audio/ogg;codecs=vorbis, audio/wav, audio/webm, audio/webm;codecs=opus, audio/webm;codecs=vorbis, or multipart/form-data. |
| 214 | + :param str model: The identifier of the model to be used for the recognition request. |
| 215 | + :param RecognizeCallback recognize_callback: The instance handling events returned from the service. |
| 216 | + :param str customization_id: The GUID of a custom language model that is to be used with the request. The base model of the specified custom language model must match the model specified with the `model` parameter. You must make the request with service credentials created for the instance of the service that owns the custom model. By default, no custom language model is used. |
| 217 | + :param str acoustic_customization_id: The GUID of a custom acoustic model that is to be used with the request. The base model of the specified custom acoustic model must match the model specified with the `model` parameter. You must make the request with service credentials created for the instance of the service that owns the custom model. By default, no custom acoustic model is used. |
| 218 | + :param float customization_weight: If you specify a `customization_id` with the request, you can use the `customization_weight` parameter to tell the service how much weight to give to words from the custom language model compared to those from the base model for speech recognition. Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model when it was trained, the default value is 0.3. A customization weight that you specify overrides a weight that was specified when the custom model was trained. The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the accuracy of phrases from the custom model's domain, but it can negatively affect performance on non-domain phrases. |
| 219 | + :param str version: The version of the specified base `model` that is to be used for speech recognition. Multiple versions of a base model can exist when a model is updated for internal improvements. The parameter is intended primarily for use with custom models that have been upgraded for a new base model. The default value depends on whether the parameter is used with or without a custom model. For more information, see [Base model version](https://console.bluemix.net/docs/services/speech-to-text/input.html#version). |
| 220 | + :param int inactivity_timeout: The time in seconds after which, if only silence (no speech) is detected in submitted audio, the connection is closed with a 400 error. Useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. |
| 221 | + :param bool interim_results: Send back non-final previews of each "sentence" as it is being processed. These results are ignored in text mode. |
| 222 | + :param list[str] keywords: Array of keyword strings to spot in the audio. Each keyword string can include one or more tokens. Keywords are spotted only in the final hypothesis, not in interim results. If you specify any keywords, you must also specify a keywords threshold. Omit the parameter or specify an empty array if you do not need to spot keywords. |
| 223 | + :param float keywords_threshold: Confidence value that is the lower bound for spotting a keyword. A word is considered to match a keyword if its confidence is greater than or equal to the threshold. Specify a probability between 0 and 1 inclusive. No keyword spotting is performed if you omit the parameter. If you specify a threshold, you must also specify one or more keywords. |
| 224 | + :param int max_alternatives: Maximum number of alternative transcripts to be returned. By default, a single transcription is returned. |
| 225 | + :param float word_alternatives_threshold: Confidence value that is the lower bound for identifying a hypothesis as a possible word alternative (also known as \"Confusion Networks\"). An alternative word is considered if its confidence is greater than or equal to the threshold. Specify a probability between 0 and 1 inclusive. No alternative words are computed if you omit the parameter. |
| 226 | + :param bool word_confidence: If `true`, confidence measure per word is returned. |
| 227 | + :param bool timestamps: If `true`, time alignment for each word is returned. |
| 228 | + :param bool profanity_filter: If `true` (the default), filters profanity from all output except for keyword results by replacing inappropriate words with a series of asterisks. Set the parameter to `false` to return results with no censoring. Applies to US English transcription only. |
| 229 | + :param bool smart_formatting: If `true`, converts dates, times, series of digits and numbers, phone numbers, currency values, and Internet addresses into more readable, conventional representations in the final transcript of a recognition request. If `false` (the default), no formatting is performed. Applies to US English transcription only. |
| 230 | + :param bool speaker_labels: Indicates whether labels that identify which words were spoken by which participants in a multi-person exchange are to be included in the response. The default is `false`; no speaker labels are returned. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. To determine whether a language model supports speaker labels, use the `GET /v1/models` method and check that the attribute `speaker_labels` is set to `true`. You can also refer to [Speaker labels](https://console.bluemix.net/docs/services/speech-to-text/output.html#speaker_labels). |
| 231 | + :return: |
| 232 | + """ |
| 233 | + if audio is None: |
| 234 | + raise ValueError('Audio must be provided') |
| 235 | + if recognize_callback is None: |
| 236 | + raise ValueError('Recognize callback must be provided') |
| 237 | + if not isinstance(recognize_callback, RecognizeCallback): |
| 238 | + raise Exception('Callback is not a derived class of RecognizeCallback') |
| 239 | + |
| 240 | + headers = {} |
| 241 | + if self.default_headers is not None: |
| 242 | + headers = self.default_headers.copy() |
| 243 | + base64_authorization = base64.b64encode(self.username + ':' + self.password) |
| 244 | + headers['Authorization'] = 'Basic {0}'.format(base64_authorization) |
| 245 | + |
| 246 | + url = self.url.replace('https:', 'wss:') |
| 247 | + params = { |
| 248 | + 'model': model, |
| 249 | + 'customization_id': customization_id, |
| 250 | + 'acoustic_customization_id': acoustic_customization_id, |
| 251 | + 'customization_weight': customization_weight, |
| 252 | + 'version': version |
| 253 | + } |
| 254 | + params = _remove_null_values(params) |
| 255 | + url = url + '/v1/recognize?{0}'.format(urllib.urlencode(params)) |
| 256 | + |
| 257 | + options = { |
| 258 | + 'content_type': content_type, |
| 259 | + 'inactivity_timeout': inactivity_timeout, |
| 260 | + 'interim_results': interim_results, |
| 261 | + 'keywords': keywords, |
| 262 | + 'keywords_threshold': keywords_threshold, |
| 263 | + 'max_alternatives': max_alternatives, |
| 264 | + 'word_alternatives_threshold': word_alternatives_threshold, |
| 265 | + 'word_confidence': word_confidence, |
| 266 | + 'timestamps': timestamps, |
| 267 | + 'profanity_filter': profanity_filter, |
| 268 | + 'smart_formatting': smart_formatting, |
| 269 | + 'speaker_labels': speaker_labels |
| 270 | + } |
| 271 | + options = _remove_null_values(options) |
| 272 | + |
| 273 | + recognizeListener = RecognizeListener(audio, |
| 274 | + options, |
| 275 | + recognize_callback, |
| 276 | + url, |
| 277 | + headers) |
| 278 | + |
186 | 279 | ######################### |
187 | 280 | # asynchronous |
188 | 281 | ######################### |
|
0 commit comments