-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmain.py
285 lines (236 loc) · 9.48 KB
/
main.py
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
import json
import re
from typing import List, Dict, Optional
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import onnxruntime
import phonemizer
import sounddevice as sd
from phonemizer.backend.espeak.wrapper import EspeakWrapper
import espeakng_loader
from ollama import chat
from lightning_whisper_mlx import LightningWhisperMLX
import signal
from threading import Event
class Weebo:
def __init__(self):
# audio settings
self.SAMPLE_RATE = 24000
self.WHISPER_SAMPLE_RATE = 16000
self.SILENCE_THRESHOLD = 0.02 # volume level that counts as silence
self.SILENCE_DURATION = 1.5 # seconds of silence before cutting recording
# text-to-speech settings
self.MAX_PHONEME_LENGTH = 510
self.CHUNK_SIZE = 300 # size of text chunks for processing
self.SPEED = 1.2
self.VOICE = "am_michael"
# processing things
self.MAX_THREADS = 1
# ollama settings
self.messages = []
self.SYSTEM_PROMPT = "Give a conversational response to the following statement or question in 1-2 sentences. The response should be natural and engaging, and the length depends on what you have to say."
# init components
self._init_espeak()
self._init_models()
self.executor = ThreadPoolExecutor(max_workers=self.MAX_THREADS)
# interrupt handling
self.shutdown_event = Event()
signal.signal(signal.SIGINT, self._signal_handler)
def _signal_handler(self, signum, frame):
print("\nStopping...")
self.shutdown_event.set()
def _init_espeak(self):
# setup espeak for phoneme generation
espeak_data_path = espeakng_loader.get_data_path()
espeak_lib_path = espeakng_loader.get_library_path()
EspeakWrapper.set_data_path(espeak_data_path)
EspeakWrapper.set_library(espeak_lib_path)
# vocab for phoneme tokenization
self.vocab = self._create_vocab()
def _init_models(self):
# init text-to-speech model
self.tts_session = onnxruntime.InferenceSession(
"kokoro-v0_19.onnx",
providers=["CPUExecutionProvider"]
)
# load voice profiles
with open("voices.json") as f:
self.voices = json.load(f)
# init speech recognition model
self.whisper_mlx = LightningWhisperMLX(model="small", batch_size=12)
def _create_vocab(self) -> Dict[str, int]:
# create mapping of characters/phonemes to integer tokens
chars = ['$'] + list(';:,.!?¡¿—…"«»"" ') + \
list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") + \
list("ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ")
return {c: i for i, c in enumerate(chars)}
def phonemize(self, text: str) -> str:
# clean text and convert to phonemes
text = re.sub(r"[^\S \n]", " ", text)
text = re.sub(r" +", " ", text).strip()
phonemes = phonemizer.phonemize(
text,
"en-us",
preserve_punctuation=True,
with_stress=True
)
return "".join(p for p in phonemes.replace("r", "ɹ") if p in self.vocab).strip()
def generate_audio(self, phonemes: str, voice: str, speed: float) -> np.ndarray:
# convert phonemes to audio using TTS model
tokens = [self.vocab[p] for p in phonemes if p in self.vocab]
if not tokens:
return np.array([], dtype=np.float32)
tokens = tokens[:self.MAX_PHONEME_LENGTH]
style = np.array(self.voices[voice], dtype=np.float32)[len(tokens)]
audio = self.tts_session.run(
None,
{
'tokens': [[0, *tokens, 0]],
'style': style,
'speed': np.array([speed], dtype=np.float32)
}
)[0]
return audio
def record_and_transcribe(self):
# state for audio recording
audio_buffer = []
silence_frames = 0
total_frames = 0
def callback(indata, frames, time_info, status):
# callback function that processes incoming audio frames
if self.shutdown_event.is_set():
raise sd.CallbackStop()
nonlocal audio_buffer, silence_frames, total_frames
if status:
print(status)
audio = indata.flatten()
level = np.abs(audio).mean()
audio_buffer.extend(audio.tolist())
total_frames += len(audio)
# track silence duration
if level < self.SILENCE_THRESHOLD:
silence_frames += len(audio)
else:
silence_frames = 0
# process audio when silence is detected
if silence_frames > self.SILENCE_DURATION * self.SAMPLE_RATE:
audio_segment = np.array(audio_buffer, dtype=np.float32)
if len(audio_segment) > self.SAMPLE_RATE:
text = self.whisper_mlx.transcribe(audio_segment)['text']
# skip empty/invalid transcriptions
if text.strip():
print(f"Transcription: {text}")
self.messages.append({
'role': 'user',
'content': text
})
self.create_and_play_response(text)
# reset state
audio_buffer.clear()
silence_frames = 0
total_frames = 0
# start recording loop
try:
with sd.InputStream(
callback=callback,
channels=1,
samplerate=self.SAMPLE_RATE,
dtype=np.float32
):
print("Recording... Press Ctrl+C to stop")
while not self.shutdown_event.is_set():
sd.sleep(100)
except sd.CallbackStop:
pass
def create_and_play_response(self, prompt: str):
if self.shutdown_event.is_set():
return
# stream response from llm
stream = chat(
model='llama3.2',
messages=[{
'role': 'system',
'content': self.SYSTEM_PROMPT
}] + self.messages,
stream=True,
)
# state for processing response
futures = []
buffer = ""
curr_str = ""
try:
# process response stream
for chunk in stream:
if self.shutdown_event.is_set():
break
print(chunk)
text = chunk['message']['content']
if len(text) == 0:
self.messages.append({
'role': 'assistant',
'content': curr_str
})
curr_str = ""
print(self.messages)
continue
buffer += text
curr_str += text
# find end of sentence to chunk at
last_punctuation = max(
buffer.rfind('. '),
buffer.rfind('? '),
buffer.rfind('! ')
)
if last_punctuation == -1:
continue
# handle long chunks
while last_punctuation != -1 and last_punctuation >= self.CHUNK_SIZE:
last_punctuation = max(
buffer.rfind(', ', 0, last_punctuation),
buffer.rfind('; ', 0, last_punctuation),
buffer.rfind('— ', 0, last_punctuation)
)
if last_punctuation == -1:
last_punctuation = buffer.find(' ', 0, self.CHUNK_SIZE)
# process chunk
# convert chunk to audio
chunk_text = buffer[:last_punctuation + 1]
ph = self.phonemize(chunk_text)
futures.append(
self.executor.submit(
self.generate_audio,
ph, self.VOICE, self.SPEED
)
)
buffer = buffer[last_punctuation + 1:]
# process final chunk if any
if buffer and not self.shutdown_event.is_set():
ph = self.phonemize(buffer)
futures.append(
self.executor.submit(
self.generate_audio,
ph, self.VOICE, self.SPEED
)
)
# play generated audio
if not self.shutdown_event.is_set():
with sd.OutputStream(
samplerate=self.SAMPLE_RATE,
channels=1,
dtype=np.float32
) as out_stream:
for fut in futures:
if self.shutdown_event.is_set():
break
audio_data = fut.result()
if len(audio_data) == 0:
continue
out_stream.write(audio_data.reshape(-1, 1))
except Exception as e:
if not self.shutdown_event.is_set():
raise e
def main():
weebo = Weebo()
weebo.record_and_transcribe()
if __name__ == "__main__":
main()