/
demo.jsx
585 lines (514 loc) · 21.8 KB
/
demo.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/* eslint no-param-reassign: 0 */
import React, { Component } from 'react';
import Dropzone from 'react-dropzone';
import {
Icon, Tabs, Pane, Alert,
} from 'watson-react-components';
import recognizeMicrophone from 'watson-speech/speech-to-text/recognize-microphone';
import recognizeFile from 'watson-speech/speech-to-text/recognize-file';
import ModelDropdown from './model-dropdown.jsx';
import Transcript from './transcript.jsx';
import { Keywords, getKeywordsSummary } from './keywords.jsx';
import SpeakersView from './speaker.jsx';
import TimingView from './timing.jsx';
import JSONView from './json-view.jsx';
import samples from '../src/data/samples.json';
import cachedModels from '../src/data/models.json';
const ERR_MIC_NARROWBAND = 'Microphone transcription cannot accommodate narrowband voice models, please select a broadband one.';
const NEW_DEMO_NOTIFICATION = 'A new Speech to Text demo is available, check it out ';
export class Demo extends Component {
constructor(props) {
super();
this.state = {
model: 'en-US_BroadbandModel',
rawMessages: [],
formattedMessages: [],
audioSource: null,
speakerLabels: false,
keywords: this.getKeywords('en-US_BroadbandModel'),
// transcript model and keywords are the state that they were when the button was clicked.
// Changing them during a transcription would cause a mismatch between the setting sent to the
// service and what is displayed on the demo, and could cause bugs.
settingsAtStreamStart: {
model: '',
keywords: [],
speakerLabels: false,
},
error: null,
};
this.handleSampleClick = this.handleSampleClick.bind(this);
this.handleSample1Click = this.handleSample1Click.bind(this);
this.handleSample2Click = this.handleSample2Click.bind(this);
this.reset = this.reset.bind(this);
this.captureSettings = this.captureSettings.bind(this);
this.stopTranscription = this.stopTranscription.bind(this);
this.getRecognizeOptions = this.getRecognizeOptions.bind(this);
this.isNarrowBand = this.isNarrowBand.bind(this);
this.handleMicClick = this.handleMicClick.bind(this);
this.handleUploadClick = this.handleUploadClick.bind(this);
this.handleUserFile = this.handleUserFile.bind(this);
this.handleUserFileRejection = this.handleUserFileRejection.bind(this);
this.playFile = this.playFile.bind(this);
this.handleStream = this.handleStream.bind(this);
this.handleRawMessage = this.handleRawMessage.bind(this);
this.handleFormattedMessage = this.handleFormattedMessage.bind(this);
this.handleTranscriptEnd = this.handleTranscriptEnd.bind(this);
this.getKeywords = this.getKeywords.bind(this);
this.handleModelChange = this.handleModelChange.bind(this);
this.supportsSpeakerLabels = this.supportsSpeakerLabels.bind(this);
this.handleSpeakerLabelsChange = this.handleSpeakerLabelsChange.bind(this);
this.handleKeywordsChange = this.handleKeywordsChange.bind(this);
this.getKeywordsArr = this.getKeywordsArr.bind(this);
this.getKeywordsArrUnique = this.getKeywordsArrUnique.bind(this);
this.getFinalResults = this.getFinalResults.bind(this);
this.getCurrentInterimResult = this.getCurrentInterimResult.bind(this);
this.getFinalAndLatestInterimResult = this.getFinalAndLatestInterimResult.bind(this);
this.handleError = this.handleError.bind(this);
}
reset() {
if (this.state.audioSource) {
this.stopTranscription();
}
this.setState({ rawMessages: [], formattedMessages: [], error: null });
}
/**
* The behavior of several of the views depends on the settings when the
* transcription was started. So, this stores those values in a settingsAtStreamStart object.
*/
captureSettings() {
const { model, speakerLabels } = this.state;
this.setState({
settingsAtStreamStart: {
model,
keywords: this.getKeywordsArrUnique(),
speakerLabels,
},
});
}
stopTranscription() {
if (this.stream) {
this.stream.stop();
// this.stream.removeAllListeners();
// this.stream.recognizeStream.removeAllListeners();
}
this.setState({ audioSource: null });
}
getRecognizeOptions(extra) {
const keywords = this.getKeywordsArrUnique();
return Object.assign({
// formats phone numbers, currency, etc. (server-side)
access_token: this.state.accessToken,
token: this.state.token,
smart_formatting: true,
format: true, // adds capitals, periods, and a few other things (client-side)
model: this.state.model,
objectMode: true,
interim_results: true,
// note: in normal usage, you'd probably set this a bit higher
word_alternatives_threshold: 0.01,
keywords,
keywords_threshold: keywords.length
? 0.01
: undefined, // note: in normal usage, you'd probably set this a bit higher
timestamps: true, // set timestamps for each word - automatically turned on by speaker_labels
// includes the speaker_labels in separate objects unless resultsBySpeaker is enabled
speaker_labels: this.state.speakerLabels,
// combines speaker_labels and results together into single objects,
// making for easier transcript outputting
resultsBySpeaker: this.state.speakerLabels,
// allow interim results through before the speaker has been determined
speakerlessInterim: this.state.speakerLabels,
url: this.state.serviceUrl,
}, extra);
}
isNarrowBand(model) {
model = model || this.state.model;
return model.indexOf('Narrowband') !== -1;
}
handleMicClick() {
if (this.state.audioSource === 'mic') {
this.stopTranscription();
return;
}
this.reset();
this.setState({ audioSource: 'mic' });
// The recognizeMicrophone() method is a helper method provided by the watson-speech package
// It sets up the microphone, converts and downsamples the audio, and then transcribes it
// over a WebSocket connection
// It also provides a number of optional features, some of which are enabled by default:
// * enables object mode by default (options.objectMode)
// * formats results (Capitals, periods, etc.) (options.format)
// * outputs the text to a DOM element - not used in this demo because it doesn't play nice
// with react (options.outputElement)
// * a few other things for backwards compatibility and sane defaults
// In addition to this, it passes other service-level options along to the RecognizeStream that
// manages the actual WebSocket connection.
this.handleStream(recognizeMicrophone(this.getRecognizeOptions()));
}
handleUploadClick() {
if (this.state.audioSource === 'upload') {
this.stopTranscription();
} else {
this.dropzone.open();
}
}
handleUserFile(files) {
const file = files[0];
if (!file) {
return;
}
this.reset();
this.setState({ audioSource: 'upload' });
this.playFile(file);
}
handleUserFileRejection() {
this.setState({ error: 'Sorry, that file does not appear to be compatible.' });
}
handleSample1Click() {
this.handleSampleClick(1);
}
handleSample2Click() {
this.handleSampleClick(2);
}
handleSampleClick(which) {
if (this.state.audioSource === `sample-${which}`) {
this.stopTranscription();
} else {
const filename = samples[this.state.model] && samples[this.state.model][which - 1].filename;
if (!filename) {
this.handleError(`No sample ${which} available for model ${this.state.model}`, samples[this.state.model]);
}
this.reset();
this.setState({ audioSource: `sample-${which}` });
this.playFile(`audio/${filename}`);
}
}
/**
* @param {File|Blob|String} file - url to an audio file or a File
* instance fro user-provided files.
*/
playFile(file) {
// The recognizeFile() method is a helper method provided by the watson-speach package
// It accepts a file input and transcribes the contents over a WebSocket connection
// It also provides a number of optional features, some of which are enabled by default:
// * enables object mode by default (options.objectMode)
// * plays the file in the browser if possible (options.play)
// * formats results (Capitals, periods, etc.) (options.format)
// * slows results down to realtime speed if received faster than realtime -
// this causes extra interim `data` events to be emitted (options.realtime)
// * combines speaker_labels with results (options.resultsBySpeaker)
// * outputs the text to a DOM element - not used in this demo because it doesn't play
// nice with react (options.outputElement)
// * a few other things for backwards compatibility and sane defaults
// In addition to this, it passes other service-level options along to the RecognizeStream
// that manages the actual WebSocket connection.
this.handleStream(recognizeFile(this.getRecognizeOptions({
file,
play: true, // play the audio out loud
// use a helper stream to slow down the transcript output to match the audio speed
realtime: true,
})));
}
handleStream(stream) {
console.log(stream);
// cleanup old stream if appropriate
if (this.stream) {
this.stream.stop();
this.stream.removeAllListeners();
this.stream.recognizeStream.removeAllListeners();
}
this.stream = stream;
this.captureSettings();
// grab the formatted messages and also handle errors and such
stream.on('data', this.handleFormattedMessage).on('end', this.handleTranscriptEnd).on('error', this.handleError);
// when errors occur, the end event may not propagate through the helper streams.
// However, the recognizeStream should always fire a end and close events
stream.recognizeStream.on('end', () => {
if (this.state.error) {
this.handleTranscriptEnd();
}
});
// grab raw messages from the debugging events for display on the JSON tab
stream.recognizeStream
.on('message', (frame, json) => this.handleRawMessage({ sent: false, frame, json }))
.on('send-json', json => this.handleRawMessage({ sent: true, json }))
.once('send-data', () => this.handleRawMessage({
sent: true, binary: true, data: true, // discard the binary data to avoid waisting memory
}))
.on('close', (code, message) => this.handleRawMessage({ close: true, code, message }));
// ['open','close','finish','end','error', 'pipe'].forEach(e => {
// stream.recognizeStream.on(e, console.log.bind(console, 'rs event: ', e));
// stream.on(e, console.log.bind(console, 'stream event: ', e));
// });
}
handleRawMessage(msg) {
const { rawMessages } = this.state;
this.setState({ rawMessages: rawMessages.concat(msg) });
}
handleFormattedMessage(msg) {
const { formattedMessages } = this.state;
this.setState({ formattedMessages: formattedMessages.concat(msg) });
}
handleTranscriptEnd() {
// note: this function will be called twice on a clean end,
// but may only be called once in the event of an error
this.setState({ audioSource: null });
}
componentDidMount() {
this.fetchToken();
// tokens expire after 60 minutes, so automatcally fetch a new one ever 50 minutes
// Not sure if this will work properly if a computer goes to sleep for > 50 minutes
// and then wakes back up
// react automatically binds the call to this
// eslint-disable-next-line
this.setState({ tokenInterval: setInterval(this.fetchToken, 50 * 60 * 1000) });
}
componentWillUnmount() {
clearInterval(this.state.tokenInterval);
}
fetchToken() {
return fetch('/api/v1/credentials').then((res) => {
if (res.status !== 200) {
throw new Error('Error retrieving auth token');
}
return res.json();
}) // todo: throw here if non-200 status
.then(creds => this.setState({ ...creds })).catch(this.handleError);
}
getKeywords(model) {
// a few models have more than two sample files, but the demo can only handle
// two samples at the moment
// so this just takes the keywords from the first two samples
const files = samples[model];
return (files && files.length >= 2 && `${files[0].keywords}, ${files[1].keywords}`) || '';
}
handleModelChange(model) {
this.reset();
this.setState({
model,
keywords: this.getKeywords(model),
speakerLabels: this.supportsSpeakerLabels(model),
});
// clear the microphone narrowband error if it's visible and a broadband model was just selected
if (this.state.error === ERR_MIC_NARROWBAND && !this.isNarrowBand(model)) {
this.setState({ error: null });
}
// clear the speaker_lables is not supported error - e.g.
// speaker_labels is not a supported feature for model en-US_BroadbandModel
if (this.state.error && this.state.error.indexOf('speaker_labels is not a supported feature for model') === 0) {
this.setState({ error: null });
}
}
supportsSpeakerLabels(model) {
model = model || this.state.model;
// todo: read the upd-to-date models list instead of the cached one
return cachedModels.some(m => m.name === model && m.supported_features.speaker_labels);
}
handleSpeakerLabelsChange() {
this.setState(prevState => ({ speakerLabels: !prevState.speakerLabels }));
}
handleKeywordsChange(e) {
this.setState({ keywords: e.target.value });
}
// cleans up the keywords string into an array of individual, trimmed, non-empty keywords/phrases
getKeywordsArr() {
return this.state.keywords.split(',').map(k => k.trim()).filter(k => k);
}
// cleans up the keywords string and produces a unique list of keywords
getKeywordsArrUnique() {
return this.state.keywords
.split(',')
.map(k => k.trim())
.filter((value, index, self) => self.indexOf(value) === index);
}
getFinalResults() {
return this.state.formattedMessages.filter(r => r.results
&& r.results.length && r.results[0].final);
}
getCurrentInterimResult() {
const r = this.state.formattedMessages[this.state.formattedMessages.length - 1];
// When resultsBySpeaker is enabled, each msg.results array may contain multiple results.
// However, all results in a given message will be either final or interim, so just checking
// the first one still works here.
if (!r || !r.results || !r.results.length || r.results[0].final) {
return null;
}
return r;
}
getFinalAndLatestInterimResult() {
const final = this.getFinalResults();
const interim = this.getCurrentInterimResult();
if (interim) {
final.push(interim);
}
return final;
}
handleError(err, extra) {
console.error(err, extra);
if (err.name === 'UNRECOGNIZED_FORMAT') {
err = 'Unable to determine content type from file name or header; mp3, wav, flac, ogg, opus, and webm are supported. Please choose a different file.';
} else if (err.name === 'NotSupportedError' && this.state.audioSource === 'mic') {
err = 'This browser does not support microphone input.';
} else if (err.message === '(\'UpsamplingNotAllowed\', 8000, 16000)') {
err = 'Please select a narrowband voice model to transcribe 8KHz audio files.';
} else if (err.message === 'Invalid constraint') {
// iPod Touch does this on iOS 11 - there is a microphone, but Safari claims there isn't
err = 'Unable to access microphone';
}
this.setState({ error: err.message || err });
}
render() {
const {
token, accessToken, audioSource, error, model, speakerLabels, settingsAtStreamStart,
formattedMessages, rawMessages,
} = this.state;
const buttonsEnabled = !!token || !!accessToken;
const buttonClass = buttonsEnabled
? 'base--button'
: 'base--button base--button_black';
let micIconFill = '#000000';
let micButtonClass = buttonClass;
if (audioSource === 'mic') {
micButtonClass += ' mic-active';
micIconFill = '#FFFFFF';
} else if (!recognizeMicrophone.isSupported) {
micButtonClass += ' base--button_black';
}
const err = error
? (
<Alert type="error" color="red">
<p className="base--p">
{error}
</p>
</Alert>
)
: null;
const messages = this.getFinalAndLatestInterimResult();
const micBullet = (typeof window !== 'undefined' && recognizeMicrophone.isSupported)
? <li className="base--li">Use your microphone to record audio. For best results, use broadband models for microphone input.</li>
: <li className="base--li base--p_light">Use your microphone to record audio. (Not supported in current browser)</li>;// eslint-disable-line
return (
<Dropzone
onDropAccepted={this.handleUserFile}
onDropRejected={this.handleUserFileRejection}
maxSize={200 * 1024 * 1024}
accept="audio/wav, audio/mp3, audio/mpeg, audio/l16, audio/ogg, audio/flac, .mp3, .mpeg, .wav, .ogg, .opus, .flac" // eslint-disable-line
disableClick
className="dropzone _container _container_large"
activeClassName="dropzone-active"
rejectClassName="dropzone-reject"
ref={(node) => {
this.dropzone = node;
}}
>
<div className="drop-info-container">
<div className="drop-info">
<h1>Drop an audio file here.</h1>
<p>Watson Speech to Text supports .mp3, .mpeg, .wav, .opus, and
.flac files up to 200mb.
</p>
</div>
</div>
<div className="new_demo_notification">
<Alert type="info" color="blue">
{NEW_DEMO_NOTIFICATION}
<a href="https://www.ibm.com/demos/live/speech-to-text/self-service/home" target="blank">
here.
</a>
</Alert>
</div>
<h2 className="base--h2">Transcribe Audio</h2>
<ul className="base--ul">
{micBullet}
<li className="base--li">Upload pre-recorded audio (.mp3, .mpeg, .wav, .flac, or .opus only).</li>
<li className="base--li">Play one of the sample audio files.*</li>
</ul>
<div className="smalltext">
*Both US English broadband sample audio files are covered under the
Creative Commons license.
</div>
<div style={{
paddingRight: '3em',
paddingBottom: '2em',
}}
>
The returned result includes the recognized text, {' '}
<a className="base--a" href="https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#word_alternatives">word alternatives</a>, {' '}
and <a className="base--a" href="https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting">spotted keywords</a>. {' '}
Some models can <a className="base--a" href="https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels">detect multiple speakers</a>; this may slow down performance.
</div>
<div className="flex setup">
<div className="column">
<p>Voice Model:
<ModelDropdown
model={model}
token={token || accessToken}
onChange={this.handleModelChange}
/>
</p>
<p className={this.supportsSpeakerLabels() ? 'base--p' : 'base--p_light'}>
<input
className="base--checkbox"
type="checkbox"
checked={speakerLabels}
onChange={this.handleSpeakerLabelsChange}
disabled={!this.supportsSpeakerLabels()}
id="speaker-labels"
/>
<label className="base--inline-label" htmlFor="speaker-labels">
Detect multiple speakers {this.supportsSpeakerLabels() ? '' : ' (Not supported on current model)'}
</label>
</p>
</div>
<div className="column">
<p>Keywords to spot: <input
value={this.getKeywordsArrUnique().join()}
onChange={this.handleKeywordsChange}
type="text"
id="keywords"
placeholder="Type comma separated keywords here (optional)"
className="base--input"
/>
</p>
</div>
</div>
<div className="flex buttons">
<button type="button" className={micButtonClass} onClick={this.handleMicClick}>
<Icon type={audioSource === 'mic' ? 'stop' : 'microphone'} fill={micIconFill} /> Record Audio
</button>
<button type="button" className={buttonClass} onClick={this.handleUploadClick}>
<Icon type={audioSource === 'upload' ? 'stop' : 'upload'} /> Upload Audio File
</button>
<button type="button" className={buttonClass} onClick={this.handleSample1Click}>
<Icon type={audioSource === 'sample-1' ? 'stop' : 'play'} /> Play Sample 1
</button>
<button type="button" className={buttonClass} onClick={this.handleSample2Click}>
<Icon type={audioSource === 'sample-2' ? 'stop' : 'play'} /> Play Sample 2
</button>
</div>
{err}
<Tabs selected={0}>
<Pane label="Text">
{settingsAtStreamStart.speakerLabels
? <SpeakersView messages={messages} />
: <Transcript messages={messages} />}
</Pane>
<Pane label="Word Timings and Alternatives">
<TimingView messages={messages} />
</Pane>
<Pane label={`Keywords ${getKeywordsSummary(settingsAtStreamStart.keywords, messages)}`}>
<Keywords
messages={messages}
keywords={settingsAtStreamStart.keywords}
isInProgress={!!audioSource}
/>
</Pane>
<Pane label="JSON">
<JSONView raw={rawMessages} formatted={formattedMessages} />
</Pane>
</Tabs>
</Dropzone>
);
}
};
export default Demo;