whispering/whispering/serve.py

58 lines
1.3 KiB
Python
Raw Normal View History

2022-09-24 11:45:20 +00:00
#!/usr/bin/env python3
import asyncio
from logging import getLogger
import numpy as np
import websockets
2022-09-29 11:14:56 +00:00
from whispering.transcriber import Context, WhisperStreamingTranscriber
2022-09-24 11:45:20 +00:00
logger = getLogger(__name__)
async def serve_with_websocket_main(websocket):
global g_wsp
2022-09-29 11:43:49 +00:00
global g_ctx
2022-09-24 11:45:20 +00:00
idx: int = 0
while True:
logger.debug(f"Segment #: {idx}")
message = await websocket.recv()
if isinstance(message, str):
logger.debug(f"Got str: {message}")
continue
logger.debug(f"Message size: {len(message)}")
segment = np.frombuffer(message, dtype=np.float32)
2022-09-29 11:43:49 +00:00
for chunk in g_wsp.transcribe(segment=segment, ctx=g_ctx):
2022-09-24 12:39:30 +00:00
await websocket.send(chunk.json())
2022-09-24 11:45:20 +00:00
idx += 1
async def serve_with_websocket(
*,
wsp: WhisperStreamingTranscriber,
host: str,
port: int,
2022-09-29 11:43:49 +00:00
ctx: Context,
2022-09-24 11:45:20 +00:00
):
logger.info(f"Serve at {host}:{port}")
logger.info("Make secure with your responsibility!")
global g_wsp
2022-09-29 11:43:49 +00:00
global g_ctx
2022-09-24 11:45:20 +00:00
g_wsp = wsp
2022-09-29 11:43:49 +00:00
g_ctx = ctx
2022-09-24 11:45:20 +00:00
try:
async with websockets.serve( # type: ignore
serve_with_websocket_main,
host=host,
port=port,
max_size=999999999,
):
await asyncio.Future()
except KeyboardInterrupt:
pass