Skip to content

Commit 264807d

Browse files
gabe-l-hartmamoonrajaapaparazzi0329
authored
fix: robustify the STT streaming results handling (#768)
* fix: robustify the STT streaming results handling In the STT recognize_listener, the clause that handles 'results' or 'speaker_labels' was prone to index errors when the 'results' object returned by the service was empty. This can happen, so this change makes that logic safe to empty (or otherwise malformed) results. * Remove buggy extra call to on_hypothesis Co-authored-by: Mamoon Raja <mamoonraja1@gmail.com> Co-authored-by: Angelo Paparazzi <angelo.paparazzi@ibm.com>
1 parent a23a745 commit 264807d

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

ibm_watson/websocket/recognize_listener.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -194,18 +194,21 @@ def on_data(self, ws, message, message_type, fin):
194194

195195
# if in streaming
196196
elif 'results' in json_object or 'speaker_labels' in json_object:
197-
hypothesis = ''
198-
if 'results' in json_object:
199-
hypothesis = json_object['results'][0]['alternatives'][0][
200-
'transcript']
201-
b_final = (json_object['results'][0]['final'] is True)
202-
transcripts = self.extract_transcripts(
203-
json_object['results'][0]['alternatives'])
204-
205-
if b_final:
206-
self.callback.on_transcription(transcripts)
207-
208-
self.callback.on_hypothesis(hypothesis)
197+
# If results are present, extract the hypothesis and, if finalized, the full
198+
# set of transcriptions and send them to the appropriate callbacks.
199+
results = json_object.get('results')
200+
if results:
201+
b_final = (results[0].get('final') is True)
202+
alternatives = results[0].get('alternatives')
203+
if alternatives:
204+
hypothesis = alternatives[0].get('transcript')
205+
transcripts = self.extract_transcripts(alternatives)
206+
if b_final:
207+
self.callback.on_transcription(transcripts)
208+
if hypothesis:
209+
self.callback.on_hypothesis(hypothesis)
210+
211+
# Always call the on_data callback if 'results' or 'speaker_labels' are present
209212
self.callback.on_data(json_object)
210213

211214
def on_error(self, ws, error):

0 commit comments

Comments
 (0)