This repository was archived by the owner on May 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSpokestackModule.kt
More file actions
460 lines (418 loc) · 15.4 KB
/
Copy pathSpokestackModule.kt
File metadata and controls
460 lines (418 loc) · 15.4 KB
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
package com.reactnativespokestack
import android.net.Uri
import android.util.Log
import com.facebook.react.bridge.*
import com.facebook.react.modules.core.DeviceEventManagerModule
import io.spokestack.spokestack.PipelineProfile
import io.spokestack.spokestack.Spokestack
import io.spokestack.spokestack.profile.*
import io.spokestack.spokestack.tts.AudioResponse
import io.spokestack.spokestack.tts.SpokestackTTSOutput
import io.spokestack.spokestack.tts.SynthesisRequest
import kotlinx.coroutines.*
import java.util.*
import javax.annotation.Nullable
class SpokestackModule(private val reactContext: ReactApplicationContext): ReactContextBaseJavaModule(reactContext) {
private val adapter = SpokestackAdapter { event: String, data: WritableMap -> sendEvent(event, data) }
private var spokestack: Spokestack? = null
private var audioPlayer: SpokestackTTSOutput? = null
private var downloader: Downloader? = null
private val promises = mutableMapOf<SpokestackPromise, Promise>()
private var say: ((url: String) -> Unit)? = null
private val filenameToProp = mapOf(
"detect.tflite" to "wake-detect-path",
"encode.tflite" to "wake-encode-path",
"filter.tflite" to "wake-filter-path",
"nlu.tflite" to "nlu-model-path",
"metadata.json" to "nlu-metadata-path",
"vocab.txt" to "wordpiece-vocab-path",
"keyword_detect.tflite" to "keyword-detect-path",
"keyword_encode.tflite" to "keyword-encode-path",
"keyword_filter.tflite" to "keyword-filter-path",
"keyword_metadata.json" to "keyword-metadata-path"
)
private val propToFilename = filenameToProp.entries.associateBy({ it.value }, { it.key })
override fun getName(): String {
return "Spokestack"
}
override fun onCatalystInstanceDestroy() {
super.onCatalystInstanceDestroy()
if (started()) {
spokestack?.stop()
}
}
private enum class SpokestackPromise {
SYNTHESIZE,
SPEAK,
CLASSIFY
}
private enum class PipelineProfiles(p:Class<out PipelineProfile>) {
TFLiteWakewordNativeASR(TFWakewordAndroidASR::class.java),
VADNativeASR(VADTriggerAndroidASR::class.java),
PTTNativeASR(PushToTalkAndroidASR::class.java),
TFLiteWakewordSpokestackASR(TFWakewordSpokestackASR::class.java),
VADSpokestackASR(VADTriggerSpokestackASR::class.java),
PTTSpokestackASR(PushToTalkSpokestackASR::class.java),
TFLiteWakewordKeyword(TFWakewordKeywordASR::class.java),
VADKeywordASR(VADTriggerKeywordASR::class.java);
private val profile:Class<out PipelineProfile> = p
fun value():String {
return this.profile.name
}
}
private fun sendEvent(event: String, @Nullable params: WritableMap) {
if (reactContext.hasActiveCatalystInstance()) {
val eventLower = event.toLowerCase(Locale.ROOT)
when(eventLower) {
"error" -> {
Log.e(name, "Received error event with params: $params")
// Reject all existing promises
for ((key, promise) in promises) {
promise.reject(Exception("Error in Spokestack during ${key.name}."))
}
promises.clear()
}
"synthesize" -> {
val url = params.getString("url")
promises[SpokestackPromise.SYNTHESIZE]?.resolve(url)
promises.remove(SpokestackPromise.SYNTHESIZE)
if (say != null && url != null) {
say!!(url)
say = null
}
}
"classify" -> {
promises[SpokestackPromise.CLASSIFY]?.resolve(params)
promises.remove(SpokestackPromise.CLASSIFY)
}
else -> Log.d(name, "Sending JS event: $eventLower")
}
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(eventLower, params)
}
}
private fun kebabCase(str: String): String {
return str.replace(Regex("([a-z])([A-Z])")) {
m -> "${m.groupValues[1]}-${m.groupValues[2].toLowerCase()}"
}
}
private fun textToSpeech(input: String, format: Int, voice: String) {
if (!initialized()) {
throw Exception("Spokestack must be initialized before synthesizing text")
}
if (format > 2 || format < 0) {
throw Exception("A format of $format is not supported. Please use an int from 0 to 2 (or use the TTSFormat enum). Refer to documentation for further details.")
}
val req = SynthesisRequest.Builder(input)
.withMode(SynthesisRequest.Mode.values()[format])
.withVoice(voice)
.build()
spokestack!!.synthesize(req)
}
private fun initialized(): Boolean {
return spokestack != null
}
private fun started(): Boolean {
return initialized() && spokestack?.speechPipeline?.isRunning!!
}
private fun activated(): Boolean {
return started() && spokestack?.speechPipeline?.context?.isActive ?: false
}
@ReactMethod
fun initialize(clientId: String, clientSecret: String, config: ReadableMap, promise: Promise) = runBlocking(Dispatchers.Default) {
if (initialized()) {
promise.resolve(null)
return@runBlocking
}
if (clientId.isEmpty() || clientSecret.isEmpty()) {
val e = IllegalArgumentException("Client ID and Client Secret are required to initialize Spokestack")
promise.reject(e)
return@runBlocking
}
val builder = Spokestack.Builder()
builder.addListener(adapter)
builder.withAndroidContext(reactContext.applicationContext)
builder.setProperty("spokestack-id", clientId)
builder.setProperty("spokestack-secret", clientSecret)
downloader = Downloader(
reactContext.applicationContext,
if (config.hasKey("allowCellularDownloads")) config.getBoolean("allowCellularDownloads") else false,
if (config.hasKey("refreshModels")) config.getBoolean("refreshModels") else false
)
// Top-level config
if (config.hasKey("traceLevel")) {
val traceLevel = config.getInt("traceLevel")
builder.setProperty("trace-level", traceLevel)
Log.d(name, "Trace level set to: $traceLevel")
} else {
// Set trace-level to NONE by default
builder.setProperty("trace-level", 100)
}
// Wakeword
val wakeDownloads = mutableMapOf<String, String>()
if (config.hasKey("wakeword")) {
val map = config.getMap("wakeword")?.toHashMap()
if (map != null) {
for (key in map.keys) {
// Map JS keys to Android keys
when (key) {
"detect" -> {
wakeDownloads[propToFilename["wake-detect-path"] as String] = map[key] as String
}
"encode" -> {
wakeDownloads[propToFilename["wake-encode-path"] as String] = map[key] as String
}
"filter" -> {
wakeDownloads[propToFilename["wake-filter-path"] as String] = map[key] as String
}
"activeMin" -> builder.setProperty("wake-active-min", map[key])
"activeMax" -> builder.setProperty("wake-active-max", map[key])
"encodeLength" -> builder.setProperty("wake-encode-length", map[key])
"encodeWidth" -> builder.setProperty("wake-encode-width", map[key])
"stateWidth" -> builder.setProperty("wake-state-width", map[key])
"threshold" -> builder.setProperty("wake-threshold", map[key])
else -> builder.setProperty(kebabCase(key), map[key])
}
}
}
}
// Wakeword needs all three config paths
if (wakeDownloads.size == 3) {
Log.d(name, "Building with wakeword.")
downloader!!.downloadAll(wakeDownloads).forEach { (filename, loc) ->
builder.setProperty(filenameToProp[filename], loc)
}
} else {
Log.d(name, "Not enough wakeword config files. Building without wakeword.")
builder.withoutWakeword()
}
// Keyword
val keywordDownloads = mutableMapOf<String, String>()
if (config.hasKey("keyword")) {
val map = config.getMap("keyword")?.toHashMap()
if (map != null) {
for (key in map.keys) {
// Map JS keys to Android keys
when (key) {
"detect" -> {
keywordDownloads[propToFilename["keyword-detect-path"] as String] = map[key] as String
}
"encode" -> {
keywordDownloads[propToFilename["keyword-encode-path"] as String] = map[key] as String
}
"filter" -> {
keywordDownloads[propToFilename["keyword-filter-path"] as String] = map[key] as String
}
"metadata" -> {
keywordDownloads[propToFilename["keyword-metadata-path"] as String] = map[key] as String
}
"classes" -> builder.setProperty("keyword-classes", map[key])
"encodeLength" -> builder.setProperty("keyword-encode-length", map[key])
"encodeWidth" -> builder.setProperty("keyword-encode-width", map[key])
"fftWindowSize" -> builder.setProperty("keyword-fft-window-size", map[key])
"fftWindowType" -> builder.setProperty("keyword-fft-window-type", map[key])
"fftHopLength" -> builder.setProperty("keyword-fft-hop-length", map[key])
"melFrameLength" -> builder.setProperty("keyword-mel-frame-length", map[key])
"melFrameWidth" -> builder.setProperty("keyword-mel-frame-width", map[key])
"preEmphasis" -> builder.setProperty("keyword-pre-emphasis", map[key])
"stateWidth" -> builder.setProperty("keyword-state-width", map[key])
"threshold" -> builder.setProperty("keyword-threshold", map[key])
}
}
}
}
// Keyword at least needs filter, detect, and encode
if (keywordDownloads.size >= 3) {
Log.d(name, "Building with keyword.")
downloader!!.downloadAll(keywordDownloads).forEach { (filename, loc) ->
builder.setProperty(filenameToProp[filename], loc)
}
}
// NLU
val nluDownloads = mutableMapOf<String, String>()
if (config.hasKey("nlu")) {
val map = config.getMap("nlu")?.toHashMap()
if (map != null) {
for (key in map.keys) {
// Map JS keys to Android keys
when (key) {
"model" -> {
nluDownloads[propToFilename["nlu-model-path"] as String] = map[key] as String
}
"metadata" -> {
nluDownloads[propToFilename["nlu-metadata-path"] as String] = map[key] as String
}
"vocab" -> {
nluDownloads[propToFilename["wordpiece-vocab-path"] as String] = map[key] as String
}
"inputLength" -> builder.setProperty("nlu-input-length", map[key])
}
}
}
}
if (nluDownloads.size == 3) {
Log.d(name, "Building with NLU.")
downloader!!.downloadAll(nluDownloads).forEach { (filename, loc) ->
builder.setProperty(filenameToProp[filename], loc)
}
} else {
Log.d(name, "Not enough NLU config files. Building without NLU.")
builder.withoutNlu()
}
// TTS is automatically built and available
builder.withoutAutoPlayback()
// Profile
// Default to PTT
var profile = PipelineProfiles.PTTNativeASR.value()
if (config.hasKey("pipeline")) {
val map = config.getMap("pipeline")?.toHashMap()
if (map != null) {
for (key in map.keys) {
// JS uses camelCase for keys
// Convert to kebab-case
builder.setProperty(kebabCase(key), map[key])
}
if (map.containsKey("profile")) {
profile = PipelineProfiles.values()[(map["profile"] as Double).toInt()].value()
}
}
}
builder.withPipelineProfile(profile)
// Initialize the audio player for speaking
audioPlayer = SpokestackTTSOutput(null)
audioPlayer!!.setAndroidContext(reactContext.applicationContext)
audioPlayer!!.addListener(adapter)
spokestack = builder.build()
promise.resolve(null)
}
@ReactMethod
fun start(promise: Promise) {
if (!initialized()) {
promise.reject(Exception("Call Spokestack.initialize() before starting the speech pipeline."))
return
}
try {
if (!started()) {
spokestack!!.start()
}
if (spokestack!!.speechPipeline.isPaused) {
spokestack!!.resume()
}
promise.resolve(null)
// Send a start event for parity with iOS
val reactEvent = Arguments.createMap()
reactEvent.putString("transcript", "")
sendEvent("start", reactEvent)
} catch (e: Exception) {
promise.reject(e)
}
}
@ReactMethod
fun stop(promise: Promise) {
try {
// Calling stop here is more destructive than we want
// and removes all references to TTS. Use pause instead.
spokestack?.pause()
promise.resolve(null)
// Send a stop event for parity with iOS
val reactEvent = Arguments.createMap()
reactEvent.putString("transcript", "")
sendEvent("stop", reactEvent)
} catch (e: Exception) {
promise.reject(e)
}
}
@ReactMethod
fun activate(promise: Promise) {
if (!initialized()) {
promise.reject(Exception("Call Spokestack.initialize() and then Spokestack.start() to start the speech pipeline before calling Spokestack.activate()."))
return
}
if (!started()) {
promise.reject(Exception("The speech pipeline is not yet running. Call Spokestack.start() before calling Spokestack.activate()."))
return
}
try {
audioPlayer?.stopPlayback()
spokestack?.activate()
promise.resolve(null)
} catch (e: Exception) {
promise.reject(e)
}
}
@ReactMethod
fun deactivate(promise: Promise) {
try {
spokestack?.deactivate()
promise.resolve(null)
} catch (e: Exception) {
promise.reject(e)
}
}
@ReactMethod
fun synthesize(input: String, format: Int, voice: String, promise: Promise) {
promises[SpokestackPromise.SYNTHESIZE] = promise
try {
textToSpeech(input, format, voice)
} catch (e: Exception) {
promise.reject(e)
promises.remove(SpokestackPromise.SYNTHESIZE)
}
}
@ReactMethod
fun speak(input: String, format: Int, voice: String, promise: Promise) {
if (!initialized()) {
promise.reject(Exception("Call Spokestack.initialize() before calling Spokestack.speak()."))
return
}
promises[SpokestackPromise.SPEAK] = promise
say = { url ->
Log.d(name,"Playing audio from URL: $url")
val uri = Uri.parse(url)
val response = AudioResponse(uri)
audioPlayer?.audioReceived(response)
// Resolve RN promise
promise.resolve(null)
promises.remove(SpokestackPromise.SPEAK)
}
try {
textToSpeech(input, format, voice)
} catch (e: Exception) {
promise.reject(e)
promises.remove(SpokestackPromise.SPEAK)
}
}
@ReactMethod
fun classify(utterance:String, promise: Promise) {
if (!initialized()) {
promise.reject(Exception("Call Spokestack.initialize() before calling Spokestack.classify()."))
return
}
promises[SpokestackPromise.CLASSIFY] = promise
spokestack!!.classify(utterance)
}
@ReactMethod
fun isInitialized(promise: Promise) {
promise.resolve(initialized())
}
@ReactMethod
fun isStarted(promise: Promise) {
promise.resolve(started())
}
@ReactMethod
fun isActivated(promise: Promise) {
promise.resolve(activated())
}
@ReactMethod
fun destroy(promise: Promise) {
spokestack?.close()
spokestack?.removeListener(adapter)
spokestack = null
audioPlayer?.close()
audioPlayer?.removeListener(adapter)
audioPlayer = null
downloader = null
promise.resolve(null)
}
}