-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1271 lines (1133 loc) · 48.2 KB
/
Copy pathapp.py
File metadata and controls
1271 lines (1133 loc) · 48.2 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
# Copyright (C) 2024 LiveTalking@lipku https://github.com/lipku/LiveTalking
# email: lipku@foxmail.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# server.py
from flask import Flask, render_template,send_from_directory,request, jsonify
from flask_sockets import Sockets
import base64
import json
#import gevent
#from gevent import pywsgi
#from geventwebsocket.handler import WebSocketHandler
import re
import numpy as np
from threading import Thread,Event
#import multiprocessing
import torch.multiprocessing as mp
from aiohttp import web
import aiohttp
import aiohttp_cors
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc.rtcrtpsender import RTCRtpSender
from aiortc.rtcrtpparameters import RTCRtpEncodingParameters
from webrtc import HumanPlayer
from basereal import BaseReal
from llm import llm_response
import argparse
import random
import shutil
import asyncio
import torch
import os
import time
from typing import Dict, Optional
from logger import logger
from daily_bot import DailyBot, DailyBotConfig
import uuid
def _enable_h264_nvenc() -> bool:
try:
import fractions
import av
import aiortc.codecs as codecs
import aiortc.codecs.h264 as h264
except Exception as exc:
logger.info("NVENC init skipped: %s", exc)
return False
try:
av.CodecContext.create("h264_nvenc", "w")
except av.AVError as exc:
logger.info("NVENC not available: %s", exc)
return False
class H264EncoderNVENC(h264.H264Encoder):
def _encode_frame(self, frame, force_keyframe: bool):
if self.codec and (
frame.width != self.codec.width
or frame.height != self.codec.height
or abs(self.target_bitrate - self.codec.bit_rate) / self.codec.bit_rate
> 0.1
):
self.buffer_data = b""
self.buffer_pts = None
self.codec = None
if force_keyframe:
frame.pict_type = av.video.frame.PictureType.I
else:
frame.pict_type = av.video.frame.PictureType.NONE
if self.codec is None:
try:
codec = av.CodecContext.create("h264_nvenc", "w")
except av.AVError:
codec = av.CodecContext.create("libx264", "w")
codec.width = frame.width
codec.height = frame.height
codec.bit_rate = self.target_bitrate
codec.pix_fmt = "yuv420p"
codec.framerate = fractions.Fraction(h264.MAX_FRAME_RATE, 1)
codec.time_base = fractions.Fraction(1, h264.MAX_FRAME_RATE)
if codec.name == "h264_nvenc":
try:
codec.options = {
"preset": "p3",
"rc": "cbr",
"bf": "0",
"g": "60",
"tune": "ll",
}
except Exception:
codec.options = {}
try:
codec.profile = "baseline"
except Exception:
pass
else:
codec.options = {
"level": "31",
"tune": "zerolatency",
}
codec.profile = "Baseline"
self.codec = codec
data_to_send = b""
for package in self.codec.encode(frame):
data_to_send += bytes(package)
if data_to_send:
yield from self._split_bitstream(data_to_send)
h264.H264Encoder = H264EncoderNVENC
codecs.H264Encoder = H264EncoderNVENC
logger.info("Using NVENC H264 encoder")
return True
_H264_NVENC_ENABLED = _enable_h264_nvenc()
app = Flask(__name__)
#sockets = Sockets(app)
nerfreals:Dict[int, BaseReal] = {} #sessionid:BaseReal
opt = None
model = None
avatar = None
_default_config = {
"openai_key": "",
"openai_base": "",
"openai_model": "",
"openai_tts_model": "",
"openai_tts_voice": "",
"openai_tts_format": "",
"openai_tts_speed": None,
"openai_tts_sample_rate": None,
"assemblyai_key": "",
}
# WebRTC quality presets (bitrate in bps).
QUALITY_PROFILES = {
"emergency": {
"max_bitrate": 80_000,
"max_fps": 8,
"scale": 3.0,
"audio_bitrate": 16_000,
},
"very_low": {
"max_bitrate": 150_000,
"max_fps": 10,
"scale": 2.5,
"audio_bitrate": 20_000,
},
"low": {
"max_bitrate": 350_000,
"max_fps": 15,
"scale": 1.5,
"audio_bitrate": 24_000,
},
"balanced": {
"max_bitrate": 800_000,
"max_fps": 20,
"scale": 1.0,
"audio_bitrate": 32_000,
},
"high": {
"max_bitrate": 1_600_000,
"max_fps": 25,
"scale": 1.0,
"audio_bitrate": 48_000,
},
}
def _apply_video_quality(sender: RTCRtpSender, quality: str) -> None:
profile = QUALITY_PROFILES.get((quality or "").lower())
if not profile:
return
if not hasattr(sender, "getParameters") or not hasattr(sender, "setParameters"):
# Older aiortc versions don't support sender parameters; skip.
return
params = sender.getParameters()
if not params.encodings:
params.encodings = [RTCRtpEncodingParameters()]
enc = params.encodings[0]
if profile.get("max_bitrate"):
enc.maxBitrate = int(profile["max_bitrate"])
if profile.get("max_fps"):
enc.maxFramerate = int(profile["max_fps"])
if profile.get("scale"):
enc.scaleResolutionDownBy = float(profile["scale"])
sender.setParameters(params)
def _apply_audio_quality(sender: RTCRtpSender, quality: str) -> None:
profile = QUALITY_PROFILES.get((quality or "").lower())
if not profile:
return
if not hasattr(sender, "getParameters") or not hasattr(sender, "setParameters"):
return
params = sender.getParameters()
if not params.encodings:
params.encodings = [RTCRtpEncodingParameters()]
enc = params.encodings[0]
if profile.get("audio_bitrate"):
enc.maxBitrate = int(profile["audio_bitrate"])
sender.setParameters(params)
def _parse_fmtp(params: str) -> dict:
result = {}
if not params:
return result
for item in params.split(";"):
item = item.strip()
if not item:
continue
if "=" in item:
key, value = item.split("=", 1)
result[key.strip()] = value.strip()
else:
result[item] = "1"
return result
def _format_fmtp(params: dict) -> str:
items = []
for key in sorted(params.keys()):
value = params[key]
if value is None or value == "":
items.append(key)
else:
items.append(f"{key}={value}")
return ";".join(items)
def _tune_audio_sdp(sdp: str) -> str:
lines = sdp.splitlines()
opus_pts = []
for line in lines:
if line.startswith("a=rtpmap:") and " opus/" in line.lower():
pt = line.split(":", 1)[1].split(" ", 1)[0]
opus_pts.append(pt)
if not opus_pts:
return sdp
tuned = []
opus_pt_set = set(opus_pts)
inserted = set()
for idx, line in enumerate(lines):
if line.startswith("a=fmtp:"):
pt = line.split(":", 1)[1].split(" ", 1)[0]
if pt in opus_pt_set:
params = ""
if " " in line:
params = line.split(" ", 1)[1]
fmtp = _parse_fmtp(params)
fmtp.update(
{
"useinbandfec": "1",
"cbr": "1",
"maxaveragebitrate": "64000",
"maxplaybackrate": "16000",
"minptime": "10",
"maxptime": "20",
"ptime": "20",
"stereo": "0",
}
)
line = f"a=fmtp:{pt} {_format_fmtp(fmtp)}"
inserted.add(pt)
tuned.append(line)
if line.startswith("a=rtpmap:"):
pt = line.split(":", 1)[1].split(" ", 1)[0]
if pt in opus_pt_set and pt not in inserted:
fmtp = _format_fmtp(
{
"useinbandfec": "1",
"cbr": "1",
"maxaveragebitrate": "64000",
"maxplaybackrate": "16000",
"minptime": "10",
"maxptime": "20",
"ptime": "20",
"stereo": "0",
}
)
tuned.append(f"a=fmtp:{pt} {fmtp}")
inserted.add(pt)
return "\r\n".join(tuned) + "\r\n"
def _apply_video_overrides(sender: RTCRtpSender, overrides: dict) -> None:
if not hasattr(sender, "getParameters") or not hasattr(sender, "setParameters"):
return
params = sender.getParameters()
if not params.encodings:
params.encodings = [RTCRtpEncodingParameters()]
enc = params.encodings[0]
if overrides.get("max_bitrate") is not None:
enc.maxBitrate = int(overrides["max_bitrate"])
if overrides.get("max_fps") is not None:
enc.maxFramerate = int(overrides["max_fps"])
if overrides.get("scale") is not None:
enc.scaleResolutionDownBy = float(overrides["scale"])
sender.setParameters(params)
def _load_secrets(path: str):
if not path:
return
try:
secrets_path = os.path.expanduser(path)
if not os.path.isfile(secrets_path):
return
with open(secrets_path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
logger.info(f"Failed to load secrets file: {e}")
return
def _pick(*keys):
for k in keys:
if k in data and data[k] not in (None, ""):
return str(data[k]).strip()
return ""
openai_key = _pick("openai_key", "openai_api_key", "OPENAI_API_KEY")
openai_base = _pick("openai_base", "openai_base_url", "OPENAI_BASE_URL")
openai_model = _pick("openai_model", "OPENAI_MODEL")
openai_tts_model = _pick("openai_tts_model", "OPENAI_TTS_MODEL")
openai_tts_voice = _pick("openai_tts_voice", "OPENAI_TTS_VOICE")
openai_tts_format = _pick("openai_tts_format", "OPENAI_TTS_FORMAT")
openai_tts_speed = data.get("openai_tts_speed", data.get("OPENAI_TTS_SPEED"))
openai_tts_sample_rate = data.get("openai_tts_sample_rate", data.get("OPENAI_TTS_SAMPLE_RATE"))
assemblyai_key = _pick("assemblyai_key", "assemblyai_api_key", "ASSEMBLYAI_API_KEY")
if openai_key:
_default_config["openai_key"] = openai_key
if openai_base:
_default_config["openai_base"] = openai_base
if openai_model:
_default_config["openai_model"] = openai_model
if openai_tts_model:
_default_config["openai_tts_model"] = openai_tts_model
if openai_tts_voice:
_default_config["openai_tts_voice"] = openai_tts_voice
if openai_tts_format:
_default_config["openai_tts_format"] = openai_tts_format
if openai_tts_speed is not None:
try:
_default_config["openai_tts_speed"] = float(openai_tts_speed)
except Exception:
pass
if openai_tts_sample_rate is not None:
try:
_default_config["openai_tts_sample_rate"] = int(openai_tts_sample_rate)
except Exception:
pass
if assemblyai_key:
_default_config["assemblyai_key"] = assemblyai_key
#####webrtc###############################
pcs = set()
pcs_by_session: Dict[int, RTCPeerConnection] = {}
video_senders_by_session: Dict[int, RTCRtpSender] = {}
audio_senders_by_session: Dict[int, RTCRtpSender] = {}
daily_sessions: Dict[int, dict] = {}
def randN(N)->int:
'''生成长度为 N的随机数 '''
min = pow(10, N - 1)
max = pow(10, N)
return random.randint(min, max - 1)
def build_nerfreal(sessionid:int)->BaseReal:
opt.sessionid=sessionid
if opt.model == 'wav2lip':
from lipreal import LipReal
nerfreal = LipReal(opt,model,avatar)
elif opt.model == 'musetalk':
from musereal import MuseReal
nerfreal = MuseReal(opt,model,avatar)
elif opt.model == 'ernerf':
from nerfreal import NeRFReal
nerfreal = NeRFReal(opt,model,avatar)
elif opt.model == 'ultralight':
from lightreal import LightReal
nerfreal = LightReal(opt,model,avatar)
# apply cached defaults (if any)
if _default_config.get("openai_key"):
nerfreal.openai_api_key = _default_config["openai_key"]
if _default_config.get("openai_base"):
nerfreal.openai_base_url = _default_config["openai_base"]
if _default_config.get("openai_model"):
nerfreal.openai_model = _default_config["openai_model"]
if _default_config.get("openai_tts_model"):
nerfreal.openai_tts_model = _default_config["openai_tts_model"]
if _default_config.get("openai_tts_voice"):
nerfreal.openai_tts_voice = _default_config["openai_tts_voice"]
if _default_config.get("openai_tts_format"):
nerfreal.openai_tts_format = _default_config["openai_tts_format"]
if _default_config.get("openai_tts_speed") is not None:
nerfreal.openai_tts_speed = _default_config["openai_tts_speed"]
if _default_config.get("openai_tts_sample_rate") is not None:
nerfreal.openai_tts_sample_rate = _default_config["openai_tts_sample_rate"]
return nerfreal
def _daily_domain() -> str:
return os.getenv("DAILY_DOMAIN", "").strip()
def _daily_api_key() -> str:
return os.getenv("DAILY_API_KEY", "").strip()
async def _daily_api_request(method: str, path: str, payload: dict | None = None) -> Optional[dict]:
api_key = _daily_api_key()
if not api_key:
logger.info("Daily API key missing.")
return None
url = f"https://api.daily.co/v1/{path.lstrip('/')}"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
try:
async with aiohttp.ClientSession() as session:
async with session.request(method, url, json=payload, headers=headers) as response:
text = await response.text()
if response.status not in (200, 201):
logger.info("Daily API error %s: %s", response.status, text[:200])
return None
if not text:
return {}
return json.loads(text)
except Exception as exc:
logger.info("Daily API request failed: %s", exc)
return None
async def _daily_create_room(name: str) -> Optional[dict]:
ttl = int(os.getenv("DAILY_ROOM_TTL", "7200"))
payload = {
"name": name,
"privacy": "private",
"properties": {
"exp": int(time.time()) + ttl,
},
}
data = await _daily_api_request("post", "rooms", payload)
if data:
return data
# Fallback: try to fetch existing room
return await _daily_api_request("get", f"rooms/{name}")
async def _daily_delete_room(name: str) -> None:
api_key = _daily_api_key()
if not api_key:
return
url = f"https://api.daily.co/v1/rooms/{name}"
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
try:
async with aiohttp.ClientSession() as session:
async with session.delete(url, headers=headers):
return
except Exception:
return
async def _daily_create_token(room_name: str, user_name: str, is_owner: bool) -> Optional[str]:
ttl = int(os.getenv("DAILY_TOKEN_TTL", "7200"))
payload = {
"properties": {
"room_name": room_name,
"user_name": user_name,
"is_owner": is_owner,
"exp": int(time.time()) + ttl,
}
}
data = await _daily_api_request("post", "meeting-tokens", payload)
if not data:
return None
return data.get("token")
#@app.route('/offer', methods=['POST'])
async def offer(request):
return web.Response(
content_type="application/json",
status=410,
text=json.dumps({"code": -1, "msg": "WebRTC offer disabled (Daily only)"}),
)
async def daily_start(request):
params = await request.json()
if len(nerfreals) >= opt.max_session:
return web.Response(
content_type="application/json",
status=429,
text=json.dumps({"code": -1, "msg": "reach max session"}),
)
domain = _daily_domain()
if not domain or not _daily_api_key():
return web.Response(
content_type="application/json",
status=500,
text=json.dumps({"code": -1, "msg": "Daily not configured"}),
)
if opt.transport != "daily":
opt.transport = "daily"
sessionid = randN(6)
logger.info("daily sessionid=%d", sessionid)
nerfreals[sessionid] = None
try:
nerfreal = await asyncio.get_event_loop().run_in_executor(None, build_nerfreal, sessionid)
except Exception:
logger.exception("build_nerfreal failed")
nerfreals.pop(sessionid, None)
return web.Response(
content_type="application/json",
status=500,
text=json.dumps({"code": -1, "msg": "Failed to build avatar"}),
)
if nerfreal is None:
nerfreals.pop(sessionid, None)
return web.Response(
content_type="application/json",
status=500,
text=json.dumps({"code": -1, "msg": "Failed to build avatar"}),
)
nerfreals[sessionid] = nerfreal
room_name = f"avatar-{sessionid}-{uuid.uuid4().hex[:6]}"
room = await _daily_create_room(room_name)
if not room:
nerfreals.pop(sessionid, None)
return web.Response(
content_type="application/json",
status=502,
text=json.dumps({"code": -1, "msg": "Failed to create Daily room"}),
)
room_url = room.get("url") or f"https://{domain}/{room_name}"
viewer_token = await _daily_create_token(room_name, "viewer", False)
bot_token = await _daily_create_token(room_name, f"avatar-{sessionid}", True)
if not viewer_token or not bot_token:
nerfreals.pop(sessionid, None)
await _daily_delete_room(room_name)
return web.Response(
content_type="application/json",
status=502,
text=json.dumps({"code": -1, "msg": "Failed to create Daily token"}),
)
audio_rate = int(os.getenv("DAILY_AUDIO_RATE", "16000"))
audio_bitrate = int(os.getenv("DAILY_AUDIO_BITRATE", "64000"))
video_quality = os.getenv("DAILY_VIDEO_QUALITY", "high")
preferred_codec = os.getenv("DAILY_VIDEO_CODEC", "H264")
video_width = int(os.getenv("DAILY_VIDEO_WIDTH", str(nerfreal.W)))
video_height = int(os.getenv("DAILY_VIDEO_HEIGHT", str(nerfreal.H)))
video_fps = int(os.getenv("DAILY_VIDEO_FPS", "25"))
quality_auto = os.getenv("DAILY_QUALITY_AUTO", "1").strip() != "0"
bot = DailyBot(
DailyBotConfig(
room_url=room_url,
meeting_token=bot_token,
width=video_width,
height=video_height,
fps=video_fps,
sample_rate=audio_rate,
user_name=f"avatar-{sessionid}",
video_quality=video_quality,
preferred_codec=preferred_codec,
audio_bitrate=audio_bitrate,
quality_auto=quality_auto,
)
)
if not bot.wait_ready(15) or bot.error:
err = bot.error or "Daily bot join timeout"
bot.close()
nerfreals.pop(sessionid, None)
await _daily_delete_room(room_name)
return web.Response(
content_type="application/json",
status=502,
text=json.dumps({"code": -1, "msg": err}),
)
quit_event = Event()
render_thread = Thread(
target=nerfreal.render,
args=(quit_event, None, None, None, bot),
daemon=True,
)
render_thread.start()
daily_sessions[sessionid] = {
"bot": bot,
"quit": quit_event,
"thread": render_thread,
"room_name": room_name,
"room_url": room_url,
}
return web.Response(
content_type="application/json",
text=json.dumps({"code": 0, "sessionid": sessionid, "room_url": room_url, "token": viewer_token}),
)
async def human(request):
params = await request.json()
sessionid = params.get('sessionid',0)
if params.get('interrupt'):
nerfreals[sessionid].flush_talk()
if params['type']=='echo':
nerfreals[sessionid].put_msg_txt(params['text'])
elif params['type']=='chat':
try:
res=await asyncio.get_event_loop().run_in_executor(None, llm_response, params['text'],nerfreals[sessionid])
#nerfreals[sessionid].put_msg_txt(res)
except Exception as e:
# Do not echo the user's message on LLM errors.
logger.info(f'LLM error, no echo: {e}')
return web.Response(
status=500,
content_type="application/json",
text=json.dumps({"code": -1, "msg": "LLM error"}),
)
payload = {"code": 0, "data": "ok"}
if params.get('type') == 'chat':
payload["reply"] = res if isinstance(res, str) else ""
return web.Response(
content_type="application/json",
text=json.dumps(payload),
)
async def humanaudio(request):
try:
form= await request.post()
sessionid = int(form.get('sessionid',0))
fileobj = form["file"]
filename=fileobj.filename
filebytes=fileobj.file.read()
nerfreals[sessionid].put_audio_file(filebytes)
return web.Response(
content_type="application/json",
text=json.dumps(
{"code": 0, "msg":"ok"}
),
)
except Exception as e:
return web.Response(
content_type="application/json",
text=json.dumps(
{"code": -1, "msg":"err","data": ""+e.args[0]+""}
),
)
async def set_audiotype(request):
params = await request.json()
sessionid = params.get('sessionid',0)
nerfreals[sessionid].set_custom_state(params['audiotype'],params['reinit'])
return web.Response(
content_type="application/json",
text=json.dumps(
{"code": 0, "data":"ok"}
),
)
async def config(request):
params = await request.json()
sessionid = params.get('sessionid', 0)
nerfreal = nerfreals.get(sessionid)
# allow storing defaults before session exists
if nerfreal is None and sessionid:
return web.Response(
content_type="application/json",
text=json.dumps({"code": -1, "msg": "invalid session"}),
)
# LLM settings
if 'openai_key' in params:
value = (params.get('openai_key') or "").strip()
_default_config["openai_key"] = value
if nerfreal:
nerfreal.openai_api_key = value
if 'openai_base' in params:
value = (params.get('openai_base') or "").strip()
_default_config["openai_base"] = value
if nerfreal:
nerfreal.openai_base_url = value
if 'openai_model' in params:
model = (params.get('openai_model') or "").strip()
if model:
_default_config["openai_model"] = model
if nerfreal:
nerfreal.openai_model = model
if 'openai_tts_model' in params:
model = (params.get('openai_tts_model') or "").strip()
if model:
_default_config["openai_tts_model"] = model
if nerfreal:
nerfreal.openai_tts_model = model
if 'openai_tts_voice' in params:
value = (params.get('openai_tts_voice') or "").strip()
if value:
_default_config["openai_tts_voice"] = value
if nerfreal:
nerfreal.openai_tts_voice = value
if 'openai_tts_format' in params:
value = (params.get('openai_tts_format') or "").strip()
if value:
_default_config["openai_tts_format"] = value
if nerfreal:
nerfreal.openai_tts_format = value
if 'openai_tts_speed' in params:
try:
value = float(params.get('openai_tts_speed'))
_default_config["openai_tts_speed"] = value
if nerfreal:
nerfreal.openai_tts_speed = value
except Exception:
pass
if 'openai_tts_sample_rate' in params:
try:
value = int(params.get('openai_tts_sample_rate'))
_default_config["openai_tts_sample_rate"] = value
if nerfreal:
nerfreal.openai_tts_sample_rate = value
except Exception:
pass
if 'assemblyai_key' in params:
value = (params.get('assemblyai_key') or "").strip()
_default_config["assemblyai_key"] = value
return web.Response(
content_type="application/json",
text=json.dumps({"code": 0, "data": "ok"}),
)
async def assemblyai_token(request):
key = (_default_config.get("assemblyai_key") or "").strip()
if not key:
return web.Response(
status=400,
content_type="application/json",
text=json.dumps({"code": -1, "msg": "AssemblyAI key not configured"}),
)
try:
params = await request.json()
except Exception:
params = {}
expires = params.get("expires_in_seconds", 120)
try:
expires = int(expires)
except Exception:
expires = 120
expires = max(60, min(expires, 3600))
url = f"https://streaming.assemblyai.com/v3/token?expires_in_seconds={expires}"
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, headers={"Authorization": key}) as resp:
raw = await resp.text()
if resp.status != 200:
return web.Response(
status=resp.status,
content_type="application/json",
text=json.dumps({"code": -1, "msg": "AssemblyAI token request failed", "detail": raw}),
)
data = json.loads(raw)
except Exception as e:
return web.Response(
status=500,
content_type="application/json",
text=json.dumps({"code": -1, "msg": f"AssemblyAI token error: {e}"}),
)
token = data.get("token") or data.get("temporary_token")
if not token:
return web.Response(
status=500,
content_type="application/json",
text=json.dumps({"code": -1, "msg": "AssemblyAI token missing"}),
)
return web.Response(
content_type="application/json",
text=json.dumps(
{
"code": 0,
"token": token,
"expires_in_seconds": data.get("expires_in_seconds", expires),
}
),
)
async def webrtc_quality(request):
params = await request.json()
sessionid = int(params.get('sessionid', 0))
video_sender = video_senders_by_session.get(sessionid)
audio_sender = audio_senders_by_session.get(sessionid)
if not video_sender and not audio_sender:
return web.Response(
content_type="application/json",
status=410,
text=json.dumps({"code": -1, "msg": "session expired"}),
)
quality = params.get("quality")
if quality:
if video_sender:
_apply_video_quality(video_sender, quality)
if audio_sender:
_apply_audio_quality(audio_sender, quality)
else:
overrides = {}
if params.get("max_bitrate") is not None:
try:
overrides["max_bitrate"] = int(params.get("max_bitrate"))
except Exception:
pass
if params.get("max_fps") is not None:
try:
overrides["max_fps"] = int(params.get("max_fps"))
except Exception:
pass
if params.get("scale") is not None:
try:
overrides["scale"] = float(params.get("scale"))
except Exception:
pass
if overrides:
if video_sender:
_apply_video_overrides(video_sender, overrides)
return web.Response(
content_type="application/json",
text=json.dumps({"code": 0, "data": "ok"}),
)
async def record(request):
params = await request.json()
sessionid = params.get('sessionid',0)
if params['type']=='start_record':
# nerfreals[sessionid].put_msg_txt(params['text'])
nerfreals[sessionid].start_recording()
elif params['type']=='end_record':
nerfreals[sessionid].stop_recording()
return web.Response(
content_type="application/json",
text=json.dumps(
{"code": 0, "data":"ok"}
),
)
async def is_speaking(request):
params = await request.json()
sessionid = params.get('sessionid',0)
return web.Response(
content_type="application/json",
text=json.dumps(
{"code": 0, "data": nerfreals[sessionid].is_speaking()}
),
)
async def end_session(request):
params = await request.json()
sessionid = int(params.get('sessionid', 0))
if sessionid:
pc = pcs_by_session.pop(sessionid, None)
if pc:
try:
await pc.close()
except Exception:
pass
pcs.discard(pc)
video_senders_by_session.pop(sessionid, None)
audio_senders_by_session.pop(sessionid, None)
daily = daily_sessions.pop(sessionid, None)
if daily:
try:
daily.get("quit").set()
except Exception:
pass
try:
if daily.get("thread"):
daily.get("thread").join(timeout=2)
except Exception:
pass
try:
daily.get("bot").close()
except Exception:
pass
try:
room_name = daily.get("room_name")
if room_name:
await _daily_delete_room(room_name)
except Exception:
pass
nerfreal = nerfreals.get(sessionid)
if nerfreal:
try:
nerfreal.flush_talk()
except Exception:
pass
del nerfreals[sessionid]
return web.Response(
content_type="application/json",
text=json.dumps({"code": 0, "msg": "ended"}),
)
async def health(request):
return web.Response(text="ok")
async def on_shutdown(app):
# close peer connections
coros = [pc.close() for pc in pcs]
await asyncio.gather(*coros)
pcs.clear()
pcs_by_session.clear()
video_senders_by_session.clear()
audio_senders_by_session.clear()
for sessionid, daily in list(daily_sessions.items()):
try:
daily.get("quit").set()
except Exception:
pass
try:
if daily.get("thread"):
daily.get("thread").join(timeout=2)
except Exception:
pass
try:
daily.get("bot").close()
except Exception:
pass
try:
room_name = daily.get("room_name")
if room_name:
await _daily_delete_room(room_name)
except Exception:
pass
daily_sessions.pop(sessionid, None)
audio_senders_by_session.clear()
async def post(url,data):
try:
async with aiohttp.ClientSession() as session:
async with session.post(url,data=data) as response:
return await response.text()
except aiohttp.ClientError as e:
logger.info(f'Error: {e}')
async def run(push_url,sessionid):
nerfreal = await asyncio.get_event_loop().run_in_executor(None, build_nerfreal,sessionid)
nerfreals[sessionid] = nerfreal
pc = RTCPeerConnection()
pcs.add(pc)
@pc.on("connectionstatechange")
async def on_connectionstatechange():
logger.info("Connection state is %s" % pc.connectionState)
if pc.connectionState == "failed":
await pc.close()
pcs.discard(pc)