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.
To create a Python system with a client and server using WebSockets for real-time audio transcription, we'll need to implement both the client and server components. The server will handle incoming audio streams from clients, transcribe them using the speech_recognition library, and send back the transcription results. The client will capture audio from the microphone, stream it to the server, and display the transcription.
Here's a step-by-step implementation:
1. Server Implementation
The server will handle WebSocket connections, receive audio data, and perform transcription.
python
import asyncio
import websockets
import speech_recognition as sr
from collections import deque
class WebSocketAudioSource(sr.AudioSource):
def __init__(self, websocket):
self.websocket = websocket
self.queue = deque()
self.sample_rate = 16000 # Adjust based on your audio format
self.sample_width = 2 # 16-bit audio
self.stream = self
def read(self, size):
while len(self.queue) < size:
audio_data = asyncio.run(self.websocket.recv())
self.queue.extend(audio_data)
return bytes([self.queue.popleft() for _ in range(size)])
def close(self):
pass
async def handle_client(websocket, path):
print("Client connected")
audio_source = WebSocketAudioSource(websocket)
recognizer = sr.Recognizer()
try:
while True:
audio_data = await websocket.recv()
if audio_data == b"END":
break
# Perform transcription
try:
text = recognizer.recognize_google(audio_source)
await websocket.send(f"Transcription: {text}")
except sr.UnknownValueError:
await websocket.send("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
await websocket.send(f"Could not request results from Google Speech Recognition service; {e}")
except websockets.ConnectionClosed:
print("Client disconnected")
async def start_server():
async with websockets.serve(handle_client, "localhost", 8765):
await asyncio.Future() # Run forever
if __name__ == "__main__":
asyncio.run(start_server())
2. Client Implementation
The client will capture audio from the microphone, stream it to the server, and display the transcription.
python
import asyncio
import websockets
import sounddevice as sd
import numpy as np
async def send_audio(websocket):
sample_rate = 16000
channels = 1
dtype = np.int16
def callback(indata, frames, time, status):
if status:
print(status)
asyncio.run(websocket.send(indata.tobytes()))
with sd.InputStream(samplerate=sample_rate, channels=channels, dtype=dtype, callback=callback):
print("Recording... Press Enter to stop.")
input() # Wait for Enter key
await websocket.send(b"END") # Signal end of stream
async def client():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
await websocket.send("client1") # Send client identifier
print("Connected to server")
await send_audio(websocket)
# Receive transcription
transcription = await websocket.recv()
print(transcription)
if __name__ == "__main__":
asyncio.run(client())
3. Robustness and Reconnection
To make the connection robust, you can implement a reconnection mechanism in the client:
python
async def client():
uri = "ws://localhost:8765"
while True:
try:
async with websockets.connect(uri) as websocket:
await websocket.send("client1") # Send client identifier
print("Connected to server")
await send_audio(websocket)
# Receive transcription
transcription = await websocket.recv()
print(transcription)
break # Exit the loop after successful transcription
except (websockets.ConnectionClosed, ConnectionRefusedError):
print("Connection lost, retrying...")
await asyncio.sleep(5) # Wait before retrying
if __name__ == "__main__":
asyncio.run(client())
Explanation
Server:
The server listens for WebSocket connections and handles audio streams.
It uses a custom WebSocketAudioSource class to read audio data from the WebSocket and feed it into the speech_recognition library.
The server transcribes the audio in real-time and sends the transcription back to the client.
Client:
The client captures audio from the microphone using sounddevice and streams it to the server.
It waits for the user to press Enter to stop recording and sends an "END" signal to the server.
The client then waits for the transcription result from the server and prints it.
Reconnection:
The client will automatically reconnect if the connection is lost, ensuring robustness.
This implementation provides a basic real-time audio transcription system using WebSockets. You can further enhance it by adding more features like handling multiple clients, improving error handling, and optimizing the audio stream processing.