|
| 1 | +import React, { useCallback, useEffect, useRef, useState } from 'react' |
| 2 | +import { StyleSheet, ScrollView, View, Text } from 'react-native' |
| 3 | +import LiveAudioStream from '@fugood/react-native-audio-pcm-stream' |
| 4 | +import { Buffer } from 'buffer' |
| 5 | +import RNFS from 'react-native-fs' |
| 6 | +import Sound from 'react-native-sound' |
| 7 | +import { initWhisper, libVersion } from '../../src' |
| 8 | +import type { WhisperContext } from '../../src' |
| 9 | +import { Button } from './Button' |
| 10 | +import contextOpts from './context-opts' |
| 11 | +import { createDir, fileDir } from './util' |
| 12 | + |
| 13 | +const styles = StyleSheet.create({ |
| 14 | + scrollview: { flexGrow: 1, justifyContent: 'center' }, |
| 15 | + container: { |
| 16 | + flex: 1, |
| 17 | + alignItems: 'center', |
| 18 | + justifyContent: 'center', |
| 19 | + padding: 4, |
| 20 | + }, |
| 21 | + buttons: { flexDirection: 'row' }, |
| 22 | + button: { margin: 4, backgroundColor: '#333', borderRadius: 4, padding: 8 }, |
| 23 | + buttonClear: { backgroundColor: '#888' }, |
| 24 | + buttonText: { fontSize: 14, color: 'white', textAlign: 'center' }, |
| 25 | + logContainer: { |
| 26 | + backgroundColor: 'lightgray', |
| 27 | + padding: 8, |
| 28 | + width: '95%', |
| 29 | + borderRadius: 8, |
| 30 | + marginVertical: 8, |
| 31 | + }, |
| 32 | + logText: { fontSize: 12, color: '#333' }, |
| 33 | +}) |
| 34 | + |
| 35 | +const mode = process.env.NODE_ENV === 'development' ? 'debug' : 'release' |
| 36 | +const recordFile = `${fileDir}/record.wav` |
| 37 | + |
| 38 | +const audioOptions = { |
| 39 | + sampleRate: 16000, |
| 40 | + channels: 1, |
| 41 | + bitsPerSample: 16, |
| 42 | + audioSource: 6, |
| 43 | + wavFile: recordFile, |
| 44 | + bufferSize: 16 * 1024, |
| 45 | +} |
| 46 | + |
| 47 | +export default function TranscribeData() { |
| 48 | + const whisperContextRef = useRef<WhisperContext | null>(null) |
| 49 | + const whisperContext = whisperContextRef.current |
| 50 | + const [logs, setLogs] = useState([`whisper.cpp version: ${libVersion}`]) |
| 51 | + const [transcibeResult, setTranscibeResult] = useState<string | null>(null) |
| 52 | + const [isRecording, setIsRecording] = useState(false) |
| 53 | + const recordedDataRef = useRef<Buffer | null>(null) |
| 54 | + |
| 55 | + const log = useCallback((...messages: any[]) => { |
| 56 | + setLogs((prev) => [...prev, messages.join(' ')]) |
| 57 | + }, []) |
| 58 | + |
| 59 | + useEffect( |
| 60 | + () => () => { |
| 61 | + whisperContextRef.current?.release() |
| 62 | + whisperContextRef.current = null |
| 63 | + }, |
| 64 | + [], |
| 65 | + ) |
| 66 | + |
| 67 | + const startRecording = async () => { |
| 68 | + try { |
| 69 | + await createDir(log) |
| 70 | + recordedDataRef.current = null |
| 71 | + |
| 72 | + LiveAudioStream.init(audioOptions) |
| 73 | + LiveAudioStream.on('data', (data: string) => { |
| 74 | + if (!recordedDataRef.current) { |
| 75 | + recordedDataRef.current = Buffer.from(data, 'base64') |
| 76 | + } else { |
| 77 | + recordedDataRef.current = Buffer.concat([ |
| 78 | + recordedDataRef.current, |
| 79 | + Buffer.from(data, 'base64'), |
| 80 | + ]) |
| 81 | + } |
| 82 | + }) |
| 83 | + |
| 84 | + LiveAudioStream.start() |
| 85 | + setIsRecording(true) |
| 86 | + log('Started recording...') |
| 87 | + } catch (error) { |
| 88 | + log('Error starting recording:', error) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + const stopRecording = async () => { |
| 93 | + try { |
| 94 | + // Stop recording and get the wav file path |
| 95 | + await LiveAudioStream.stop() |
| 96 | + setIsRecording(false) |
| 97 | + log('Stopped recording') |
| 98 | + |
| 99 | + if (!recordedDataRef.current) return log('No recorded data') |
| 100 | + if (!whisperContext) return log('No context') |
| 101 | + |
| 102 | + // Read the wav file as base64 |
| 103 | + const base64Data = recordedDataRef.current!.toString('base64') |
| 104 | + log('Start transcribing...') |
| 105 | + |
| 106 | + const startTime = Date.now() |
| 107 | + const { promise } = await whisperContext.transcribeData(base64Data, { |
| 108 | + language: 'en', |
| 109 | + onProgress: (progress) => { |
| 110 | + log(`Transcribing progress: ${progress}%`) |
| 111 | + }, |
| 112 | + }) |
| 113 | + const { result } = await promise |
| 114 | + const endTime = Date.now() |
| 115 | + |
| 116 | + setTranscibeResult( |
| 117 | + `Transcribed result: ${result}\n` + |
| 118 | + `Transcribed in ${endTime - startTime}ms in ${mode} mode`, |
| 119 | + ) |
| 120 | + log('Finished transcribing') |
| 121 | + } catch (error) { |
| 122 | + log('Error stopping recording:', error) |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + return ( |
| 127 | + <ScrollView |
| 128 | + contentInsetAdjustmentBehavior="automatic" |
| 129 | + contentContainerStyle={styles.scrollview} |
| 130 | + > |
| 131 | + <View style={styles.container}> |
| 132 | + <View style={styles.buttons}> |
| 133 | + <Button |
| 134 | + title="Initialize Context" |
| 135 | + onPress={async () => { |
| 136 | + if (whisperContext) { |
| 137 | + log('Found previous context') |
| 138 | + await whisperContext.release() |
| 139 | + whisperContextRef.current = null |
| 140 | + log('Released previous context') |
| 141 | + } |
| 142 | + log('Initialize context...') |
| 143 | + const startTime = Date.now() |
| 144 | + const ctx = await initWhisper({ |
| 145 | + filePath: require('../assets/ggml-base.bin'), |
| 146 | + ...contextOpts, |
| 147 | + }) |
| 148 | + const endTime = Date.now() |
| 149 | + log('Loaded model, ID:', ctx.id) |
| 150 | + log('Loaded model in', endTime - startTime, `ms in ${mode} mode`) |
| 151 | + whisperContextRef.current = ctx |
| 152 | + }} |
| 153 | + /> |
| 154 | + </View> |
| 155 | + |
| 156 | + <View style={styles.buttons}> |
| 157 | + <Button |
| 158 | + title={isRecording ? 'Stop Recording' : 'Start Recording'} |
| 159 | + onPress={isRecording ? stopRecording : startRecording} |
| 160 | + disabled={!whisperContext} |
| 161 | + /> |
| 162 | + </View> |
| 163 | + |
| 164 | + <View style={styles.logContainer}> |
| 165 | + {logs.map((msg, index) => ( |
| 166 | + <Text key={index} style={styles.logText}> |
| 167 | + {msg} |
| 168 | + </Text> |
| 169 | + ))} |
| 170 | + </View> |
| 171 | + |
| 172 | + {transcibeResult && ( |
| 173 | + <View style={styles.logContainer}> |
| 174 | + <Text style={styles.logText}>{transcibeResult}</Text> |
| 175 | + </View> |
| 176 | + )} |
| 177 | + |
| 178 | + <Button |
| 179 | + title="Release Context" |
| 180 | + style={styles.buttonClear} |
| 181 | + onPress={async () => { |
| 182 | + if (!whisperContext) return |
| 183 | + await whisperContext.release() |
| 184 | + whisperContextRef.current = null |
| 185 | + log('Released context') |
| 186 | + }} |
| 187 | + /> |
| 188 | + |
| 189 | + <Button |
| 190 | + title="Clear Logs" |
| 191 | + style={styles.buttonClear} |
| 192 | + onPress={() => { |
| 193 | + setLogs([]) |
| 194 | + setTranscibeResult(null) |
| 195 | + }} |
| 196 | + /> |
| 197 | + |
| 198 | + <Button |
| 199 | + title="Play Recorded file" |
| 200 | + style={styles.buttonClear} |
| 201 | + onPress={async () => { |
| 202 | + if (!(await RNFS.exists(recordFile))) { |
| 203 | + log('Recorded file does not exist') |
| 204 | + return |
| 205 | + } |
| 206 | + const player = new Sound(recordFile, '', (e) => { |
| 207 | + if (e) { |
| 208 | + log('error', e) |
| 209 | + return |
| 210 | + } |
| 211 | + player.play((success) => { |
| 212 | + if (success) { |
| 213 | + log('successfully finished playing') |
| 214 | + } else { |
| 215 | + log('playback failed due to audio decoding errors') |
| 216 | + } |
| 217 | + player.release() |
| 218 | + }) |
| 219 | + }) |
| 220 | + }} |
| 221 | + /> |
| 222 | + </View> |
| 223 | + </ScrollView> |
| 224 | + ) |
| 225 | +} |
0 commit comments