forked from deepgram/live-streaming-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_suite.py
474 lines (403 loc) Β· 18.1 KB
/
test_suite.py
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import pyaudio
import argparse
import asyncio
import aiohttp
import json
import os
import sys
import wave
import websockets
from datetime import datetime
startTime = datetime.now()
all_mic_data = []
all_transcripts = []
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 8000
audio_queue = asyncio.Queue()
# Mimic sending a real-time stream by sending this many seconds of audio at a time.
# Used for file "streaming" only.
REALTIME_RESOLUTION = 0.250
subtitle_line_counter = 0
def subtitle_time_formatter(seconds, separator):
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02}:{minutes:02}:{secs:02}{separator}{millis:03}"
def subtitle_formatter(response, format):
global subtitle_line_counter
subtitle_line_counter += 1
start = response["start"]
end = start + response["duration"]
transcript = response.get("channel", {}).get("alternatives", [{}])[0].get("transcript", "")
separator = "," if format == "srt" else '.'
prefix = "- " if format == "vtt" else ""
subtitle_string = (
f"{subtitle_line_counter}\n"
f"{subtitle_time_formatter(start, separator)} --> "
f"{subtitle_time_formatter(end, separator)}\n"
f"{prefix}{transcript}\n\n"
)
return subtitle_string
# Used for microphone streaming only.
def mic_callback(input_data, frame_count, time_info, status_flag):
audio_queue.put_nowait(input_data)
return (input_data, pyaudio.paContinue)
async def run(key, method, format, **kwargs):
deepgram_url = f'{kwargs["host"]}/v1/listen?punctuate=true'
if kwargs["model"]:
deepgram_url += f"&model={kwargs['model']}"
if kwargs["tier"]:
deepgram_url += f"&tier={kwargs['tier']}"
if method == "mic":
deepgram_url += "&encoding=linear16&sample_rate=16000"
elif method == "wav":
data = kwargs["data"]
deepgram_url += f'&channels={kwargs["channels"]}&sample_rate={kwargs["sample_rate"]}&encoding=linear16'
# Connect to the real-time streaming endpoint, attaching our credentials.
async with websockets.connect(
deepgram_url, extra_headers={"Authorization": "Token {}".format(key)}
) as ws:
print(f'βΉοΈ Request ID: {ws.response_headers.get("dg-request-id")}')
if kwargs["model"]:
print(f'βΉοΈ Model: {kwargs["model"]}')
if kwargs["tier"]:
print(f'βΉοΈ Tier: {kwargs["tier"]}')
print("π’ (1/5) Successfully opened Deepgram streaming connection")
async def sender(ws):
print(
f'π’ (2/5) Ready to stream {method if (method == "mic" or method == "url") else kwargs["filepath"]} audio to Deepgram{". Speak into your microphone to transcribe." if method == "mic" else ""}'
)
if method == "mic":
try:
while True:
mic_data = await audio_queue.get()
all_mic_data.append(mic_data)
await ws.send(mic_data)
except websockets.exceptions.ConnectionClosedOK:
await ws.send(json.dumps({"type": "CloseStream"}))
print(
"π’ (5/5) Successfully closed Deepgram connection, waiting for final transcripts if necessary"
)
except Exception as e:
print(f"Error while sending: {str(e)}")
raise
elif method == "url":
# Listen for the connection to open and send streaming audio from the URL to Deepgram
async with aiohttp.ClientSession() as session:
async with session.get(kwargs["url"]) as audio:
while True:
remote_url_data = await audio.content.readany()
await ws.send(remote_url_data)
# If no data is being sent from the live stream, then break out of the loop.
if not remote_url_data:
break
elif method == "wav":
nonlocal data
# How many bytes are contained in one second of audio?
byte_rate = (
kwargs["sample_width"] * kwargs["sample_rate"] * kwargs["channels"]
)
# How many bytes are in `REALTIME_RESOLUTION` seconds of audio?
chunk_size = int(byte_rate * REALTIME_RESOLUTION)
try:
while len(data):
chunk, data = data[:chunk_size], data[chunk_size:]
# Mimic real-time by waiting `REALTIME_RESOLUTION` seconds
# before the next packet.
await asyncio.sleep(REALTIME_RESOLUTION)
# Send the data
await ws.send(chunk)
await ws.send(json.dumps({"type": "CloseStream"}))
print(
"π’ (5/5) Successfully closed Deepgram connection, waiting for final transcripts if necessary"
)
except Exception as e:
print(f"π΄ ERROR: Something happened while sending, {e}")
raise e
return
async def receiver(ws):
"""Print out the messages received from the server."""
first_message = True
first_transcript = True
transcript = ""
async for msg in ws:
res = json.loads(msg)
if first_message:
print(
"π’ (3/5) Successfully receiving Deepgram messages, waiting for finalized transcription..."
)
first_message = False
try:
# handle local server messages
if res.get("msg"):
print(res["msg"])
if res.get("is_final"):
transcript = (
res.get("channel", {})
.get("alternatives", [{}])[0]
.get("transcript", "")
)
if kwargs["timestamps"]:
words = res.get("channel", {}).get("alternatives", [{}])[0].get("words", [])
start = words[0]["start"] if words else None
end = words[-1]["end"] if words else None
transcript += " [{} - {}]".format(start, end) if (start and end) else ""
if transcript != "":
if first_transcript:
print("π’ (4/5) Began receiving transcription")
# if using webvtt, print out header
if format == "vtt":
print("WEBVTT\n")
first_transcript = False
if format == "vtt" or format == "srt":
transcript = subtitle_formatter(res, format)
print(transcript)
all_transcripts.append(transcript)
# if using the microphone, close stream if user says "goodbye"
if method == "mic" and "goodbye" in transcript.lower():
await ws.send(json.dumps({"type": "CloseStream"}))
print(
"π’ (5/5) Successfully closed Deepgram connection, waiting for final transcripts if necessary"
)
# handle end of stream
if res.get("created"):
# save subtitle data if specified
if format == "vtt" or format == "srt":
data_dir = os.path.abspath(
os.path.join(os.path.curdir, "data")
)
if not os.path.exists(data_dir):
os.makedirs(data_dir)
transcript_file_path = os.path.abspath(
os.path.join(
data_dir,
f"{startTime.strftime('%Y%m%d%H%M')}.{format}",
)
)
with open(transcript_file_path, "w") as f:
f.write("".join(all_transcripts))
print(f"π’ Subtitles saved to {transcript_file_path}")
# also save mic data if we were live streaming audio
# otherwise the wav file will already be saved to disk
if method == "mic":
wave_file_path = os.path.abspath(
os.path.join(
data_dir,
f"{startTime.strftime('%Y%m%d%H%M')}.wav",
)
)
wave_file = wave.open(wave_file_path, "wb")
wave_file.setnchannels(CHANNELS)
wave_file.setsampwidth(SAMPLE_SIZE)
wave_file.setframerate(RATE)
wave_file.writeframes(b"".join(all_mic_data))
wave_file.close()
print(f"π’ Mic audio saved to {wave_file_path}")
print(
f'π’ Request finished with a duration of {res["duration"]} seconds. Exiting!'
)
except KeyError:
print(f"π΄ ERROR: Received unexpected API response! {msg}")
# Set up microphone if streaming from mic
async def microphone():
audio = pyaudio.PyAudio()
stream = audio.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=mic_callback,
)
stream.start_stream()
global SAMPLE_SIZE
SAMPLE_SIZE = audio.get_sample_size(FORMAT)
while stream.is_active():
await asyncio.sleep(0.1)
stream.stop_stream()
stream.close()
functions = [
asyncio.ensure_future(sender(ws)),
asyncio.ensure_future(receiver(ws)),
]
if method == "mic":
functions.append(asyncio.ensure_future(microphone()))
await asyncio.gather(*functions)
def validate_input(input):
if input.lower().startswith("mic"):
return input
elif input.lower().endswith("wav"):
if os.path.exists(input):
return input
elif input.lower().startswith("http"):
return input
raise argparse.ArgumentTypeError(
f'{input} is an invalid input. Please enter the path to a WAV file, a valid stream URL, or "mic" to stream from your microphone.'
)
def validate_format(format):
if (
format.lower() == ("text")
or format.lower() == ("vtt")
or format.lower() == ("srt")
):
return format
raise argparse.ArgumentTypeError(
f'{format} is invalid. Please enter "text", "vtt", or "srt".'
)
def validate_dg_host(dg_host):
if (
# Check that the host is a websocket URL
dg_host.startswith("wss://")
or dg_host.startswith("ws://")
):
# Trim trailing slash if necessary
if dg_host[-1] == '/':
return dg_host[:-1]
return dg_host
raise argparse.ArgumentTypeError(
f'{dg_host} is invalid. Please provide a WebSocket URL in the format "{{wss|ws}}://hostname[:port]".'
)
def parse_args():
"""Parses the command-line arguments."""
parser = argparse.ArgumentParser(
description="Submits data to the real-time streaming endpoint."
)
parser.add_argument(
"-k", "--key", required=True, help="YOUR_DEEPGRAM_API_KEY (authorization)"
)
parser.add_argument(
"-i",
"--input",
help='Input to stream to Deepgram. Can be "mic" to stream from your microphone (requires pyaudio), the path to a WAV file, or the URL to a direct audio stream. Defaults to the included file preamble.wav',
nargs="?",
const=1,
default="preamble.wav",
type=validate_input,
)
parser.add_argument(
"-m",
"--model",
help='Which model to make your request against. Defaults to none specified. See https://developers.deepgram.com/docs/models-overview for all model options.',
nargs="?",
const="",
default="general",
)
parser.add_argument(
"-t",
"--tier",
help='Which model tier to make your request against. Defaults to none specified. See https://developers.deepgram.com/docs/tier for all tier options.',
nargs="?",
const="",
default="",
)
parser.add_argument(
"-ts",
"--timestamps",
help='Whether to include timestamps in the printed streaming transcript. Defaults to False.',
nargs="?",
const=1,
default=False,
)
parser.add_argument(
"-f",
"--format",
help='Format for output. Can be "text" to return plain text, "VTT", or "SRT". If set to VTT or SRT, the audio file and subtitle file will be saved to the data/ directory. Defaults to "text".',
nargs="?",
const=1,
default="text",
type=validate_format,
)
#Parse the host
parser.add_argument(
"--host",
help='Point the test suite at a specific Deepgram URL (useful for on-prem deployments). Takes "{{wss|ws}}://hostname[:port]" as its value. Defaults to "wss://api.deepgram.com".',
nargs="?",
const=1,
default="wss://api.deepgram.com",
type=validate_dg_host,
)
return parser.parse_args()
def main():
"""Entrypoint for the example."""
# Parse the command-line arguments.
args = parse_args()
input = args.input
format = args.format.lower()
host = args.host
try:
if input.lower().startswith("mic"):
asyncio.run(run(args.key, "mic", format, model=args.model, tier=args.tier, host=host, timestamps=args.timestamps))
elif input.lower().endswith("wav"):
if os.path.exists(input):
# Open the audio file.
with wave.open(input, "rb") as fh:
(
channels,
sample_width,
sample_rate,
num_samples,
_,
_,
) = fh.getparams()
assert sample_width == 2, "WAV data must be 16-bit."
data = fh.readframes(num_samples)
asyncio.run(
run(
args.key,
"wav",
format,
model=args.model,
tier=args.tier,
data=data,
channels=channels,
sample_width=sample_width,
sample_rate=sample_rate,
filepath=args.input,
host=host,
timestamps=args.timestamps,
)
)
else:
raise argparse.ArgumentTypeError(
f"π΄ {args.input} is not a valid WAV file."
)
elif input.lower().startswith("http"):
asyncio.run(run(args.key, "url", format, model=args.model, tier=args.tier, url=input, host=host, timestamps=args.timestamps))
else:
raise argparse.ArgumentTypeError(
f'π΄ {input} is an invalid input. Please enter the path to a WAV file, a valid stream URL, or "mic" to stream from your microphone.'
)
except websockets.exceptions.InvalidStatusCode as e:
print(f'π΄ ERROR: Could not connect to Deepgram! {e.headers.get("dg-error")}')
print(
f'π΄ Please contact Deepgram Support ([email protected]) with request ID {e.headers.get("dg-request-id")}'
)
return
except websockets.exceptions.ConnectionClosedError as e:
error_description = f"Unknown websocket error."
print(
f"π΄ ERROR: Deepgram connection unexpectedly closed with code {e.code} and payload {e.reason}"
)
if e.reason == "DATA-0000":
error_description = "The payload cannot be decoded as audio. It is either not audio data or is a codec unsupported by Deepgram."
elif e.reason == "NET-0000":
error_description = "The service has not transmitted a Text frame to the client within the timeout window. This may indicate an issue internally in Deepgram's systems or could be due to Deepgram not receiving enough audio data to transcribe a frame."
elif e.reason == "NET-0001":
error_description = "The service has not received a Binary frame from the client within the timeout window. This may indicate an internal issue in Deepgram's systems, the client's systems, or the network connecting them."
print(f"π΄ {error_description}")
# TODO: update with link to streaming troubleshooting page once available
# print(f'π΄ Refer to our troubleshooting suggestions: ')
print(
f"π΄ Please contact Deepgram Support ([email protected]) with the request ID listed above."
)
return
except websockets.exceptions.ConnectionClosedOK:
return
except Exception as e:
print(f"π΄ ERROR: Something went wrong! {e}")
return
if __name__ == "__main__":
sys.exit(main() or 0)