-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeepgram_transcribe.py
142 lines (117 loc) · 4.62 KB
/
deepgram_transcribe.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
from signal import SIGINT, SIGTERM
import asyncio
from dotenv import load_dotenv
import sys
from deepgram import (
DeepgramClient,
DeepgramClientOptions,
LiveTranscriptionEvents,
LiveOptions,
Microphone,
)
load_dotenv()
is_finals = []
async def main():
try:
loop = asyncio.get_event_loop()
# Check if not running on Windows before adding signal handlers
if sys.platform != "win32":
for signal in (SIGTERM, SIGINT):
loop.add_signal_handler(
signal,
lambda: asyncio.create_task(
shutdown(signal, loop, dg_connection, microphone)
),
)
# example of setting up a client config. logging values: WARNING, VERBOSE, DEBUG, SPAM
config: DeepgramClientOptions = DeepgramClientOptions(
options={"keepalive": "true"}
)
deepgram: DeepgramClient = DeepgramClient("", config)
# otherwise, use default config
# deepgram: DeepgramClient = DeepgramClient()
dg_connection = deepgram.listen.asyncwebsocket.v("1")
async def on_open(self, open, **kwargs):
print("Connection Open")
async def on_message(self, result, **kwargs):
global is_finals
sentence = result.channel.alternatives[0].transcript
if len(sentence) == 0:
return
if result.is_final:
is_finals.append(sentence)
if result.speech_final:
utterance = " ".join(is_finals)
print(f"Speech Final: {utterance}")
is_finals = []
else:
print(f"Is Final: {sentence}")
else:
print(f"Interim Results: {sentence}")
async def on_metadata(self, metadata, **kwargs):
print(f"Metadata: {metadata}")
async def on_speech_started(self, speech_started, **kwargs):
print("Speech Started")
async def on_utterance_end(self, utterance_end, **kwargs):
global is_finals
if len(is_finals) > 0:
utterance = " ".join(is_finals)
print(f"Utterance End: {utterance}")
is_finals = []
async def on_close(self, close, **kwargs):
print("Connection Closed")
async def on_error(self, error, **kwargs):
print(f"Handled Error: {error}")
async def on_unhandled(self, unhandled, **kwargs):
print(f"Unhandled Websocket Message: {unhandled}")
dg_connection.on(LiveTranscriptionEvents.Open, on_open)
dg_connection.on(LiveTranscriptionEvents.Transcript, on_message)
dg_connection.on(LiveTranscriptionEvents.Metadata, on_metadata)
dg_connection.on(LiveTranscriptionEvents.SpeechStarted, on_speech_started)
dg_connection.on(LiveTranscriptionEvents.UtteranceEnd, on_utterance_end)
dg_connection.on(LiveTranscriptionEvents.Close, on_close)
dg_connection.on(LiveTranscriptionEvents.Error, on_error)
dg_connection.on(LiveTranscriptionEvents.Unhandled, on_unhandled)
# connect to websocket
options: LiveOptions = LiveOptions(
model="nova-2",
language="en-US",
smart_format=True,
encoding="linear16",
channels=1,
sample_rate=16000,
interim_results=True,
utterance_end_ms="1000",
vad_events=True,
endpointing=300,
)
addons = {"no_delay": "true"}
print("\n\nStart talking! Press Ctrl+C to stop...\n")
if await dg_connection.start(options, addons=addons) is False:
print("Failed to connect to Deepgram")
return
microphone = Microphone(dg_connection.send)
microphone.start()
try:
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
pass
finally:
microphone.finish()
await dg_connection.finish()
print("Finished")
except Exception as e:
print(f"Could not open socket: {e}")
return
async def shutdown(signal, loop, dg_connection, microphone):
print(f"Received exit signal {signal.name}...")
microphone.finish()
await dg_connection.finish()
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
[task.cancel() for task in tasks]
print(f"Cancelling {len(tasks)} outstanding tasks")
await asyncio.gather(*tasks, return_exceptions=True)
loop.stop()
print("Shutdown complete.")
asyncio.run(main())