Create a python system, client and server, using websockets (with all things needed so that the connection is robust, such as the clients reconnecting periodically if the connection is lost), where the server will work as a "transcription server". The idea is the following:
server starts; client connects and sends an identifier (for the moment just hardcode it as "client1"); server stores the client's identifier and websocket in a dictionary; client waits for the user to press enter; client starts streaming audio to the server, read from the microphone (using sounddevice); server listens to the stream and transcribes the audio; when the transcription is finished the server sends a stop signal so that the client can stop recording; server sends the recognized text to the client; client prints the text.
Important details: the audio is not first recorded, then sent; it is sent as soon as it is recorded, maybe using a queue. With the new implementation of websockets, the call server = await websockets.serve(handle_client, "localhost", 8765) expects a method like async def handle_client(websocket), without a path; for the transcription you will have to create a custom audiosource daughter class that receives the websocket (the websocket object, not the uri) and reads from it, probably storing in a queue and giving that to the stream.read when required.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, this is a complex request, but I can definitely help you structure the code for a robust, real-time transcription system using websockets. I'll provide a detailed breakdown with explanations and code snippets for each part.
Project Structure
We'll have three main files:
server.py: The websocket server that manages client connections, receives audio, transcribes it, and sends results back.
client.py: The websocket client that records audio from the microphone, sends it to the server, and prints the transcriptions.
custom_audio.py: A custom audio source implementation tailored for websockets.
1. custom_audio.py
python
import asyncio
import collections
import io
import logging
import time
import wave
from typing import Optional
import websockets
from speech_recognition import AudioData, AudioSource
from speech_recognition.exceptions import RequestError
class WebsocketAudioSource(AudioSource):
"""
An audio source that reads audio data from a websocket connection.
This class is designed to be used with the speech_recognition library,
allowing it to process audio received over a websocket in real-time.
"""
def __init__(self, websocket, sample_rate=16000, sample_width=2, chunk_size=1024):
"""
Initializes the WebsocketAudioSource.
Args:
websocket: The websocket connection to receive audio from.
sample_rate: The sample rate of the audio.
sample_width: The sample width of the audio (in bytes).
chunk_size: The size of audio chunks to read from the websocket (in samples).
"""
assert sample_rate > 0, "Sample rate must be a positive integer"
assert (
sample_width % 1 == 0 and 1 <= sample_width <= 4
), "Sample width must be between 1 and 4 inclusive"
assert chunk_size > 0, "Chunk size must be a positive integer"
self.websocket = websocket
self.SAMPLE_RATE = sample_rate
self.SAMPLE_WIDTH = sample_width
self.CHUNK = chunk_size
self.stream = None
self._audio_queue = collections.deque()
self._is_closed = False
self.logger = logging.getLogger(__name__)
async def _receive_audio(self):
"""
Continuously receives audio data from the websocket and adds it to the queue.
This method runs in a separate task to avoid blocking the main thread.
"""
try:
async for message in self.websocket:
if isinstance(message, bytes):
self._audio_queue.append(message)
else:
self.logger.warning("Received non-binary message from websocket, ignoring")
except websockets.exceptions.ConnectionClosedError:
self.logger.info("Websocket connection closed.")
self._is_closed = True
except Exception as e:
self.logger.error(f"Error receiving audio from websocket: {e}")
self._is_closed = True
self.logger.info("Finished receiving audio.")
def __enter__(self):
"""
Starts the audio receiving process.
"""
self.stream = WebsocketAudioSource.WebsocketAudioStream(self)
self._receiving_task = asyncio.create_task(self._receive_audio())
return self
def __exit__(self, exc_type, exc_value, traceback):
"""
Stops the audio receiving process.
"""
if self._receiving_task:
self._receiving_task.cancel()
self.stream = None
class WebsocketAudioStream(object):
def __init__(self, audio_source):
self.audio_source = audio_source
def read(self, size):
"""
Reads audio data from the queue.
If no data is available, it will block until at least one chunk of data is received.
If the connection is closed, it will return empty bytes.
Args:
size: The number of bytes to read.
Returns:
The audio data as bytes.
"""
if self.audio_source._is_closed:
return b""
if not self.audio_source._audio_queue:
# Wait for audio data to arrive if queue is empty.
start = time.time()
while not self.audio_source._audio_queue and not self.audio_source._is_closed:
time.sleep(0.001) # avoid busy waiting
if time.time() - start > 2:
self.audio_source.logger.warning("Timeout waiting for audio data")
break
if self.audio_source._is_closed:
return b""
try:
full_frame = b""
while len(full_frame) < size and self.audio_source._audio_queue:
full_frame += self.audio_source._audio_queue.popleft()
return full_frame[:size] # ensures not returning more than requested
except Exception as e:
self.audio_source.logger.error(f"Error reading from audio queue {e}")
return b""
def get_audio_data(self):
"""Returns an AudioData object with all the audio from the websocket."""
all_audio = b""
while self._audio_queue:
all_audio += self._audio_queue.popleft()
return AudioData(all_audio, self.SAMPLE_RATE, self.SAMPLE_WIDTH)
2. server.py
python
3. client.py
python
Explanation
custom_audio.py:
WebsocketAudioSource acts as a bridge between the websocket and speech_recognition's audio handling.
It uses an internal queue to store audio data as it arrives from the websocket.
The stream.read method provides the speech_recognition library with audio data as needed.
The get_audio_data() method provides an AudioData object containing all the audio in the queue.
server.py:
Uses websockets.serve to start a websocket server.
handle_client stores client connections in a dictionary and calls the process_audio method to handle audio transcription for each client.
process_audio reads audio data using the custom WebsocketAudioSource, transcribes it using speech_recognition, and sends back the transcriptions. It also sends a stop signal to the client.
Includes a robust error handling, with logs and reconnections strategies.
client.py:
Uses websockets.connect to connect to the server.
connect_and_stream sends the client ID to the server and call the method to start recording and streaming.
_stream_audio records audio data using sounddevice and sends it to the server using send_audio.
It receives transcriptions from the server and prints them. It stops streaming when receive the stop signal.
Includes a robust error handling, with logs and reconnections strategies.
To Run
Make sure you have the necessary libraries installed:
You might also need PyAudio, install it as required by your OS.
Run the server in one terminal:
bash
python server.py
Run the client in another terminal:
bash
python client.py
Press Enter in the client terminal and start speaking into the microphone
Important Notes
This is a relatively basic framework. You'll want to add more robust error handling (for example, handling cases where the transcription service fails or the connection is closed unexpectedly) and potentially more sophisticated audio handling, for example adding a gain/noise filter.
The reconnection logic in the client could be improved, you can also add an exponential backoff strategy for reconnection.
Consider using a more robust queue system, like RabbitMQ or Redis if you need to scale this application further or make the system fault tolerant.
For a production environment, you may need to implement more robust security measures.
I hope this detailed explanation helps! Let me know if you have any further questions.
Dataset releases
Not yet included in a published release.
import asyncio
import json
import logging
import os
import time
from typing import Dict
import websockets
from websockets.exceptions import ConnectionClosedError
import speech_recognition as sr
from custom_audio import WebsocketAudioSource
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class TranscriptionServer:
"""A websocket server that transcribes audio from clients."""
def __init__(self):
self.clients: Dict[str, websockets.WebSocketClientProtocol] = {}
self.recognizer = sr.Recognizer()
self.logger = logging.getLogger(__name__)
async def handle_client(self, websocket):
"""Handles a new client connection."""
try:
self.logger.info("New client connected.")
client_id = await websocket.recv()
self.logger.info(f"Client ID received: {client_id}")
self.clients[client_id] = websocket
await self.process_audio(websocket, client_id)
except ConnectionClosedError:
self.logger.warning(f"Client connection closed unexpectedly.")
except Exception as e:
self.logger.error(f"Error handling client: {e}")
finally:
if client_id in self.clients:
del self.clients[client_id]
self.logger.info(f"Client {client_id} disconnected.")
async def process_audio(self, websocket, client_id):
"""Receives audio from a client, transcribes it, and sends back the text."""
try:
with WebsocketAudioSource(websocket) as source:
self.logger.info(f"Start recording from client {client_id}.")
while True:
try:
audio_data = self.recognizer.record(source, duration=1)
if not audio_data.frame_data:
self.logger.info(f"No audio data, stop recording from client {client_id}")
break
text = self.recognizer.recognize_google(audio_data)
self.logger.info(f"Transcription from client {client_id}: {text}")
await websocket.send(json.dumps({"text": text}))
except sr.UnknownValueError:
self.logger.warning(f"Could not understand audio from client {client_id}")
except sr.RequestError as e:
self.logger.error(f"Error requesting from google, from client {client_id}: {e}")
break # stop processing if there is an error
except Exception as e:
self.logger.error(f"Error processing audio from client {client_id}: {e}")
break # stop processing if there is an error
self.logger.info(f"Stop recording from client {client_id}")
await websocket.send(json.dumps({"stop": True}))
except ConnectionClosedError:
self.logger.warning(f"Connection closed while receiving audio for client {client_id}.")
except Exception as e:
self.logger.error(f"Unexpected error while receiving audio for client {client_id}: {e}")
async def start(self, host="localhost", port=8765):
"""Starts the websocket server."""
self.logger.info(f"Starting server on {host}:{port}")
async with websockets.serve(self.handle_client, host, port) as server:
await asyncio.Future() # run forever
if __name__ == "__main__":
server = TranscriptionServer()
asyncio.run(server.start())
import asyncio
import json
import logging
import sys
import sounddevice as sd
import websockets
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class TranscriptionClient:
"""A websocket client that sends audio to the server for transcription."""
def __init__(self, server_uri, client_id="client1"):
self.server_uri = server_uri
self.client_id = client_id
self.logger = logging.getLogger(__name__)
self.sample_rate = 16000
self.sample_width = 2 # 16 bits
self.channels = 1
self.blocksize = 1024
async def connect_and_stream(self):
"""Connects to the server, sends audio, and receives transcriptions."""
while True: # loop to allow reconnections
try:
async with websockets.connect(self.server_uri) as websocket:
self.logger.info("Connected to server.")
await websocket.send(self.client_id)
await self._stream_audio(websocket)
break # stop reconnection loop if client disconnect gracefully
except websockets.exceptions.ConnectionClosedError:
self.logger.warning("Connection to server lost, attempting reconnect in 5 seconds.")
except Exception as e:
self.logger.error(f"Error during connection or streaming: {e}")
await asyncio.sleep(5)
async def _stream_audio(self, websocket):
"""Streams audio data from the microphone to the server."""
try:
input("Press Enter to start recording...") # waits until the user press enter
def callback(indata, frames, time, status):
if status:
self.logger.warning(f"Error in audio stream {status}")
asyncio.create_task(self._send_audio(websocket, indata.tobytes())) # send the audio to the server
stream = sd.InputStream(samplerate=self.sample_rate, blocksize=self.blocksize,
channels=self.channels, dtype="int16", callback=callback)
with stream:
self.logger.info("Start recording...")
while True:
try:
response = await websocket.recv()
data = json.loads(response)
if "text" in data:
print(f"Transcription: {data['text']}")
if data.get("stop"):
self.logger.info("Received stop signal. Stop recording")
break
except websockets.exceptions.ConnectionClosedError:
self.logger.warning("Connection closed while receiving results.")
break
except Exception as e:
self.logger.error(f"Unexpected error during streaming: {e}")
async def _send_audio(self, websocket, audio_data):
"""Sends audio data to the websocket server"""
try:
await websocket.send(audio_data)
except Exception as e:
self.logger.error(f"Error sending audio: {e}")
async def main():
"""Entrypoint for the client."""
client = TranscriptionClient("ws://localhost:8765")
await client.connect_and_stream()
if __name__ == "__main__":
asyncio.run(main())