forked from JARS-PennApps2023/TheraSpeak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsr_in_streamlit.py
112 lines (81 loc) · 2.45 KB
/
sr_in_streamlit.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
import streamlit as st
import websockets
import asyncio
import base64
import json
from configure import auth_key
import pyaudio
if 'text' not in st.session_state:
st.session_state['text'] = 'Listening...'
st.session_state['run'] = False
FRAMES_PER_BUFFER = 3200
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
p = pyaudio.PyAudio()
# starts recording
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=FRAMES_PER_BUFFER
)
def start_listening():
st.session_state['run'] = True
def stop_listening():
st.session_state['run'] = False
st.title('Get real-time transcription')
start, stop = st.columns(2)
start.button('Start listening', on_click=start_listening)
stop.button('Stop listening', on_click=stop_listening)
URL = "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=16000"
async def send_receive():
print(f'Connecting websocket to url ${URL}')
async with websockets.connect(
URL,
extra_headers=(("Authorization", auth_key),),
ping_interval=5,
ping_timeout=20
) as _ws:
r = await asyncio.sleep(0.1)
print("Receiving SessionBegins ...")
session_begins = await _ws.recv()
print(session_begins)
print("Sending messages ...")
async def send():
while st.session_state['run']:
try:
data = stream.read(FRAMES_PER_BUFFER)
data = base64.b64encode(data).decode("utf-8")
json_data = json.dumps({"audio_data":str(data)})
r = await _ws.send(json_data)
except websockets.exceptions.ConnectionClosedError as e:
print(e)
print('5')
assert e.code == 4008
break
except Exception as e:
print(e)
print('6')
assert False, "Not a websocket 4008 error"
r = await asyncio.sleep(0.01)
async def receive():
while st.session_state['run']:
try:
result_str = await _ws.recv()
result = json.loads(result_str)['text']
if json.loads(result_str)['message_type']=='FinalTranscript':
print(result)
st.session_state['text'] = result
st.markdown(st.session_state['text'])
except websockets.exceptions.ConnectionClosedError as e:
print(e)
print('7')
assert e.code == 4008
break
except Exception as e:
print(e)
assert False, "Not a websocket 4008 error"
send_result, receive_result = await asyncio.gather(send(), receive())
asyncio.run(send_receive())