| 12 | import time |
| 13 | |
| 14 | class AudioClient: |
| 15 | def __init__(self, server_url="ws://localhost:8000", token_temp=None, categorical_temp=None, gaussian_temp=None): |
| 16 | # Convert ws:// to http:// for the base URL |
| 17 | self.base_url = server_url.replace("ws://", "http://") |
| 18 | self.server_url = f"{server_url}/audio" |
| 19 | |
| 20 | # Set temperatures if provided |
| 21 | if any(t is not None for t in [token_temp, categorical_temp, gaussian_temp]): |
| 22 | self.set_temperature_and_echo(token_temp, categorical_temp, gaussian_temp) |
| 23 | |
| 24 | # Initialize queues |
| 25 | self.audio_queue = queue.Queue() |
| 26 | self.output_queue = queue.Queue() |
| 27 | |
| 28 | def set_temperature_and_echo(self, token_temp=None, categorical_temp=None, gaussian_temp=None, echo_testing = False): |
| 29 | """Send temperature settings to server""" |
| 30 | params = {} |
| 31 | if token_temp is not None: |
| 32 | params['token_temp'] = token_temp |
| 33 | if categorical_temp is not None: |
| 34 | params['categorical_temp'] = categorical_temp |
| 35 | if gaussian_temp is not None: |
| 36 | params['gaussian_temp'] = gaussian_temp |
| 37 | |
| 38 | response = requests.post(f"{self.base_url}/set_temperature", params=params) |
| 39 | print(response.json()['message']) |
| 40 | |
| 41 | def audio_callback(self, indata, frames, time, status): |
| 42 | """This is called for each audio block""" |
| 43 | if status: |
| 44 | print(status) |
| 45 | # if np.isclose(indata, 0).all(): |
| 46 | # raise Exception('Audio input is not working - received all zeros') |
| 47 | # Convert float32 to int16 for efficient transmission |
| 48 | indata_int16 = (indata.copy() * 32767).astype(np.int16) |
| 49 | # indata_int16 = np.zeros_like(indata_int16) |
| 50 | self.audio_queue.put(indata_int16) |
| 51 | |
| 52 | def output_stream_callback(self, outdata, frames, time, status): |
| 53 | """Callback for output stream to get audio data""" |
| 54 | if status: |
| 55 | print(status) |
| 56 | |
| 57 | try: |
| 58 | data = self.output_queue.get_nowait() |
| 59 | data = data.astype(np.float32) / 32767.0 |
| 60 | if len(data) < len(outdata): |
| 61 | outdata[:len(data)] = data |
| 62 | outdata[len(data):] = 0 |
| 63 | else: |
| 64 | outdata[:] = data[:len(outdata)] |
| 65 | except queue.Empty: |
| 66 | outdata.fill(0) |
| 67 | |
| 68 | async def process_audio(self): |
| 69 | async with websockets.connect(self.server_url) as ws: |
| 70 | while self.running: |
| 71 | if not self.audio_queue.empty(): |