generated from deepgram-starters/project-template
-
Notifications
You must be signed in to change notification settings - Fork 24
/
app_socketio.py
86 lines (67 loc) · 2.52 KB
/
app_socketio.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
import logging
import os
from flask import Flask
from flask_socketio import SocketIO
from dotenv import load_dotenv
from deepgram import (
DeepgramClient,
LiveTranscriptionEvents,
LiveOptions,
DeepgramClientOptions
)
load_dotenv()
app_socketio = Flask("app_socketio")
socketio = SocketIO(app_socketio, cors_allowed_origins=['http://127.0.0.1:8000'])
API_KEY = os.getenv("DEEPGRAM_API_KEY")
# Set up client configuration
config = DeepgramClientOptions(
verbose=logging.WARN, # Change to logging.INFO or logging.DEBUG for more verbose output
options={"keepalive": "true"}
)
deepgram = DeepgramClient(API_KEY, config)
dg_connection = None
def initialize_deepgram_connection():
global dg_connection
# Initialize Deepgram client and connection
dg_connection = deepgram.listen.live.v("1")
def on_open(self, open, **kwargs):
print(f"\n\n{open}\n\n")
def on_message(self, result, **kwargs):
transcript = result.channel.alternatives[0].transcript
if len(transcript) > 0:
print(result.channel.alternatives[0].transcript)
socketio.emit('transcription_update', {'transcription': transcript})
def on_close(self, close, **kwargs):
print(f"\n\n{close}\n\n")
def on_error(self, error, **kwargs):
print(f"\n\n{error}\n\n")
dg_connection.on(LiveTranscriptionEvents.Open, on_open)
dg_connection.on(LiveTranscriptionEvents.Transcript, on_message)
dg_connection.on(LiveTranscriptionEvents.Close, on_close)
dg_connection.on(LiveTranscriptionEvents.Error, on_error)
# Define the options for the live transcription
options = LiveOptions(model="nova-2", language="en-US")
if dg_connection.start(options) is False: # THIS CAUSES ERROR
print("Failed to start connection")
exit()
@socketio.on('audio_stream')
def handle_audio_stream(data):
if dg_connection:
dg_connection.send(data)
@socketio.on('toggle_transcription')
def handle_toggle_transcription(data):
print("toggle_transcription", data)
action = data.get("action")
if action == "start":
print("Starting Deepgram connection")
initialize_deepgram_connection()
@socketio.on('connect')
def server_connect():
print('Client connected')
@socketio.on('restart_deepgram')
def restart_deepgram():
print('Restarting Deepgram connection')
initialize_deepgram_connection()
if __name__ == '__main__':
logging.info("Starting SocketIO server.")
socketio.run(app_socketio, debug=True, allow_unsafe_werkzeug=True, port=5001)