This repository has been archived by the owner on Mar 15, 2022. It is now read-only.
/
LocalSpeechRecognition.java
363 lines (281 loc) · 11.6 KB
/
LocalSpeechRecognition.java
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
package com.mozilla.speechlibrary;
import android.content.Context;
import android.media.AudioRecord;
import android.os.Process;
import com.github.axet.audiolibrary.encoders.Sound;
import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileReader;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import android.util.Log;
import org.json.JSONObject;
import org.mozilla.deepspeech.libdeepspeech.DeepSpeechModel;
import org.mozilla.deepspeech.libdeepspeech.DeepSpeechStreamingState;
class LocalDSInference implements Runnable {
DeepSpeechModel mModel;
DeepSpeechStreamingState mStreamingState;
MozillaSpeechService mService;
Queue<short[]> mBuffers = new ConcurrentLinkedQueue<short[]>();
boolean stopStream;
static final String _tag = "LocalDSInference";
static boolean keepClips = false;
static boolean useDecoder = true;
static int clipNumber = 0;
FileChannel clipDebug;
String modelRoot;
String tfliteModel;
String LM;
String trie;
String infoJson;
int beamWidth = -1;
float lmAlpha = -1;
float lmBeta = -1;
protected LocalDSInference(MozillaSpeechService aService) {
Log.e(this._tag, "new LocalDSInference()");
modelRoot = aService.getModelPath() + "/" + aService.getLanguageDir();
Log.e(this._tag, "Loading model from " + modelRoot);
this.tfliteModel = this.modelRoot + "/" + LocalSpeechRecognition.kTfLiteModel;
this.LM = this.modelRoot + "/" + LocalSpeechRecognition.kLM;
this.trie = this.modelRoot + "/" + LocalSpeechRecognition.kTrie;
this.infoJson = this.modelRoot + "/" + LocalSpeechRecognition.kInfoJson;
try {
String infoJsonContent = new String();
BufferedReader br = new BufferedReader(new FileReader(this.infoJson));
String line;
while ((line = br.readLine()) != null) {
Log.e(this._tag, "line=" + line);
infoJsonContent += line;
}
br.close();
Log.e(this._tag, "infoJsonContent=" + infoJsonContent);
JSONObject modelParameters = (new JSONObject(infoJsonContent)).getJSONObject("parameters");
this.beamWidth = modelParameters.getInt("beamWidth");
this.lmAlpha = (float)modelParameters.getDouble("lmAlpha");
this.lmBeta = (float)modelParameters.getDouble("lmBeta");
} catch (Exception ex) {
}
Log.e(this._tag, "Read model parameters: beamWidth=" + this.beamWidth);
Log.e(this._tag, "Read model parameters: lmAlpha=" + this.lmAlpha);
Log.e(this._tag, "Read model parameters: lmBeta=" + this.lmBeta);
this.clipNumber += 1;
this.keepClips = (new File(this.modelRoot + "/.keepClips")).exists();
this.useDecoder = !(new File(this.modelRoot + "/.noUseDecoder")).exists();
Log.e(this._tag, "keepClips=" + this.keepClips);
Log.e(this._tag, "useDecoder=" + this.useDecoder);
this.mService = aService;
if (this.mModel == null) {
Log.e(this._tag, "new DeepSpeechModel(\"" + this.tfliteModel + "\")");
this.mModel = new DeepSpeechModel(this.tfliteModel, this.beamWidth);
}
if (this.useDecoder) {
this.mModel.enableDecoderWihLM(this.LM, this.trie, this.lmAlpha, this.lmBeta);
}
if (this.keepClips) {
try {
this.clipDebug = new FileOutputStream(this.modelRoot + "/clip_" + this.clipNumber + ".wav").getChannel();
} catch (Exception ex) {
}
}
this.mStreamingState = this.mModel.createStream();
this.stopStream = false;
}
public void closeModel() {
Log.e(this._tag, "closeModel()");
if (this.mStreamingState != null) {
String _ = this.mModel.finishStream(this.mStreamingState);
}
if (this.mModel != null) {
Log.e(this._tag, "closeModel()");
this.mModel.freeModel();
}
this.mStreamingState = null;
this.mModel = null;
}
public void appendAudio(short[] aBuffer) {
Log.e(this._tag, "appendAudio()");
if (!this.stopStream) {
// Log.e(this._tag, "appendAudio()::add");
this.mBuffers.add(aBuffer);
if (this.keepClips) {
// DEBUG
ByteBuffer myByteBuffer = ByteBuffer.allocate(aBuffer.length * 2);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer();
myShortBuffer.put(aBuffer);
try {
this.clipDebug.write(myByteBuffer);
} catch (Exception ex) {
}
}
}
}
public void endOfStream() {
Log.e(this._tag, "endOfStream()");
this.stopStream = true;
if (this.keepClips) {
try {
this.clipDebug.close();
} catch (Exception ex) {
}
}
}
public void run() {
Log.e(this._tag, "run()");
while ((!this.stopStream) || (this.mBuffers.size() > 0)) {
short[] aBuffer = this.mBuffers.poll();
if (aBuffer == null) {
continue;
}
this.mModel.feedAudioContent(this.mStreamingState, aBuffer, aBuffer.length);
}
Log.e(this._tag, "finishStream()");
mService.notifyListeners(MozillaSpeechService.SpeechState.DECODING, null);
String finalDecoded = this.mModel.finishStream(this.mStreamingState);
Log.e(this._tag, "finalDecoded(" + finalDecoded.length() + ")=" + finalDecoded);
this.mStreamingState = null;
STTResult sttResult = new STTResult(finalDecoded, (float)(1.0));
mService.notifyListeners(MozillaSpeechService.SpeechState.STT_RESULT, sttResult);
}
}
class LocalSpeechRecognition implements Runnable {
Vad mVad;
boolean done;
boolean cancelled;
int mMinimumVoice = 150;
int mMaximumSilence = 500;
int mUpperLimit = 10;
static final int FRAME_SIZE = 80;
int mSampleRate;
int mChannels;
MozillaSpeechService mService;
static final String _tag = "LocalSpeechRecognition";
LocalDSInference mInferer;
Thread mInferenceThread;
public static String kTfLiteModel = "output_graph.tflite";
public static String kLM = "lm.binary";
public static String kTrie = "trie";
public static String kInfoJson = "info.json";
private static Map<String,String> mLanguages = new HashMap<String, String>();
static {
mLanguages.put("en-US", "en-us");
mLanguages.put("fr-FR", "fr-fr");
}
private static String kBaseModelURL = "https://github.com/lissyx/DeepSpeech/releases/download/v0.6.0/";
protected LocalSpeechRecognition(int aSampleRate, int aChannels, Vad aVad,
MozillaSpeechService aService) {
Log.e(this._tag, "new LocalSpeechRecognition()");
this.mVad = aVad;
this.mSampleRate = aSampleRate;
this.mChannels = aChannels;
this.mService = aService;
this.mInferer = new LocalDSInference(this.mService);
this.mInferenceThread = new Thread(this.mInferer);
this.mInferenceThread.start();
}
public void run() {
try {
int vad = 0;
boolean finishedvoice = false;
boolean touchedvoice = false;
boolean touchedsilence = false;
boolean raisenovoice = false;
long samplesvoice = 0 ;
long samplessilence = 0 ;
long dtantes = System.currentTimeMillis();
long dtantesmili = System.currentTimeMillis();
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
AudioRecord recorder = Sound.getAudioRecord(mChannels, mSampleRate);
recorder.startRecording();
mService.notifyListeners(MozillaSpeechService.SpeechState.START_LISTEN, null);
while (!this.done && !this.cancelled) {
int nshorts = 0 ;
short[] mBuftemp = new short[FRAME_SIZE * mChannels * 2];
nshorts = recorder.read(mBuftemp, 0, mBuftemp.length);
vad = mVad.feed(mBuftemp, nshorts);
double[] fft = Sound.fft(mBuftemp, 0, nshorts);
double fftsum = Arrays.stream(fft).sum()/fft.length;
mService.notifyListeners(MozillaSpeechService.SpeechState.MIC_ACTIVITY, fftsum);
long dtdepois = System.currentTimeMillis();
if (vad == 0) {
if (touchedvoice) {
samplessilence += dtdepois - dtantesmili;
if (samplessilence > mMaximumSilence) touchedsilence = true;
}
} else { // vad == 1 => Active voice
samplesvoice += dtdepois - dtantesmili;
if (samplesvoice > mMinimumVoice) touchedvoice = true;
for (int i = 0; i < mBuftemp.length; ++i) {
mBuftemp[i] *= 5.0;
}
}
dtantesmili = dtdepois;
this.mInferer.appendAudio(mBuftemp);
if (touchedvoice && touchedsilence)
finishedvoice = true;
if (finishedvoice) {
this.done = true;
this.mInferer.endOfStream();
}
if ((dtdepois - dtantes)/1000 > mUpperLimit ) {
this.done = true;
if (touchedvoice) {
this.mInferer.endOfStream();
}
else {
raisenovoice = true;
}
}
if (nshorts <= 0)
break;
}
mVad.stop();
recorder.stop();
recorder.release();
if (raisenovoice) mService.notifyListeners(MozillaSpeechService.SpeechState.NO_VOICE, null);
if (cancelled) {
cancelled = false;
mService.notifyListeners(MozillaSpeechService.SpeechState.CANCELED, null);
return;
}
} catch (Exception exc) {
String error = String.format("General audio error %s", exc.getMessage());
mService.notifyListeners(MozillaSpeechService.SpeechState.ERROR, error);
exc.printStackTrace();
}
}
public void cancel() {
Log.e(this._tag, "cancel()");
this.cancelled = true;
this.done = true;
if (this.mInferer != null) {
this.mInferer.closeModel();
}
}
public static String getLanguageDir(String aLanguage) {
String rv = aLanguage;
if (rv.length() != 3) {
if (mLanguages.containsKey(rv)) {
rv = mLanguages.get(rv);
}
}
return rv;
}
public static boolean ensureModelInstalled(String aModelPath) {
Log.e(_tag, "ensureModelInstalled(" + aModelPath + ")");
return (new File(aModelPath + "/" + kTfLiteModel)).exists()
&& (new File(aModelPath + "/" + kLM)).exists()
&& (new File(aModelPath + "/" + kTrie)).exists();
}
public static String getModelDownloadURL(String aLang) {
return kBaseModelURL + aLang + ".zip";
}
}