-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathserver.py
100 lines (74 loc) · 2.75 KB
/
server.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
import argparse
import json
import logging
import ssl
import sys
from pathlib import Path
from aiohttp import web
from aiohttp.web_exceptions import HTTPServiceUnavailable
from aiortc import RTCSessionDescription, RTCPeerConnection
from kaldi import KaldiSink, kaldi_server_queue
ROOT = Path(__file__).parent
root = logging.getLogger()
root.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] %(name)s <%(levelname)s> %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
async def index(request):
content = open(str(ROOT / 'static' / 'index.html')).read()
return web.Response(content_type='text/html', text=content)
async def offer(request):
kaldi_server = await kaldi_server_queue.get()
if not kaldi_server:
raise HTTPServiceUnavailable()
params = await request.json()
offer = RTCSessionDescription(
sdp=params['sdp'],
type=params['type'])
pc = RTCPeerConnection()
kaldi = KaldiSink(pc, kaldi_server)
@pc.on('datachannel')
async def on_datachannel(channel):
await kaldi.set_text_channel(channel)
@pc.on('iceconnectionstatechange')
async def on_iceconnectionstatechange():
if pc.iceConnectionState == 'failed':
await pc.close()
@pc.on('track')
async def on_track(track):
if track.kind == 'audio':
await kaldi.set_audio_track(track)
@track.on('ended')
async def on_ended():
await kaldi.stop()
await pc.setRemoteDescription(offer)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
await kaldi.start()
return web.Response(
content_type='application/json',
text=json.dumps({
'sdp': pc.localDescription.sdp,
'type': pc.localDescription.type
}))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--servers', help='Server configuration JSON')
parser.add_argument('--cert-file', help='SSL certificate file (for HTTPS)')
parser.add_argument('--key-file', help='SSL key file (for HTTPS)')
parser.add_argument('--port', type=int, default=8080,
help='Port for HTTP server (default: 8080)')
args = parser.parse_args()
if args.cert_file:
ssl_context = ssl.SSLContext()
ssl_context.load_cert_chain(args.cert_file, args.key_file)
else:
ssl_context = None
app = web.Application()
app.router.add_get('/', index)
app.router.add_post('/offer', offer)
app.router.add_static('/static/', path=ROOT / 'static', name='static')
kaldi_server_queue.load(args.servers)
web.run_app(app, port=args.port, ssl_context=ssl_context)