Skip to content

Commit 0d2dbf1

Browse files
committed
Integrate VAD with STT
1 parent b94d5f8 commit 0d2dbf1

20 files changed

Lines changed: 341 additions & 76 deletions

File tree

‎apps/speech/screens/SpeechToTextScreen.tsx‎

Lines changed: 96 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
WHISPER_SMALL_EN_COREML,
2222
TranscriptionResult,
2323
SpeechToTextProps,
24+
FSMN_VAD,
2425
} from 'react-native-executorch';
2526
import { ModelPicker, ModelOption } from '../components/ModelPicker';
2627

@@ -58,6 +59,7 @@ export const SpeechToTextScreen = ({ onBack }: { onBack: () => void }) => {
5859

5960
const model = useSpeechToText({
6061
model: selectedModel,
62+
vad: FSMN_VAD,
6163
});
6264

6365
const [transcription, setTranscription] =
@@ -72,6 +74,7 @@ export const SpeechToTextScreen = ({ onBack }: { onBack: () => void }) => {
7274
} | null>(null);
7375

7476
const [enableTimestamps, setEnableTimestamps] = useState(false);
77+
const [useVAD, setUseVAD] = useState(true);
7578
const [error, setError] = useState<string | null>(null);
7679
const [audioURL, setAudioURL] = useState('');
7780
const [hasMicPermission, setHasMicPermission] = useState(false);
@@ -185,7 +188,9 @@ export const SpeechToTextScreen = ({ onBack }: { onBack: () => void }) => {
185188
try {
186189
const streamIter = model.stream({
187190
verbose: enableTimestamps,
188-
timeout: 100,
191+
timeout: 200,
192+
useVAD: useVAD,
193+
vadDetectionMargin: 1200,
189194
});
190195

191196
for await (const { committed, nonCommitted } of streamIter) {
@@ -359,22 +364,60 @@ export const SpeechToTextScreen = ({ onBack }: { onBack: () => void }) => {
359364
<Text style={styles.buttonText}> Stop Live Transcription</Text>
360365
</TouchableOpacity>
361366
) : (
362-
<TouchableOpacity
363-
disabled={recordingButtonDisabled}
364-
onPress={handleStartTranscribeFromMicrophone}
365-
style={[
366-
styles.liveTranscriptionButton,
367-
styles.backgroundBlue,
368-
recordingButtonDisabled && styles.disabled,
369-
]}
370-
>
371-
<FontAwesome name="microphone" size={20} color="white" />
372-
<Text style={styles.buttonText}>
373-
{isSimulator
374-
? 'Recording is not available on Simulator'
375-
: 'Start Live Transcription'}
376-
</Text>
377-
</TouchableOpacity>
367+
<View style={styles.buttonRow}>
368+
<TouchableOpacity
369+
disabled={recordingButtonDisabled}
370+
onPress={handleStartTranscribeFromMicrophone}
371+
style={[
372+
styles.liveTranscriptionButton,
373+
styles.backgroundBlue,
374+
styles.flex1,
375+
recordingButtonDisabled && styles.disabled,
376+
]}
377+
>
378+
<FontAwesome name="microphone" size={20} color="white" />
379+
<Text style={styles.buttonText}>
380+
{isSimulator ? 'No Mic' : 'Start Live'}
381+
</Text>
382+
</TouchableOpacity>
383+
384+
<TouchableOpacity
385+
onPress={() => setUseVAD(!useVAD)}
386+
activeOpacity={0.7}
387+
accessibilityRole="switch"
388+
accessibilityState={{ checked: useVAD }}
389+
accessibilityLabel={`Voice Activity Detection ${useVAD ? 'on' : 'off'}`}
390+
style={[
391+
styles.vadButton,
392+
useVAD ? styles.vadActive : styles.vadInactive,
393+
recordingButtonDisabled && styles.disabled,
394+
]}
395+
>
396+
<FontAwesome
397+
name={useVAD ? 'check-circle' : 'circle-o'}
398+
size={18}
399+
color={useVAD ? '#ffffff' : '#94a3b8'}
400+
/>
401+
<View style={styles.vadTextContainer}>
402+
<Text
403+
style={[
404+
styles.vadButtonLabel,
405+
{ color: useVAD ? 'white' : '#64748b' },
406+
]}
407+
>
408+
VAD
409+
</Text>
410+
<Text
411+
style={[
412+
styles.vadButtonState,
413+
{ color: useVAD ? '#bbf7d0' : '#94a3b8' },
414+
]}
415+
>
416+
{useVAD ? 'ON' : 'OFF'}
417+
</Text>
418+
</View>
419+
</TouchableOpacity>
420+
</View>
378421
)}
379422
</View>
380423
</KeyboardAvoidingView>
@@ -498,6 +541,42 @@ const styles = StyleSheet.create({
498541
backgroundBlue: {
499542
backgroundColor: '#0f186e',
500543
},
544+
buttonRow: {
545+
flexDirection: 'row',
546+
gap: 8,
547+
marginTop: 12,
548+
},
549+
flex1: {
550+
flex: 1,
551+
marginTop: 0,
552+
},
553+
vadButton: {
554+
flexDirection: 'row',
555+
alignItems: 'center',
556+
justifyContent: 'center',
557+
paddingHorizontal: 14,
558+
borderRadius: 12,
559+
gap: 10,
560+
},
561+
vadActive: {
562+
backgroundColor: '#0f186e',
563+
},
564+
vadInactive: {
565+
backgroundColor: '#f1f5f9',
566+
},
567+
vadTextContainer: {
568+
alignItems: 'flex-start',
569+
},
570+
vadButtonLabel: {
571+
fontWeight: '800',
572+
fontSize: 13,
573+
letterSpacing: 0.5,
574+
},
575+
vadButtonState: {
576+
fontWeight: '700',
577+
fontSize: 10,
578+
letterSpacing: 1,
579+
},
501580
disabled: {
502581
opacity: 0.5,
503582
},

‎packages/react-native-executorch/common/rnexecutorch/models/speech_to_text/SpeechToText.cpp‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,20 @@ namespace rnexecutorch::models::speech_to_text {
1212
SpeechToText::SpeechToText(const std::string &modelName,
1313
const std::string &modelSource,
1414
const std::string &tokenizerSource,
15+
const std::string &vadSource,
1516
std::shared_ptr<react::CallInvoker> callInvoker)
1617
: callInvoker_(std::move(callInvoker)) {
1718
// Switch between the ASR implementations based on model name
1819
if (modelName == "whisper") {
20+
if (!vadSource.empty()) {
21+
vad_ = std::make_unique<VoiceActivityDetection>(vadSource, callInvoker_);
22+
}
23+
1924
transcriber_ = std::make_unique<whisper::ASR>(modelSource, tokenizerSource,
2025
callInvoker_);
2126
streamer_ = std::make_unique<whisper::stream::OnlineASR>(
22-
static_cast<const whisper::ASR *>(transcriber_.get()));
27+
static_cast<const whisper::ASR *>(transcriber_.get()),
28+
static_cast<const VoiceActivityDetection *>(vad_.get()));
2329
} else {
2430
throw rnexecutorch::RnExecutorchError(
2531
rnexecutorch::RnExecutorchErrorCode::InvalidConfig,
@@ -116,12 +122,19 @@ TranscriptionResult wordsToResult(const std::vector<Word> &words,
116122

117123
void SpeechToText::stream(std::shared_ptr<jsi::Function> callback,
118124
std::string languageOption, bool verbose,
119-
uint32_t timeout) {
125+
uint32_t timeout, bool useVAD,
126+
uint32_t vadDetectionMargin) {
120127
if (isStreaming_) {
121128
throw RnExecutorchError(RnExecutorchErrorCode::StreamingInProgress,
122129
"Streaming is already in progress!");
123130
}
124131

132+
// VAD must be initialized for this option to work.
133+
if (useVAD && !vad_) {
134+
throw RnExecutorchError(RnExecutorchErrorCode::ModuleNotLoaded,
135+
"Attempting to use VAD but it's not initialized!");
136+
}
137+
125138
auto nativeCallback =
126139
[this, callback](const TranscriptionResult &committed,
127140
const TranscriptionResult &nonCommitted, bool isDone) {
@@ -139,18 +152,24 @@ void SpeechToText::stream(std::shared_ptr<jsi::Function> callback,
139152
};
140153

141154
isStreaming_ = true;
142-
DecodingOptions options(languageOption, verbose);
155+
StreamingOptions options(languageOption, verbose, useVAD, vadDetectionMargin);
143156

144157
while (isStreaming_) {
145158
if (readyToProcess_ && streamer_->isReady()) {
146159
ProcessResult res = streamer_->process(options);
147160

148-
TranscriptionResult committedRes =
149-
wordsToResult(res.committed, languageOption, verbose);
150-
TranscriptionResult nonCommittedRes =
151-
wordsToResult(res.nonCommitted, languageOption, verbose);
161+
// This is not only about optimization, but also about ensuring
162+
// correctness when VAD is used. Otherwise we run into the vanishing text
163+
// issue.
164+
if (!res.committed.empty() || !res.nonCommitted.empty()) {
165+
TranscriptionResult committedRes =
166+
wordsToResult(res.committed, languageOption, verbose);
167+
TranscriptionResult nonCommittedRes =
168+
wordsToResult(res.nonCommitted, languageOption, verbose);
169+
170+
nativeCallback(committedRes, nonCommittedRes, false);
171+
}
152172

153-
nativeCallback(committedRes, nonCommittedRes, false);
154173
readyToProcess_ = false;
155174
}
156175

@@ -166,6 +185,9 @@ void SpeechToText::stream(std::shared_ptr<jsi::Function> callback,
166185
[this] { return !isStreaming_.load(); });
167186
}
168187

188+
// Do not use VAD on final processing to flush and commit everything properly.
189+
options.useVAD = false;
190+
169191
std::vector<Word> finalWords = streamer_->finish(options);
170192
TranscriptionResult finalRes =
171193
wordsToResult(finalWords, languageOption, verbose);

‎packages/react-native-executorch/common/rnexecutorch/models/speech_to_text/SpeechToText.h‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,18 @@
1010
#include "common/schema/ASR.h"
1111
#include "common/schema/OnlineASR.h"
1212
#include "common/types/TranscriptionResult.h"
13+
#include <rnexecutorch/models/voice_activity_detection/VoiceActivityDetection.h>
1314

1415
namespace rnexecutorch {
1516

1617
namespace models::speech_to_text {
1718

19+
using voice_activity_detection::VoiceActivityDetection;
20+
1821
class SpeechToText {
1922
public:
2023
SpeechToText(const std::string &modelName, const std::string &modelSource,
21-
const std::string &tokenizerSource,
24+
const std::string &tokenizerSource, const std::string &vadSource,
2225
std::shared_ptr<react::CallInvoker> callInvoker);
2326

2427
// Required because of std::atomic usage
@@ -40,7 +43,8 @@ class SpeechToText {
4043

4144
// Stream
4245
void stream(std::shared_ptr<jsi::Function> callback,
43-
std::string languageOption, bool verbose, uint32_t timeout);
46+
std::string languageOption, bool verbose,
47+
uint32_t timeout, bool useVAD, uint32_t vadDetectionMargin);
4448
void streamStop();
4549
void streamInsert(std::span<float> waveform);
4650

@@ -61,12 +65,15 @@ class SpeechToText {
6165
// waiting for the next throttling interval to expire.
6266
std::mutex streamCvMutex_;
6367
std::condition_variable streamCv_;
68+
69+
// VAD submodule
70+
std::unique_ptr<VoiceActivityDetection> vad_ = nullptr;
6471
};
6572

6673
} // namespace models::speech_to_text
6774

6875
REGISTER_CONSTRUCTOR(models::speech_to_text::SpeechToText, std::string,
69-
std::string, std::string,
76+
std::string, std::string, std::string,
7077
std::shared_ptr<react::CallInvoker>);
7178

7279
} // namespace rnexecutorch

‎packages/react-native-executorch/common/rnexecutorch/models/speech_to_text/common/schema/ASR.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
#include <span>
55
#include <vector>
66

7-
#include "../types/DecodingOptions.h"
7+
#include "../types/Options.h"
88
#include "../types/Segment.h"
99
#include <rnexecutorch/models/BaseModel.h>
1010

‎packages/react-native-executorch/common/rnexecutorch/models/speech_to_text/common/schema/OnlineASR.h‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#include <span>
44
#include <vector>
55

6-
#include "../types/DecodingOptions.h"
6+
#include "../types/Options.h"
77
#include "../types/ProcessResult.h"
88
#include "../types/Word.h"
99

@@ -34,9 +34,9 @@ class OnlineASR {
3434

3535
virtual bool isReady() const = 0;
3636

37-
virtual ProcessResult process(const DecodingOptions &options) = 0;
37+
virtual ProcessResult process(const StreamingOptions &options) = 0;
3838

39-
virtual std::vector<Word> finish(const DecodingOptions &options) = 0;
39+
virtual std::vector<Word> finish(const StreamingOptions &options) = 0;
4040

4141
virtual void reset() = 0;
4242
};

‎packages/react-native-executorch/common/rnexecutorch/models/speech_to_text/common/types/DecodingOptions.h‎

Lines changed: 0 additions & 17 deletions
This file was deleted.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#pragma once
2+
3+
#include <optional>
4+
#include <string>
5+
6+
namespace rnexecutorch::models::speech_to_text {
7+
8+
struct DecodingOptions {
9+
DecodingOptions(const std::string &language, bool verbose = false)
10+
: language(language.empty() ? std::nullopt : std::optional(language)),
11+
verbose(verbose) {}
12+
13+
std::optional<std::string> language;
14+
bool verbose;
15+
};
16+
17+
struct StreamingOptions : public DecodingOptions {
18+
StreamingOptions(const std::string &language, bool verbose = false,
19+
bool useVAD = false, uint32_t vadDetectionMargin = 500)
20+
: DecodingOptions(language, verbose), useVAD(useVAD),
21+
vadDetectionMargin(vadDetectionMargin) {}
22+
23+
bool useVAD;
24+
uint32_t vadDetectionMargin;
25+
};
26+
27+
} // namespace rnexecutorch::models::speech_to_text

0 commit comments

Comments
 (0)