File size: 3,099 Bytes
63ca72d 4519b2e 861d215 63ca72d 4519b2e 63ca72d 4519b2e 63ca72d 4519b2e 861d215 4519b2e 63ca72d 4519b2e 63ca72d 4519b2e da37581 4519b2e da37581 63ca72d 4519b2e 63ca72d da37581 0e6a3e8 861d215 656c424 | 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 | from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import numpy as np
from scipy.signal import resample
import json
import asyncio
from RealtimeSTT import AudioToTextRecorder
app = FastAPI()
recorder = None
recorder_ready = asyncio.Event()
clients = set()
async def send_to_clients(message):
if clients:
for ws in clients:
try:
await ws.send_text(message)
except Exception as e:
print(f"Failed to send message: {e}")
def text_detected(text):
asyncio.create_task(send_to_clients(json.dumps({'type': 'realtime', 'text': text})))
print(f"\r{text}", flush=True, end='')
recorder_config = {
'spinner': False,
'use_microphone': False,
'model': 'large-v2',
'language': 'en',
'silero_sensitivity': 0.4,
'webrtc_sensitivity': 2,
'post_speech_silence_duration': 0.7,
'min_length_of_recording': 0,
'min_gap_between_recordings': 0,
'enable_realtime_transcription': True,
'realtime_processing_pause': 0,
'realtime_model_type': 'tiny.en',
'on_realtime_transcription_stabilized': text_detected,
}
async def recorder_task():
global recorder
print("Initializing RealtimeSTT...")
recorder = AudioToTextRecorder(**recorder_config)
print("RealtimeSTT initialized")
recorder_ready.set()
while True:
full_sentence = recorder.text()
asyncio.create_task(send_to_clients(json.dumps({'type': 'fullSentence', 'text': full_sentence})))
print(f"\rSentence: {full_sentence}")
def decode_and_resample(audio_data, original_sample_rate, target_sample_rate):
audio_np = np.frombuffer(audio_data, dtype=np.int16)
num_original_samples = len(audio_np)
num_target_samples = int(num_original_samples * target_sample_rate / original_sample_rate)
resampled_audio = resample(audio_np, num_target_samples)
return resampled_audio.astype(np.int16).tobytes()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
clients.add(websocket)
try:
while True:
message = await websocket.receive_bytes()
if not recorder_ready.is_set():
print("Recorder not ready")
continue
metadata_length = int.from_bytes(message[:4], byteorder='little')
metadata_json = message[4:4+metadata_length].decode('utf-8')
metadata = json.loads(metadata_json)
sample_rate = metadata['sampleRate']
chunk = message[4+metadata_length:]
try:
resampled_chunk = decode_and_resample(chunk, sample_rate, 16000)
recorder.feed_audio(resampled_chunk)
except Exception as e:
print(f"Error processing audio chunk: {e}")
except WebSocketDisconnect:
print("Client disconnected")
finally:
clients.remove(websocket)
@app.on_event("startup")
async def startup_event():
asyncio.create_task(recorder_task())
await recorder_ready.wait()
print("Server started. Press Ctrl+C to stop the server.")
|