-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathRealtimeTranscriber.tsx
More file actions
977 lines (893 loc) · 31.5 KB
/
Copy pathRealtimeTranscriber.tsx
File metadata and controls
977 lines (893 loc) · 31.5 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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
/* eslint-disable react/jsx-one-expression-per-line */
/* eslint-disable no-use-before-define */
import React, { useCallback, useEffect, useRef, useState } from 'react'
import {
StyleSheet,
ScrollView,
View,
Text,
Platform,
PermissionsAndroid,
Alert,
Switch,
} from 'react-native'
import RNFS from 'react-native-fs'
import { initWhisper, initWhisperVad, libVersion } from '../../src'
import type { WhisperContext, WhisperVadContext } from '../../src'
import { Button } from './Button'
import contextOpts from './context-opts'
import { createDir, fileDir, toTimestamp, downloadModel, whisperModels, WhisperModel } from './util'
import {
RealtimeTranscriber,
RingBufferVad,
VAD_PRESETS,
type RealtimeTranscribeEvent,
type RealtimeVadEvent,
type RealtimeStatsEvent,
type AudioStreamInterface,
} from '../../src/realtime-transcription'
import { SimulateFileAudioStreamAdapter } from '../../src/realtime-transcription/adapters/SimulateFileAudioStreamAdapter'
import { AudioPcmStreamAdapter } from '../../src/realtime-transcription/adapters/AudioPcmStreamAdapter'
if (Platform.OS === 'android') {
// Request record audio permission
// @ts-ignore
PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, {
title: 'Whisper Audio Permission',
message: 'Whisper needs access to your microphone',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
})
}
const styles = StyleSheet.create({
scrollview: { flexGrow: 1, justifyContent: 'center' },
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 4,
},
buttons: { flexDirection: 'row', flexWrap: 'wrap' },
button: { margin: 4, backgroundColor: '#333', borderRadius: 4, padding: 8 },
buttonClear: { backgroundColor: '#888' },
buttonActive: { backgroundColor: '#4CAF50' },
buttonDanger: { backgroundColor: '#f44336' },
buttonText: { fontSize: 14, color: 'white', textAlign: 'center' },
logContainer: {
backgroundColor: 'lightgray',
padding: 8,
width: '95%',
borderRadius: 8,
marginVertical: 8,
},
logText: { fontSize: 12, color: '#333' },
configContainer: {
backgroundColor: '#f0f0f0',
padding: 12,
width: '95%',
borderRadius: 8,
marginVertical: 4,
},
configTitle: { fontSize: 16, fontWeight: 'bold', marginBottom: 8 },
configRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginVertical: 4,
},
configLabel: { fontSize: 14, color: '#666' },
configValue: { fontSize: 14, fontWeight: '500' },
playbackContainer: {
backgroundColor: '#fff3cd',
padding: 12,
width: '95%',
borderRadius: 8,
marginVertical: 4,
},
playbackCompleted: {
backgroundColor: '#d4edda',
},
playbackTitle: { fontSize: 16, fontWeight: 'bold', marginBottom: 8 },
progressBar: {
height: 4,
backgroundColor: '#ddd',
borderRadius: 2,
marginVertical: 8,
},
progressFill: {
height: '100%',
backgroundColor: '#007bff',
borderRadius: 2,
},
statusContainer: {
backgroundColor: '#e8f5e8',
padding: 8,
width: '95%',
borderRadius: 8,
marginVertical: 4,
},
statusActive: { backgroundColor: '#e8f5e8' },
statusInactive: { backgroundColor: '#f5e8e8' },
statusText: { fontSize: 12, color: '#333' },
})
const mode = process.env.NODE_ENV === 'development' ? 'debug' : 'release'
// JFK audio file URL from whisper.cpp repository
const JFK_AUDIO_URL =
'https://github.com/ggml-org/whisper.cpp/raw/refs/heads/master/samples/jfk.wav'
export default function RealtimeTranscriberDemo() {
const whisperContextRef = useRef<WhisperContext | null>(null)
const vadContextRef = useRef<WhisperVadContext | null>(null)
const realtimeTranscriberRef = useRef<RealtimeTranscriber | null>(null)
const audioStreamRef = useRef<AudioStreamInterface | null>(null)
const [logs, setLogs] = useState([
`Realtime Transcriber Demo - whisper.cpp v${libVersion}`,
])
const [transcribeResult, setTranscribeResult] = useState<string | null>(null)
const [currentVadPreset, setCurrentVadPreset] =
useState<keyof typeof VAD_PRESETS>('default')
const [isTranscribing, setIsTranscribing] = useState(false)
const [realtimeStats, setRealtimeStats] = useState<any>(null)
const [vadEvents, setVadEvents] = useState<RealtimeVadEvent[]>([])
const [stabilizedText, setStabilizedText] = useState<string>('')
// File simulation specific state
const [useFileSimulation, setUseFileSimulation] = useState(false)
const [playbackSpeed, setPlaybackSpeed] = useState(1.0)
const [simulationStats, setSimulationStats] = useState<any>(null)
const [audioFilePath, setAudioFilePath] = useState<string | null>(null)
const [isDownloading, setIsDownloading] = useState(false)
const [downloadProgress, setDownloadProgress] = useState(0)
const [selectedModel, setSelectedModel] = useState<WhisperModel>('base')
const [modelDownloadProgress, setModelDownloadProgress] = useState<number>(0)
const log = useCallback((...messages: any[]) => {
setLogs((prev) => [
...prev,
`${new Date().toLocaleTimeString()}: ${messages.join(' ')}`,
])
}, [])
useEffect(
() => () => {
// Cleanup on unmount
whisperContextRef.current?.release()
vadContextRef.current?.release()
realtimeTranscriberRef.current?.release()
},
[],
)
// Update simulation stats periodically when using file simulation
useEffect(() => {
if (!useFileSimulation || !audioStreamRef.current) {
return undefined
}
const interval = setInterval(() => {
if (audioStreamRef.current && 'getStatistics' in audioStreamRef.current) {
const stats = (audioStreamRef.current as any).getStatistics()
setSimulationStats(stats)
}
}, 500) // Update every 500ms
return () => clearInterval(interval)
}, [useFileSimulation, isTranscribing])
const downloadAudioFile = async () => {
setIsDownloading(true)
setDownloadProgress(0)
try {
const downloadPath = `${fileDir}/jfk-sample.wav`
// Check if file already exists
const exists = await RNFS.exists(downloadPath)
if (exists) {
log('Audio file already exists, using cached version')
setAudioFilePath(downloadPath)
setIsDownloading(false)
return downloadPath
}
log('Downloading JFK audio sample from whisper.cpp repository...')
const downloadResult = await RNFS.downloadFile({
fromUrl: JFK_AUDIO_URL,
toFile: downloadPath,
progress: (res) => {
const progress = (res.bytesWritten / res.contentLength) * 100
setDownloadProgress(progress)
log(`Download progress: ${progress.toFixed(1)}%`)
},
}).promise
if (downloadResult.statusCode === 200) {
log('Audio file downloaded successfully')
setAudioFilePath(downloadPath)
setIsDownloading(false)
setDownloadProgress(100)
return downloadPath
} else {
throw new Error(
`Download failed with status: ${downloadResult.statusCode}`,
)
}
} catch (error) {
log('Error downloading audio file:', error)
setIsDownloading(false)
setDownloadProgress(0)
Alert.alert('Download Error', `Failed to download audio file: ${error}`)
throw error
}
}
const initializeContextsWithAsset = async () => {
try {
if (whisperContextRef.current) {
log('Found previous Whisper context')
await whisperContextRef.current.release()
whisperContextRef.current = null
log('Released previous Whisper context')
}
if (vadContextRef.current) {
log('Found previous VAD context')
await vadContextRef.current.release()
vadContextRef.current = null
log('Released previous VAD context')
}
log('Initializing Whisper context...')
const startTime = Date.now()
const whisperCtx = await initWhisper({
filePath: require('../assets/ggml-base.bin'),
...contextOpts,
})
const endTime = Date.now()
log('Loaded Whisper model, ID:', whisperCtx.id)
log('Loaded Whisper model in', endTime - startTime, `ms in ${mode} mode`)
whisperContextRef.current = whisperCtx
log('Initializing VAD context...')
const vadStartTime = Date.now()
const vadCtx = await initWhisperVad({
filePath: require('../assets/ggml-silero-v6.2.0.bin'),
useGpu: true,
nThreads: 4,
})
const vadEndTime = Date.now()
log('Loaded VAD model, ID:', vadCtx.id)
log(
'Loaded VAD model in',
vadEndTime - vadStartTime,
`ms in ${mode} mode`,
)
vadContextRef.current = vadCtx
log('Both contexts initialized successfully!')
} catch (error) {
log('Error initializing contexts:', error)
Alert.alert('Error', `Failed to initialize: ${error}`)
}
}
const initializeContextsWithDownload = async () => {
try {
if (whisperContextRef.current) {
log('Found previous Whisper context')
await whisperContextRef.current.release()
whisperContextRef.current = null
log('Released previous Whisper context')
}
if (vadContextRef.current) {
log('Found previous VAD context')
await vadContextRef.current.release()
vadContextRef.current = null
log('Released previous VAD context')
}
const modelFilePath = await downloadModel(
selectedModel,
(progress) => {
setModelDownloadProgress(progress)
log(`Download progress: ${Math.round(progress * 100)}%`)
},
log
)
log('Initializing Whisper context...')
const startTime = Date.now()
const whisperCtx = await initWhisper({ filePath: modelFilePath })
const endTime = Date.now()
log('Loaded Whisper model, ID:', whisperCtx.id)
log('Loaded Whisper model in', endTime - startTime, `ms in ${mode} mode`)
whisperContextRef.current = whisperCtx
setModelDownloadProgress(0)
log('Initializing VAD context...')
const vadStartTime = Date.now()
const vadCtx = await initWhisperVad({
filePath: require('../assets/ggml-silero-v6.2.0.bin'),
useGpu: true,
nThreads: 4,
})
const vadEndTime = Date.now()
log('Loaded VAD model, ID:', vadCtx.id)
log(
'Loaded VAD model in',
vadEndTime - vadStartTime,
`ms in ${mode} mode`,
)
vadContextRef.current = vadCtx
log('Both contexts initialized successfully!')
} catch (error) {
log('Error initializing contexts:', error)
setModelDownloadProgress(0)
Alert.alert('Error', `Failed to initialize: ${error}`)
}
}
const startRealtimeTranscription = async () => {
if (!whisperContextRef.current || !vadContextRef.current) {
Alert.alert('Error', 'Contexts not initialized')
return
}
try {
await createDir(log)
// Create appropriate audio stream adapter
let audioStream: AudioStreamInterface
if (useFileSimulation) {
log('Creating file simulation adapter...')
// Download audio file if needed
try {
audioStream = new SimulateFileAudioStreamAdapter({
fs: RNFS,
filePath: audioFilePath!,
playbackSpeed,
chunkDurationMs: 100,
loop: false,
onEndOfFile: () => {
log('File simulation reached end - no new buffer available')
log('Automatically stopping realtime transcription...')
// Automatically stop realtime transcription when file ends
setTimeout(() => {
stopRealtimeTranscription()
}, 1000) // Small delay to allow final processing
},
logger: (message) => console.log(message),
})
} catch (error) {
log('Failed to download audio file for simulation')
Alert.alert(
'Error',
'Could not download audio file for simulation. Please check your internet connection and try again.',
)
return
}
} else {
log('Creating live audio adapter...')
audioStream = new AudioPcmStreamAdapter()
}
audioStreamRef.current = audioStream
if (realtimeTranscriberRef.current) {
realtimeTranscriberRef.current.release()
}
// Create RingBufferVad wrapper
const vadContext = new RingBufferVad(vadContextRef.current, {
vadOptions: VAD_PRESETS[currentVadPreset],
vadPreset: currentVadPreset,
logger: (message) => log(message),
})
// Create RealtimeTranscriber if not exists
const transcriber = new RealtimeTranscriber(
// Dependencies
{
whisperContext: whisperContextRef.current,
vadContext,
audioStream,
fs: RNFS,
},
// Options
{
logger: (message) => log(message),
audioSliceSec: 30,
audioMinSec: 0.5,
maxSlicesInMemory: 1,
transcribeOptions: {
language: 'en',
maxLen: 1,
},
audioOutputPath: `${fileDir}/realtime-recording.wav`,
},
// Callbacks
{
onTranscribe: handleTranscribeEvent,
onVad: handleVadEvent,
onError: handleError,
onStatusChange: handleStatusChange,
onStatsUpdate: handleStatsUpdate,
onSliceTranscriptionStabilized: (text: string) => {
setStabilizedText(text)
log(`Stabilized: "${text.substring(0, 50)}${text.length > 50 ? '...' : ''}"`)
},
},
)
realtimeTranscriberRef.current = transcriber
// Start transcription
await realtimeTranscriberRef.current.start()
log(
`Realtime transcription started (${useFileSimulation ? 'File Simulation - JFK Speech' : 'Live Audio'
})`,
)
} catch (error) {
log('Error starting realtime transcription:', error)
Alert.alert('Error', `Failed to start: ${error}`)
}
}
const stopRealtimeTranscription = async () => {
if (!realtimeTranscriberRef.current) {
return
}
try {
await realtimeTranscriberRef.current.stop()
setRealtimeStats(null)
setSimulationStats(null)
log('Realtime transcription stopped')
} catch (error) {
log('Error stopping realtime transcription:', error)
}
}
const handleTranscribeEvent = (event: RealtimeTranscribeEvent) => {
const { data, sliceIndex } = event
if (data?.result) {
// Get all transcription results from the transcriber
const allResults =
realtimeTranscriberRef.current?.getTranscriptionResults() || []
if (allResults.length > 0) {
const separator = `\n\n${'='.repeat(50)}\n\n`
const formattedResults = allResults
.map(({ slice, transcribeEvent }) => {
const { data: resultData, processTime: procTime } = transcribeEvent
if (!resultData) return null
return (
`[Slice ${slice.index}] ${resultData.result}\n` +
`Process Time: ${procTime}ms | Duration: ${(
(slice.endTime - slice.startTime) /
1000
).toFixed(1)}s\n` +
`Memory: ${transcribeEvent.memoryUsage?.slicesInMemory || 0
} slices, ${transcribeEvent.memoryUsage?.estimatedMB || 0}MB\n` +
`Segments:\n${resultData.segments
.map(
(segment) =>
` [${toTimestamp(segment.t0)} --> ${toTimestamp(
segment.t1,
)}] ${segment.text}`,
)
.join('\n')}`
)
})
.filter((result): result is string => result !== null)
.join(separator)
setTranscribeResult(formattedResults)
}
log(
`Transcribed slice ${sliceIndex}: "${data.result.substring(
0,
50,
)}..." (Total results: ${allResults.length})`,
)
}
}
const handleVadEvent = (vadEvent: RealtimeVadEvent) => {
setVadEvents((prev) => [...prev.slice(-19), vadEvent]) // Keep last 20 events
if (vadEvent.type !== 'silence') {
log(
`VAD: ${vadEvent.type} (confidence: ${vadEvent.confidence.toFixed(2)})`,
)
}
}
const handleStatsUpdate = (statsEvent: RealtimeStatsEvent) => {
setRealtimeStats(statsEvent.data)
// Log significant changes
if (statsEvent.type === 'status_change') {
log(
`Status changed: ${statsEvent.data.isActive ? 'ACTIVE' : 'INACTIVE'
}, transcribing: ${statsEvent.data.isTranscribing}`,
)
} else if (statsEvent.type === 'memory_change') {
const memMB = statsEvent.data.sliceStats?.memoryUsage?.estimatedMB || 0
log(`Memory usage: ${memMB.toFixed(1)}MB`)
}
}
const handleError = (error: string) => {
log('Realtime Error:', error)
}
const handleStatusChange = (isActive: boolean) => {
setIsTranscribing(isActive)
log(`Realtime status: ${isActive ? 'ACTIVE' : 'INACTIVE'}`)
}
const changeVadPreset = () => {
const presetKeys = Object.keys(VAD_PRESETS) as Array<
keyof typeof VAD_PRESETS
>
const currentIndex = presetKeys.indexOf(currentVadPreset)
const nextIndex = (currentIndex + 1) % presetKeys.length
const nextPreset = presetKeys[nextIndex] as keyof typeof VAD_PRESETS
setCurrentVadPreset(nextPreset)
log(`VAD preset changed to: ${nextPreset}`)
// Update transcriber if active
if (realtimeTranscriberRef.current) {
realtimeTranscriberRef.current.updateVadOptions(VAD_PRESETS[nextPreset])
}
}
const changePlaybackSpeed = () => {
const speeds = [0.5, 1.0, 1.5, 2.0]
const currentIndex = speeds.indexOf(playbackSpeed)
const nextIndex = (currentIndex + 1) % speeds.length
const nextSpeed = speeds[nextIndex] || 1.0
setPlaybackSpeed(nextSpeed)
log(`Playback speed changed to: ${nextSpeed}x`)
// Update adapter if active and using file simulation
if (
audioStreamRef.current &&
'setPlaybackSpeed' in audioStreamRef.current
) {
; (audioStreamRef.current as any).setPlaybackSpeed(nextSpeed)
}
}
const seekToPosition = (percentage: number) => {
if (
!useFileSimulation ||
!audioStreamRef.current ||
!('seekToTime' in audioStreamRef.current) ||
!simulationStats
) {
return
}
const targetTime = simulationStats.totalDuration * (percentage / 100)
; (audioStreamRef.current as any).seekToTime(targetTime)
log(`Seeked to ${targetTime.toFixed(1)}s (${percentage}%)`)
}
const resetAll = () => {
if (realtimeTranscriberRef.current) {
realtimeTranscriberRef.current.reset()
}
setTranscribeResult(null)
setVadEvents([])
setRealtimeStats(null)
setSimulationStats(null)
setStabilizedText('')
log('Reset all components')
}
const checkRecordedFile = async () => {
const recordFilePath = `${fileDir}/realtime-recording.wav`
try {
const exists = await RNFS.exists(recordFilePath)
if (!exists) {
Alert.alert(
'Info',
'No recorded file found. Start a realtime session first.',
)
return
}
const stats = await RNFS.stat(recordFilePath)
const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2)
Alert.alert(
'Recorded File Info',
`File: realtime-recording.wav\nSize: ${fileSizeMB} MB\nPath: ${recordFilePath}`,
[
{ text: 'OK', style: 'default' },
{
text: 'Delete File',
style: 'destructive',
onPress: deleteRecordedFile,
},
],
)
log(`Found recorded file: ${fileSizeMB} MB`)
} catch (error) {
log('Error checking recorded file:', error)
Alert.alert('Error', `Failed to check recorded file: ${error}`)
}
}
const deleteRecordedFile = async () => {
const recordFilePath = `${fileDir}/realtime-recording.wav`
try {
const exists = await RNFS.exists(recordFilePath)
if (exists) {
await RNFS.unlink(recordFilePath)
log('Deleted recorded file')
Alert.alert('Success', 'Recorded file deleted')
}
} catch (error) {
log('Error deleting recorded file:', error)
Alert.alert('Error', `Failed to delete file: ${error}`)
}
}
const forceNextSlice = async () => {
if (!realtimeTranscriberRef.current) {
Alert.alert('Error', 'Realtime transcriber not initialized')
return
}
try {
log('Forcing next slice...')
await realtimeTranscriberRef.current.nextSlice()
log('Successfully forced next slice')
} catch (error) {
log('Error forcing next slice:', error)
Alert.alert('Error', `Failed to force next slice: ${error}`)
}
}
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={styles.scrollview}
>
<View style={styles.container}>
<Text style={[styles.configTitle, { fontSize: 18, marginBottom: 12, textAlign: 'center' }]}>Realtime Transcriber Demo</Text>
{/* Model Selection */}
<View style={styles.configContainer}>
<Text style={styles.configTitle}>Whisper Model Selection</Text>
<View style={styles.buttons}>
{whisperModels.map((model) => (
<Button
key={model}
title={model}
style={[
selectedModel === model ? { backgroundColor: '#007AFF' } : null,
]}
onPress={() => setSelectedModel(model)}
disabled={isTranscribing}
/>
))}
</View>
</View>
{/* Initialization */}
<View style={styles.buttons}>
<Button
title="Initialize (Use Asset base.bin)"
onPress={initializeContextsWithAsset}
disabled={isTranscribing}
/>
<Button
title={`Download & Initialize ${selectedModel}`}
onPress={initializeContextsWithDownload}
disabled={isTranscribing}
/>
</View>
{modelDownloadProgress > 0 && modelDownloadProgress < 1 && (
<View style={styles.logContainer}>
<Text style={styles.logText}>
Downloading {selectedModel}: {Math.round(modelDownloadProgress * 100)}%
</Text>
</View>
)}
{/* Audio Source Configuration */}
<View style={styles.configContainer}>
<Text style={styles.configTitle}>Audio Source</Text>
{useFileSimulation && (
<Text style={styles.configLabel}>
Using JFK speech sample from whisper.cpp repository
</Text>
)}
<View style={styles.configRow}>
<Text style={styles.configLabel}>Use File Simulation:</Text>
<Switch
value={useFileSimulation}
onValueChange={(value) => {
setUseFileSimulation(value)
if (value) downloadAudioFile()
log(`Audio source: ${value ? 'File Simulation' : 'Live Audio'}`)
}}
disabled={isTranscribing}
/>
</View>
{useFileSimulation && (
<>
<View style={styles.configRow}>
<Text style={styles.configLabel}>Audio File:</Text>
<Text style={styles.configValue}>
{audioFilePath ? 'Downloaded' : 'Not downloaded'}
</Text>
</View>
{isDownloading && (
<View style={styles.configRow}>
<Text style={styles.configLabel}>Download Progress:</Text>
<Text style={styles.configValue}>
{downloadProgress.toFixed(1)}%
</Text>
</View>
)}
<View style={styles.buttons}>
<Button
title={audioFilePath ? 'Re-download Audio' : 'Download Audio'}
onPress={() => {
setAudioFilePath(null) // Force re-download
downloadAudioFile()
}}
style={styles.buttonClear}
disabled={isDownloading || isTranscribing}
/>
{audioFilePath && (
<Button
title="Clear Cache"
onPress={async () => {
try {
if (audioFilePath) {
const exists = await RNFS.exists(audioFilePath)
if (exists) {
await RNFS.unlink(audioFilePath)
log('Audio file cache cleared')
}
}
setAudioFilePath(null)
} catch (error) {
log('Error clearing cache:', error)
}
}}
style={styles.buttonClear}
disabled={isDownloading || isTranscribing}
/>
)}
</View>
<View style={styles.configRow}>
<Text style={styles.configLabel}>Playback Speed:</Text>
<Text style={styles.configValue}>{playbackSpeed}x</Text>
</View>
<Button
title="Change Speed"
onPress={changePlaybackSpeed}
style={styles.buttonClear}
disabled={isTranscribing}
/>
</>
)}
</View>
{/* VAD Configuration */}
<View style={styles.configContainer}>
<Text style={styles.configTitle}>VAD Configuration</Text>
<View style={styles.configRow}>
<Text style={styles.configLabel}>Current Preset:</Text>
<Text style={styles.configValue}>{currentVadPreset}</Text>
</View>
<Button
title="Change VAD Preset"
onPress={changeVadPreset}
style={styles.buttonClear}
/>
</View>
{/* Realtime Controls */}
<View style={styles.buttons}>
<Button
title={isTranscribing ? 'Stop Realtime' : 'Start Realtime'}
onPress={
isTranscribing
? stopRealtimeTranscription
: startRealtimeTranscription
}
style={isTranscribing ? styles.buttonDanger : styles.buttonActive}
disabled={
!whisperContextRef.current ||
(useFileSimulation && !audioFilePath) ||
isDownloading
}
/>
<Button
title="Force Next Slice"
onPress={forceNextSlice}
style={styles.buttonClear}
disabled={!isTranscribing || !realtimeTranscriberRef.current}
/>
<Button
title="Reset All"
onPress={resetAll}
style={styles.buttonClear}
/>
</View>
{/* File Simulation Playback Controls */}
{useFileSimulation && simulationStats && (
<View
style={[
styles.playbackContainer,
simulationStats.hasReachedEnd && styles.playbackCompleted,
]}
>
<Text style={styles.playbackTitle}>File Playback Progress</Text>
<Text style={styles.configValue}>
{simulationStats.currentTime.toFixed(1)}s /{' '}
{simulationStats.totalDuration.toFixed(1)}s (
{(simulationStats.progress * 100).toFixed(1)}%)
{simulationStats.hasReachedEnd && ' - COMPLETED'}
</Text>
<View style={styles.progressBar}>
<View
style={[
styles.progressFill,
{ width: `${simulationStats.progress * 100}%` },
]}
/>
</View>
<View style={styles.buttons}>
<Button
title="0%"
onPress={() => seekToPosition(0)}
style={styles.buttonClear}
disabled={!isTranscribing || simulationStats.hasReachedEnd}
/>
<Button
title="25%"
onPress={() => seekToPosition(25)}
style={styles.buttonClear}
disabled={!isTranscribing || simulationStats.hasReachedEnd}
/>
<Button
title="50%"
onPress={() => seekToPosition(50)}
style={styles.buttonClear}
disabled={!isTranscribing || simulationStats.hasReachedEnd}
/>
<Button
title="75%"
onPress={() => seekToPosition(75)}
style={styles.buttonClear}
disabled={!isTranscribing || simulationStats.hasReachedEnd}
/>
</View>
</View>
)}
{/* Status Display */}
{realtimeStats && (
<View
style={[
styles.statusContainer,
isTranscribing ? styles.statusActive : styles.statusInactive,
]}
>
<Text style={styles.statusText}>
Status: {isTranscribing ? 'TRANSCRIBING' : 'STOPPED'} | VAD:{' '}
{realtimeStats.vadEnabled ? 'ON' : 'OFF'} | Memory:{' '}
{realtimeStats.sliceStats?.memoryUsage?.estimatedMB || 0}MB
</Text>
<Text style={styles.statusText}>
Slices: {realtimeStats.sliceStats?.currentSliceIndex || 0}{' '}
current, {realtimeStats.sliceStats?.transcribeSliceIndex || 0}{' '}
transcribing | Audio Source:{' '}
{useFileSimulation ? 'File (JFK)' : 'Live'}
{useFileSimulation && ` @ ${playbackSpeed}x`}
</Text>
<Text style={styles.statusText}>
Stabilized Transcription:{' '}
{stabilizedText}
</Text>
</View>
)}
{/* VAD Events Display */}
{vadEvents.length > 0 && (
<View style={styles.logContainer}>
<Text style={styles.configTitle}>Recent VAD Events</Text>
{vadEvents.slice(-5).map((event, index) => (
<Text key={index} style={styles.logText}>
{event.type}: {event.confidence.toFixed(2)} confidence (slice{' '}
{event.sliceIndex})
</Text>
))}
</View>
)}
{/* Transcription Result */}
{transcribeResult && (
<View style={styles.logContainer}>
<Text style={styles.configTitle}>Latest Transcription</Text>
<Text style={styles.logText}>{transcribeResult}</Text>
</View>
)}
{/* Logs */}
<View style={styles.logContainer}>
<Text style={styles.configTitle}>Debug Logs</Text>
{logs.slice(-10).map((msg, index) => (
<Text key={index} style={styles.logText}>
{msg}
</Text>
))}
</View>
{/* Cleanup */}
<View style={styles.buttons}>
<Button
title="Clear Logs"
style={styles.buttonClear}
onPress={() => {
setLogs([
`Realtime Transcriber Demo - whisper.cpp v${libVersion}`,
])
setTranscribeResult(null)
setVadEvents([])
}}
/>
<Button
title="Check Recorded File"
style={styles.buttonClear}
onPress={checkRecordedFile}
/>
</View>
</View>
</ScrollView>
)
}