V-Blaze and V-Cloud Online Help

WebSocket Example

The following is a simple python example that illustrates how to interact with the V‑Blaze REST API WebSocket interface. The URL, FILE, and HEADERS variables may be modified to change the behavior of this script.


# pip3 install websocket_client
import websocket

# URL of the V-Blaze machine to connect to
URL = 'ws://localhost:17171/transcribe'

# Path of an audio file to transcribe
FILE = 'sample1.wav'

# HTTP headers. May specify V-Blaze parameters like:
# 'X-Voci- tag_name': 'tag_value'
    'X-Voci-Model': 'eng1:callcenter',
    'X-Voci-Output': 'text',

    # Audio encoding must be specified explicitly when using the websocket
    # interface. This instructs V-Blaze that the provided audio will have a
    # WAVE header from which the audio encoding information may be extracted.
    'X-Voci-Datahdr': 'WAVE',

    # For tags which contain special characters you may escape them like so:
    # from urlparse.parse import quote
    # 'X-Voci-Subst_rules': quote(...),

# ------------------------------------------------------------------------------

def main():
    # Create and run a websocket application. The on_open function is called
    # after the connection is established. The on_message function is called
    # each time we receive a message from V-Blaze. The on_close function is
    # called when the connection is closed.
    ws = websocket.WebSocketApp(
        URL, header=HEADERS,
        on_open=on_open, on_message=on_message, on_close=on_close

def on_open(ws):
    # Sends the file to V-Blaze. This example sends the entire file in a single
    # send call; however, you may split the audio data into smaller chunks and
    # make multiple send calls. This is especially useful if you want to avoid
    # loading the entire file into memory or if you are submitting audio in
    # realtime.
    with open(FILE, 'rb') as f:
        ws.send(f.read(), opcode=websocket.ABNF.OPCODE_BINARY)
    ws.send(bytearray(), opcode=websocket.ABNF.OPCODE_BINARY)

def on_message(ws, message):
    # V-Blaze sends text websocket dataframes containing transcripts and binary
    # dataframes containing audio. This if statement distinguishes between the
    # two. If "X-Voci-Scrubaudio: true" was not specified then this check is not
    # necessary since no audio data will be received.
    if isinstance(message, str):
        # Handle transcript
        print(f'Received transcript: {message}')
        # Handle scrubbed audio
        print(f'Got {len(message)} bytes of scrubbed audio')
        with open(f'{FILE}.scrubbed', 'ab') as f: f.write(message)
def on_close(ws, status, message):
    # status is an integer websocket status code.
    # message is a string detailing the reason for the close (may be empty).
    # A 1000 status code is used for successful closes
    if status == 1000: print('Closed successfully')
    else: print(f'Closed with code {status} and error: {message}')

if __name__ == '__main__': main()