-
Notifications
You must be signed in to change notification settings - Fork 1
/
TranscribeViewModel.kt
215 lines (193 loc) · 7.61 KB
/
TranscribeViewModel.kt
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
package chat.senses.livesubs
import ai.onnxruntime.OnnxTensor
import ai.onnxruntime.OrtEnvironment
import ai.onnxruntime.OrtSession
import android.annotation.SuppressLint
import android.media.*
import android.util.Log
import androidx.lifecycle.ViewModel
import com.google.gson.annotations.SerializedName
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.gson.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flow
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import java.nio.LongBuffer
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.pow
data class TranscribeInput(
val audio: String,
)
data class TranscriptionResult(
@SerializedName("transcription_id") val transcriptionId: String,
val transcription: String?,
)
@OptIn(DelicateCoroutinesApi::class)
class TranscribeViewModel : ViewModel() {
private val SAMPLE_RATE = 16000
private val BUFFER_BEFORE_AFTER = 10
private val GAIN_DB = 10f.pow(8f / 20f)
private val minBufferSizeIn = AudioRecord.getMinBufferSize(
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_FLOAT,
)
private val minBufferSizeOut = AudioTrack.getMinBufferSize(
SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_FLOAT,
)
@SuppressLint("MissingPermission")
val audioRecord = AudioRecord(
MediaRecorder.AudioSource.MIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_FLOAT,
minBufferSizeIn,
)
val audioTrack = AudioTrack.Builder()
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
)
.setAudioFormat(
AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
.setSampleRate(SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_OUT_MONO)
.build()
)
.setBufferSizeInBytes(minBufferSizeOut)
.build()
private var ortEnv: OrtEnvironment = OrtEnvironment.getEnvironment()
private var ortSession: OrtSession? = null
val speakingProbability = MutableStateFlow(0f)
private val audioFlow: Flow<ByteArray> = flow {
audioRecord.startRecording()
// audioTrack.play()
// audioTrack.setVolume(20f)
var consecutiveSilence = 0
var hasVoice = false
val buffers = ArrayList<FloatBuffer>()
while (true) {
val size = (SAMPLE_RATE / 1000 * 50) // 50ms
val data = FloatArray(size)
var floatsRead = audioRecord.read(data, 0, size, AudioRecord.READ_NON_BLOCKING)
while (floatsRead < size) {
floatsRead += audioRecord.read(data, floatsRead, size - floatsRead, AudioRecord.READ_NON_BLOCKING)
}
// audioTrack.write(data, 0, floatsRead, AudioTrack.WRITE_NON_BLOCKING)
// add a gain
val buffer = FloatBuffer.wrap(data.map { it ->
if (kotlin.math.abs(it * GAIN_DB) > 1f) {
1f * (it / kotlin.math.abs(it))
} else {
it * GAIN_DB
}
}.toFloatArray())
val prob = runVAD(buffer, size)
speakingProbability.value = prob
if (prob > 0.15f) {
hasVoice = true
consecutiveSilence = 0
buffers.add(buffer)
} else {
if (hasVoice) {
consecutiveSilence += 1
buffers.add(buffer)
} else {
buffers.add(buffer)
if (buffers.size > BUFFER_BEFORE_AFTER) {
buffers.removeAt(0)
}
}
if (consecutiveSilence > BUFFER_BEFORE_AFTER && buffers.size > BUFFER_BEFORE_AFTER * 2) {
val byteBuffer = ByteBuffer.allocate(
buffers.fold(0) { acc, buf ->
acc + buf.capacity() * 4
}
)
val byteBufferFloatView = byteBuffer.asFloatBuffer()
for (buf in buffers) {
byteBufferFloatView.put(buf)
}
emit(byteBuffer.array())
consecutiveSilence = 0
hasVoice = false
buffers.clear()
}
}
}
}
val transcription = MutableStateFlow("speak now")
val client = HttpClient(OkHttp) {
install(ContentNegotiation) {
gson()
}
install(HttpTimeout) {
socketTimeoutMillis = 600 * 1000
connectTimeoutMillis = 600 * 1000
requestTimeoutMillis = 600 * 1000 // 10 mins
}
}
init {
CoroutineScope(Dispatchers.IO).launch {
val resources = LiveSubtitlesApplication.INSTANCE.resources
val modelId = R.raw.silero_vad
val modelBytes = resources.openRawResource(modelId).readBytes()
ortSession = ortEnv.createSession(modelBytes)
}
audioTrack.play()
CoroutineScope(newSingleThreadContext("VADThread")).launch {
audioFlow.collect { audio ->
Log.i("TranscribeViewModel", "${audio.size}")
getTranscription(audio)
}
}
}
private fun getTranscription(audio: ByteArray) {
val audioBase64 = String(Base64.getEncoder().encode(audio))
CoroutineScope(newFixedThreadPoolContext(10, "RequestThread")).launch {
val transcribeResponse = client.request("http://192.168.31.171:6666/transcribe") {
method = HttpMethod.Post
contentType(ContentType.Application.Json)
setBody(TranscribeInput(audioBase64))
}
val responseData: TranscriptionResult = transcribeResponse.body()
val transcriptionResponse = client.request("http://192.168.31.171:6666/transcription/${responseData.transcriptionId}") {
method = HttpMethod.Get
}
val transcriptionData: TranscriptionResult = transcriptionResponse.body()
transcription.value = transcriptionData.transcription!!
}
}
private fun runVAD(inputData: FloatBuffer, size: Int): Float {
val inputShape = longArrayOf(1, size.toLong()) // have to re-type numbers because long
val inputTensor = OnnxTensor.createTensor(ortEnv, inputData, inputShape)
val sampleRateTensor = OnnxTensor.createTensor(ortEnv, LongBuffer.wrap(longArrayOf(SAMPLE_RATE.toLong())), longArrayOf(1))
val hTensor = OnnxTensor.createTensor(ortEnv, FloatBuffer.allocate(2 * 1 * 64), longArrayOf(2, 1, 64))
val cTensor = OnnxTensor.createTensor(ortEnv, FloatBuffer.allocate(2 * 1 * 64), longArrayOf(2, 1, 64))
val input = mutableMapOf(
"input" to inputTensor,
"sr" to sampleRateTensor,
"h" to hTensor,
"c" to cTensor,
)
val output = ortSession?.run(input)
// FIXME: not sure why I have to multiply by 8 here, the numbers are much smaller
val prob = (output?.get(0)?.value as Array<FloatArray>)[0][0]
return prob
}
}