-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobs_live_captions.py
executable file
·302 lines (242 loc) · 7.93 KB
/
obs_live_captions.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
#!/usr/bin/env python3
import asyncio
import json
import os
import subprocess
import sys
import time
import websockets
from datetime import datetime
from flask import Flask, request, Response
from pathlib import Path
######################################################################
# Config
######################################################################
domain = 'localhost'
http_port = '5050'
ws_port = '5051'
transcript_dir = os.path.join(Path.home(), 'obs-live-transcripts')
font_color = "#bbbbbb"
font_family = 'Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Georgia, serif'
container_height = "7.2rem"
container_width = "10rem"
#######################################################################
### Pathing
python_path = sys.executable
script_path = os.path.realpath(__file__)
### Setup transcript
Path(transcript_dir).mkdir(parents=True, exist_ok=True)
transcript_file_name = f'obs-live-transcript-{datetime.now().strftime("%Y-%m-%d--%H-%M-%S")}.txt'
transcript_file_path = f'{transcript_dir}/{transcript_file_name}'
def write_to_transcript(text):
with open(transcript_file_path, 'a') as _file:
_file.write(f"{datetime.now().strftime('%Y-%m-%d--%H-%M-%S')} ~ ")
_file.write(f"{text.strip()}\n\n")
### Flask Stuff
app = Flask(__name__)
@app.route('/', methods=['GET'])
def home_page():
main_html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OBS Live Captions</title>
<style>
body {
background: #eee;
font-family: Sans-Serif;
}
.container {
height: 3.4rem;
width: 20rem;
position: relative;
overflow: hidden;
border: 1px solid black;
padding: 2px;
}
.content {
color: #000;
position: absolute;
bottom: 0;
}
</style>
</head>
<body>
<h3>OBS Live Captions</h3>
<p>To use the live captions:
<ol>
<li>Click 'Allow' when the browser asks to use your microphone'</li>
<li>Create a new Browser Source in OBS with <a href="/obs">this link</a> and crop in to the outlined box on it.</li>
</ol>
<p>You can also configure the display formatting in the config section towards the top of the .py file</p>
<div class="container">
<div class="content" id="transcript"></div>
</div>
<hr>
<p><a href="/obs" target="_blank">Open page for OBS Browser Source</a></p>
<script>
let safe_to_send = false
"""
main_html += f'let ws = new WebSocket("ws://{domain}:{ws_port}/");'
main_html += """
ws.addEventListener('open', (event) => {
safe_to_send = true
})
let restart = true
let ts = document.getElementById('transcript')
try {
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var recognition = new SpeechRecognition();
recognition.continuous = true;
recognition.lang = 'en-US';
recognition.interimResults = true;
recognition.maxAlternatives = 1;
document.addEventListener("DOMContentLoaded", recognition.start());
// Restart if the service stops
recognition.addEventListener("end", function () {
console.log("restarting process");
recognition.start();
})
let results_counter = 0
let long_text = ""
// let count_of_results = 0
let active_index = 0
recognition.onresult = function(event) {
results_counter += 1;
let isFinal = true
let new_text = "";
for (let i = 0; i < event.results.length; i = i + 1) {
if (event.results[i].isFinal == false) {
if (i > active_index){
long_text = ""
active_index = i
}
isFinal = false
new_text = event.results[i][0].transcript;
break;
}
}
if (isFinal === true) {
last_result_index = event.results.length - 1;
new_text = event.results[last_result_index][0].transcript;
long_text = ""
ts.innerHTML = new_text
if (safe_to_send) {
ws.send(`{"text": "${new_text}", "isFinal": true }`)
}
}
else if (new_text.length > long_text.length) {
long_text = new_text
ts.innerHTML = new_text
if (safe_to_send) {
ws.send(`{"text": "${new_text}", "isFinal": false }`)
}
}
}
} catch (error) {
ts.innerHTML = "This browser doesn't support the necessary WebSpeech API. Try using Google Chrome";
}
</script>
</body>
</html>
"""
return Response(
status=200,
response=main_html
)
@app.route('/obs', methods=['GET'])
def obs_page():
obs_html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Captions For OBS</title>
<style>
body {
background: rgba(180, 180, 0, 0);
font-family: Sans-Serif;
}
.container {
"""
obs_html += f"font-family: {font_family};\n"
obs_html += f"height: {container_height};\n"
obs_html += f"width: {container_width};\n"
obs_html += """
position: relative;
overflow: hidden;
padding: 1rem;
border: 1px solid gray;
}
.content {
"""
obs_html += f"color: {font_color};\n"
obs_html += """
position: absolute;
bottom: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="content" id="transcript"></div>
</div>
<script>
"""
obs_html += f'const ws = new WebSocket("ws://{domain}:{ws_port}/")'
obs_html += """
ws.onmessage = function (event) {
document.getElementById('transcript').innerHTML = event.data
}
</script>
</body>
</html>
"""
return Response(
status=200,
response=obs_html
)
### Websocket stuff
CONNECTIONS = set()
async def register(websocket):
CONNECTIONS.add(websocket)
async def unregister(websocket):
CONNECTIONS.remove(websocket)
async def notify_users(message, websocket):
connection_list = []
for connection in CONNECTIONS:
connection_list.append(connection)
await asyncio.wait([
connection.send(message) for connection in connection_list
])
async def message_control(websocket, path):
await register(websocket)
try:
await websocket.send("Connected")
async for message in websocket:
print(message)
message_data = json.loads(message)
if message_data['isFinal']:
write_to_transcript(message_data['text'])
await notify_users(message_data['text'], websocket)
finally:
await unregister(websocket)
if len(sys.argv) == 2:
if sys.argv[1] == 'run_websockets':
print("\nStarting websocket server")
start_server = websockets.serve(message_control, domain, ws_port)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
else:
time.sleep(1)
print("Triggering websocket server")
return_value = (subprocess.Popen([
python_path,
script_path,
'run_websockets'
]))
print("Starting flask web server")
app.run(port=http_port)