forked from sandboxdream/AI-Vtuber
-
Notifications
You must be signed in to change notification settings - Fork 479
/
main.py
4050 lines (3371 loc) · 166 KB
/
main.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
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
import os
import threading
import schedule
import random
import asyncio, aiohttp
import traceback
import copy
import json, re
from functools import partial
import http.cookies
from typing import *
# 按键监听语音聊天板块
import keyboard
import pyaudio
import wave
import numpy as np
import speech_recognition as sr
from aip import AipSpeech
import signal
import time
import http.server
import socketserver
from utils.my_log import logger
from utils.common import Common
from utils.config import Config
from utils.my_handle import My_handle
"""
___ _
|_ _| | ____ _ _ __ ___ ___
| || |/ / _` | '__/ _ \/ __|
| || < (_| | | | (_) \__ \
|___|_|\_\__,_|_| \___/|___/
"""
config = None
common = None
my_handle = None
last_liveroom_data = None
last_username_list = None
# 空闲时间计数器
global_idle_time = 0
# 配置文件路径
config_path = "config.json"
# web服务线程
async def web_server_thread(web_server_port):
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", web_server_port), Handler) as httpd:
logger.info(f"Web运行在端口:{web_server_port}")
logger.info(
f"可以直接访问Live2D页, http://127.0.0.1:{web_server_port}/Live2D/"
)
httpd.serve_forever()
"""
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
佛祖保佑 永不宕机 永无BUG
"""
# 点火起飞
def start_server():
global \
config, \
common, \
my_handle, \
last_username_list, \
config_path, \
last_liveroom_data
global do_listen_and_comment_thread, stop_do_listen_and_comment_thread_event
global faster_whisper_model, sense_voice_model, is_recording, is_talk_awake, wait_play_audio_num
# 按键监听相关
do_listen_and_comment_thread = None
stop_do_listen_and_comment_thread_event = threading.Event()
# 冷却时间 0.5 秒
cooldown = 0.5
last_pressed = 0
# 正在录音中 标志位
is_recording = False
# 聊天是否唤醒
is_talk_awake = False
# 待播放音频数量(在使用 音频播放器 或者 metahuman-stream等不通过AI Vtuber播放音频的对接项目时,使用此变量记录是是否还有音频没有播放完)
wait_play_audio_num = 0
# 获取 httpx 库的日志记录器
# httpx_logger = logging.getLogger("httpx")
# 设置 httpx 日志记录器的级别为 WARNING
# httpx_logger.setLevel(logging.WARNING)
# 最新的直播间数据
last_liveroom_data = {
"OnlineUserCount": 0,
"TotalUserCount": 0,
"TotalUserCountStr": "0",
"OnlineUserCountStr": "0",
"MsgId": 0,
"User": None,
"Content": "当前直播间人数 0,累计直播间人数 0",
"RoomId": 0,
}
# 最新入场的用户名列表
last_username_list = [""]
my_handle = My_handle(config_path)
if my_handle is None:
logger.error("程序初始化失败!")
os._exit(0)
# Live2D线程
try:
if config.get("live2d", "enable"):
web_server_port = int(config.get("live2d", "port"))
threading.Thread(
target=lambda: asyncio.run(web_server_thread(web_server_port))
).start()
except Exception as e:
logger.error(traceback.format_exc())
os._exit(0)
if platform != "wxlive":
"""
/@@@@@@@@ @@@@@@@@@@@@@@@]. =@@@@@@@
=@@@@@@@@@^ @@@@@@@@@@@@@@@@@@` =@@@@@@@
,@@@@@@@@@@@` @@@@@@@@@@@@@@@@@@@^ =@@@@@@@
.@@@@@@\@@@@@@. @@@@@@@^ .\@@@@@@\ =@@@@@@@
/@@@@@/ \@@@@@\ @@@@@@@^ =@@@@@@@ =@@@@@@@
=@@@@@@. .@@@@@@^ @@@@@@@\]]]@@@@@@@@^ =@@@@@@@
,@@@@@@^ =@@@@@@` @@@@@@@@@@@@@@@@@@/ =@@@@@@@
.@@@@@@@@@@@@@@@@@@@. @@@@@@@@@@@@@@@@/` =@@@@@@@
/@@@@@@@@@@@@@@@@@@@\ @@@@@@@^ =@@@@@@@
=@@@@@@@@@@@@@@@@@@@@@^ @@@@@@@^ =@@@@@@@
,@@@@@@@. ,@@@@@@@` @@@@@@@^ =@@@@@@@
@@@@@@@^ =@@@@@@@. @@@@@@@^ =@@@@@@@
"""
# HTTP API线程
def http_api_thread():
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from utils.models import (
SendMessage,
LLMMessage,
CallbackMessage,
CommonResult,
)
# 定义FastAPI应用
app = FastAPI()
# 允许跨域
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 定义POST请求路径和处理函数
@app.post("/send")
async def send(msg: SendMessage):
global my_handle, config
try:
tmp_json = msg.dict()
logger.info(f"内部HTTP API send接口收到数据:{tmp_json}")
data_json = tmp_json["data"]
if "type" not in data_json:
data_json["type"] = tmp_json["type"]
if data_json["type"] in ["reread", "reread_top_priority"]:
my_handle.reread_handle(data_json, type=data_json["type"])
elif data_json["type"] == "comment":
my_handle.process_data(data_json, "comment")
elif data_json["type"] == "tuning":
my_handle.tuning_handle(data_json)
elif data_json["type"] == "gift":
my_handle.gift_handle(data_json)
elif data_json["type"] == "entrance":
my_handle.entrance_handle(data_json)
return CommonResult(code=200, message="成功")
except Exception as e:
logger.error(f"发送数据失败!{e}")
return CommonResult(code=-1, message=f"发送数据失败!{e}")
@app.post("/llm")
async def llm(msg: LLMMessage):
global my_handle, config
try:
data_json = msg.dict()
logger.info(f"API收到数据:{data_json}")
resp_content = my_handle.llm_handle(
data_json["type"], data_json, webui_show=False
)
return CommonResult(
code=200, message="成功", data={"content": resp_content}
)
except Exception as e:
logger.error(f"调用LLM失败!{e}")
return CommonResult(code=-1, message=f"调用LLM失败!{e}")
@app.post("/callback")
async def callback(msg: CallbackMessage):
global my_handle, config, global_idle_time, wait_play_audio_num
try:
data_json = msg.dict()
# 特殊回调特殊处理
if data_json["type"] == "audio_playback_completed":
wait_play_audio_num = int(data_json["data"]["wait_play_audio_num"])
wait_synthesis_msg_num = int(data_json["data"]["wait_synthesis_msg_num"])
logger.info(f"内部HTTP API callback接口 音频播放完成回调,待播放音频数量:{wait_play_audio_num},待合成消息数量:{wait_synthesis_msg_num}")
else:
logger.info(f"内部HTTP API callback接口收到数据:{data_json}")
# 音频播放完成
if data_json["type"] in ["audio_playback_completed"]:
wait_play_audio_num = int(data_json["data"]["wait_play_audio_num"])
# 如果等待播放的音频数量大于10
if data_json["data"]["wait_play_audio_num"] > int(
config.get(
"idle_time_task", "wait_play_audio_num_threshold"
)
):
logger.info(
f'等待播放的音频数量大于限定值,闲时任务的闲时计时由 {global_idle_time} -> {int(config.get("idle_time_task", "idle_time_reduce_to"))}秒'
)
# 闲时任务的闲时计时 清零
global_idle_time = int(
config.get("idle_time_task", "idle_time_reduce_to")
)
return CommonResult(code=200, message="callback处理成功!")
except Exception as e:
logger.error(f"callback处理失败!{e}")
return CommonResult(code=-1, message=f"callback处理失败!{e}")
logger.info("HTTP API线程已启动!")
uvicorn.run(app, host="0.0.0.0", port=config.get("api_port"))
# HTTP API线程并启动
inside_http_api_thread = threading.Thread(target=http_api_thread)
inside_http_api_thread.start()
# 添加用户名到最新的用户名列表
def add_username_to_last_username_list(data):
"""
data(str): 用户名
"""
global last_username_list
# 添加数据到 最新入场的用户名列表
last_username_list.append(data)
# 保留最新的3个数据
last_username_list = last_username_list[-3:]
"""
按键监听板块
"""
# 录音功能(录音时间过短进入openai的语音转文字会报错,请一定注意)
def record_audio():
pressdown_num = 0
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
WAVE_OUTPUT_FILENAME = "out/record.wav"
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
)
frames = []
logger.info("Recording...")
flag = 0
while 1:
while keyboard.is_pressed("RIGHT_SHIFT"):
flag = 1
data = stream.read(CHUNK)
frames.append(data)
pressdown_num = pressdown_num + 1
if flag:
break
logger.info("Stopped recording.")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()
if pressdown_num >= 5: # 粗糙的处理手段
return 1
else:
logger.info("杂鱼杂鱼,好短好短(录音时间过短,按右shift重新录制)")
return 0
# THRESHOLD 设置音量阈值,默认值800.0,根据实际情况调整 silence_threshold 设置沉默阈值,根据实际情况调整
def audio_listen(volume_threshold=800.0, silence_threshold=15):
audio = pyaudio.PyAudio()
# 设置音频参数
FORMAT = pyaudio.paInt16
CHANNELS = config.get("talk", "CHANNELS")
RATE = config.get("talk", "RATE")
CHUNK = 1024
stream = audio.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=int(config.get("talk", "device_index")),
)
frames = [] # 存储录制的音频帧
is_speaking = False # 是否在说话
silent_count = 0 # 沉默计数
speaking_flag = False # 录入标志位 不重要
logger.info("[即将开始录音……]")
while True:
# 播放中不录音
if config.get("talk", "no_recording_during_playback"):
# 存在待合成音频 或 已合成音频还未播放 或 播放中 或 在数据处理中
if (
my_handle.is_audio_queue_empty() != 15
or my_handle.is_handle_empty() == 1
or wait_play_audio_num > 0
):
time.sleep(
float(
config.get(
"talk", "no_recording_during_playback_sleep_interval"
)
)
)
continue
# 读取音频数据
data = stream.read(CHUNK)
audio_data = np.frombuffer(data, dtype=np.short)
max_dB = np.max(audio_data)
# logger.info(max_dB)
if max_dB > volume_threshold:
is_speaking = True
silent_count = 0
elif is_speaking is True:
silent_count += 1
if is_speaking is True:
frames.append(data)
if speaking_flag is False:
logger.info("[录入中……]")
speaking_flag = True
if silent_count >= silence_threshold:
break
logger.info("[语音录入完成]")
# 将音频保存为WAV文件
"""with wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(pyaudio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))"""
return frames
# 处理聊天逻辑 传入ASR后的文本内容
def talk_handle(content: str):
global is_talk_awake
def clear_queue_and_stop_audio_play(message_queue: bool=True, voice_tmp_path_queue: bool=True, stop_audio_play: bool=True):
"""
清空队列 或 停止播放音频
"""
if message_queue:
ret = my_handle.clear_queue("message_queue")
if ret:
logger.info("清空待合成消息队列成功!")
else:
logger.error("清空待合成消息队列失败!")
if voice_tmp_path_queue:
ret = my_handle.clear_queue("voice_tmp_path_queue")
if ret:
logger.info("清空待播放音频队列成功!")
else:
logger.error("清空待播放音频队列失败!")
if stop_audio_play:
ret = my_handle.stop_audio("pygame", True, True)
try:
# 检查并切换聊天唤醒状态
def check_talk_awake(content: str):
"""检查并切换聊天唤醒状态
Args:
content (str): 聊天内容
Returns:
dict:
ret 是否需要触发
is_talk_awake 当前唤醒状态
first 是否是第一次触发 唤醒or睡眠,用于触发首次切换时的特殊提示语
"""
global is_talk_awake
# 判断是否启动了 唤醒词功能
if config.get("talk", "wakeup_sleep", "enable"):
if config.get("talk", "wakeup_sleep", "mode") == "长期唤醒":
# 判断现在是否是唤醒状态
if is_talk_awake is False:
# 判断文本内容是否包含唤醒词
trigger_word = common.find_substring_in_list(
content, config.get("talk", "wakeup_sleep", "wakeup_word")
)
if trigger_word:
is_talk_awake = True
logger.info("[聊天唤醒成功]")
return {
"ret": 0,
"is_talk_awake": is_talk_awake,
"first": True,
"trigger_word": trigger_word,
}
return {
"ret": -1,
"is_talk_awake": is_talk_awake,
"first": False,
}
else:
# 判断文本内容是否包含睡眠词
trigger_word = common.find_substring_in_list(
content, config.get("talk", "wakeup_sleep", "sleep_word")
)
if trigger_word:
is_talk_awake = False
logger.info("[聊天睡眠成功]")
return {
"ret": 0,
"is_talk_awake": is_talk_awake,
"first": True,
"trigger_word": trigger_word,
}
return {
"ret": 0,
"is_talk_awake": is_talk_awake,
"first": False,
}
elif config.get("talk", "wakeup_sleep", "mode") == "单次唤醒":
# 无需判断当前是否是唤醒状态,因为默认都是状态清除
# 判断文本内容是否包含唤醒词
trigger_word = common.find_substring_in_list(
content, config.get("talk", "wakeup_sleep", "wakeup_word")
)
if trigger_word:
is_talk_awake = True
logger.info("[聊天唤醒成功]")
return {
"ret": 0,
"is_talk_awake": is_talk_awake,
# 单次唤醒下 没有首次唤醒提示
"first": False,
"trigger_word": trigger_word,
}
return {
"ret": -1,
"is_talk_awake": is_talk_awake,
"first": False,
}
return {"ret": 0, "is_talk_awake": True, "trigger_word": "", "first": False}
# 输出识别结果
logger.info("识别结果:" + content)
# 空内容过滤
if content == "":
return
username = config.get("talk", "username")
data = {"platform": "本地聊天", "username": username, "content": content}
# 检查并切换聊天唤醒状态
check_resp = check_talk_awake(content)
if check_resp["ret"] == 0:
# 唤醒情况下
if check_resp["is_talk_awake"]:
# 长期唤醒、且不是首次触发的情况下,后面的内容不会携带触发词,即使携带了也不应该进行替换操作
if config.get("talk", "wakeup_sleep", "mode") == "长期唤醒" and not check_resp["first"]:
pass
else:
# 替换触发词为空
content = content.replace(check_resp["trigger_word"], "").strip()
# 因为唤醒可能会有仅唤醒词的情况,所以可能出现首次唤醒,唤醒词被过滤,content为空清空,导致不播放唤醒提示语,需要处理
if content == "" and not check_resp["first"]:
return
# 赋值给data
data["content"] = content
# 首次触发切换模式 播放唤醒文案
if check_resp["first"]:
# 随机获取文案 TODO: 如果此功能测试成功,所有的类似功能都将使用此函数简化代码
resp_json = common.get_random_str_in_list_and_format(
ori_list=config.get(
"talk", "wakeup_sleep", "wakeup_copywriting"
)
)
if resp_json["ret"] == 0:
data["content"] = resp_json["content"]
data["insert_index"] = -1
my_handle.reread_handle(data)
else:
# 如果启用了“打断对话”功能
if config.get("talk", "interrupt_talk", "enable"):
# 判断文本内容是否包含中断词
interrupt_word = common.find_substring_in_list(
data["content"], config.get("talk", "interrupt_talk", "keywords")
)
if interrupt_word:
logger.info(f"[聊天中断] 命中中断词:{interrupt_word}")
# 从配置中获取需要清除的数据类型
clean_type = config.get("talk", "interrupt_talk", "clean_type")
# 各类型数据是否清除
message_queue = "message_queue" in clean_type
voice_tmp_path_queue = "voice_tmp_path_queue" in clean_type
stop_audio_play = "stop_audio_play" in clean_type
clear_queue_and_stop_audio_play(message_queue, voice_tmp_path_queue, stop_audio_play)
return False
# 传递给my_handle进行进行后续一系列的处理
my_handle.process_data(data, "talk")
# 单次唤醒情况下,唤醒后关闭
if config.get("talk", "wakeup_sleep", "mode") == "单次唤醒":
is_talk_awake = False
# 睡眠情况下
else:
# 首次进入睡眠 播放睡眠文案
if check_resp["first"]:
resp_json = common.get_random_str_in_list_and_format(
ori_list=config.get(
"talk", "wakeup_sleep", "sleep_copywriting"
)
)
if resp_json["ret"] == 0:
data["content"] = resp_json["content"]
data["insert_index"] = -1
my_handle.reread_handle(data)
except Exception as e:
logger.error(traceback.format_exc())
# 执行录音、识别&提交
def do_listen_and_comment(status=True):
global \
stop_do_listen_and_comment_thread_event, \
faster_whisper_model, \
sense_voice_model, \
is_recording, \
is_talk_awake
try:
is_recording = True
config = Config(config_path)
# 是否启用按键监听和直接对话,没启用的话就不用执行了
if not config.get("talk", "key_listener_enable") and not config.get("talk", "direct_run_talk"):
is_recording = False
return
# 针对faster_whisper情况,模型加载一次共用,减少开销
if "faster_whisper" == config.get("talk", "type"):
from faster_whisper import WhisperModel
if faster_whisper_model is None:
logger.info("faster_whisper 模型加载中,请稍后...")
# Run on GPU with FP16
faster_whisper_model = WhisperModel(
model_size_or_path=config.get(
"talk", "faster_whisper", "model_size"
),
device=config.get("talk", "faster_whisper", "device"),
compute_type=config.get(
"talk", "faster_whisper", "compute_type"
),
download_root=config.get(
"talk", "faster_whisper", "download_root"
),
)
logger.info("faster_whisper 模型加载完毕,可以开始说话了喵~")
elif "sensevoice" == config.get("talk", "type"):
from funasr import AutoModel
logger.info("sensevoice 模型加载中,请稍后...")
asr_model_path = config.get("talk", "sensevoice", "asr_model_path")
vad_model_path = config.get("talk", "sensevoice", "vad_model_path")
if sense_voice_model is None:
sense_voice_model = AutoModel(
model=asr_model_path,
vad_model=vad_model_path,
vad_kwargs={
"max_single_segment_time": int(
config.get(
"talk", "sensevoice", "vad_max_single_segment_time"
)
)
},
trust_remote_code=True,
device=config.get("talk", "sensevoice", "device"),
remote_code="./sensevoice/model.py",
)
logger.info("sensevoice 模型加载完毕,可以开始说话了喵~")
while True:
try:
# 检查是否收到停止事件
if stop_do_listen_and_comment_thread_event.is_set():
logger.info("停止录音~")
is_recording = False
break
config = Config(config_path)
# 根据接入的语音识别类型执行
if config.get("talk", "type") in [
"baidu",
"faster_whisper",
"sensevoice",
]:
# 设置音频参数
FORMAT = pyaudio.paInt16
CHANNELS = config.get("talk", "CHANNELS")
RATE = config.get("talk", "RATE")
audio_out_path = config.get("play_audio", "out_path")
if not os.path.isabs(audio_out_path):
if not audio_out_path.startswith("./"):
audio_out_path = "./" + audio_out_path
file_name = "asr_" + common.get_bj_time(4) + ".wav"
WAVE_OUTPUT_FILENAME = common.get_new_audio_path(
audio_out_path, file_name
)
# WAVE_OUTPUT_FILENAME = './out/asr_' + common.get_bj_time(4) + '.wav'
frames = audio_listen(
config.get("talk", "volume_threshold"),
config.get("talk", "silence_threshold"),
)
# 将音频保存为WAV文件
with wave.open(WAVE_OUTPUT_FILENAME, "wb") as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(pyaudio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
if config.get("talk", "type") == "baidu":
# 读取音频文件
with open(WAVE_OUTPUT_FILENAME, "rb") as fp:
audio = fp.read()
# 初始化 AipSpeech 对象
baidu_client = AipSpeech(
config.get("talk", "baidu", "app_id"),
config.get("talk", "baidu", "api_key"),
config.get("talk", "baidu", "secret_key"),
)
# 识别音频文件
res = baidu_client.asr(
audio,
"wav",
16000,
{
"dev_pid": 1536,
},
)
if res["err_no"] == 0:
content = res["result"][0]
talk_handle(content)
else:
logger.error(f"百度接口报错:{res}")
elif config.get("talk", "type") == "faster_whisper":
logger.debug("faster_whisper模型加载中...")
language = config.get("talk", "faster_whisper", "language")
if language == "自动识别":
language = None
segments, info = faster_whisper_model.transcribe(
WAVE_OUTPUT_FILENAME,
language=language,
beam_size=config.get(
"talk", "faster_whisper", "beam_size"
),
)
logger.debug(
"识别语言为:'%s',概率:%f"
% (info.language, info.language_probability)
)
content = ""
for segment in segments:
logger.info(
"[%.2fs -> %.2fs] %s"
% (segment.start, segment.end, segment.text)
)
content += segment.text + "。"
if content == "":
# 恢复录音标志位
is_recording = False
return
talk_handle(content)
elif config.get("talk", "type") == "sensevoice":
res = sense_voice_model.generate(
input=WAVE_OUTPUT_FILENAME,
cache={},
language=config.get("talk", "sensevoice", "language"),
text_norm=config.get("talk", "sensevoice", "text_norm"),
batch_size_s=int(
config.get("talk", "sensevoice", "batch_size_s")
),
batch_size=int(
config.get("talk", "sensevoice", "batch_size")
),
)
def remove_angle_brackets_content(input_string: str):
# 使用正则表达式来匹配并删除 <> 之间的内容
return re.sub(r"<.*?>", "", input_string)
content = remove_angle_brackets_content(res[0]["text"])
talk_handle(content)
elif "google" == config.get("talk", "type"):
# 创建Recognizer对象
r = sr.Recognizer()
try:
# 打开麦克风进行录音
with sr.Microphone() as source:
logger.info("录音中...")
# 从麦克风获取音频数据
audio = r.listen(source)
logger.info("成功录制")
# 进行谷歌实时语音识别 en-US zh-CN ja-JP
content = r.recognize_google(
audio,
language=config.get("talk", "google", "tgt_lang"),
)
talk_handle(content)
except sr.UnknownValueError:
logger.warning("无法识别输入的语音")
except sr.RequestError as e:
logger.error("请求出错:" + str(e))
is_recording = False
if not status:
return
except Exception as e:
logger.error(traceback.format_exc())
is_recording = False
return
except Exception as e:
logger.error(traceback.format_exc())
is_recording = False
return
def on_key_press(event):
global \
do_listen_and_comment_thread, \
stop_do_listen_and_comment_thread_event, \
is_recording
# 是否启用按键监听,不启用的话就不用执行了
if not config.get("talk", "key_listener_enable"):
return
# if event.name in ['z', 'Z', 'c', 'C'] and keyboard.is_pressed('ctrl'):
# logger.info("退出程序")
# os._exit(0)
# 按键CD
current_time = time.time()
if current_time - last_pressed < cooldown:
return
"""
触发按键部分的判断
"""
trigger_key_lower = None
stop_trigger_key_lower = None
# trigger_key是字母, 整个小写
if trigger_key.isalpha():
trigger_key_lower = trigger_key.lower()
# stop_trigger_key是字母, 整个小写
if stop_trigger_key.isalpha():
stop_trigger_key_lower = stop_trigger_key.lower()
if trigger_key_lower:
if event.name == trigger_key or event.name == trigger_key_lower:
logger.info(f"检测到单击键盘 {event.name},即将开始录音~")
elif event.name == stop_trigger_key or event.name == stop_trigger_key_lower:
logger.info(f"检测到单击键盘 {event.name},即将停止录音~")
stop_do_listen_and_comment_thread_event.set()
return
else:
return
else:
if event.name == trigger_key:
logger.info(f"检测到单击键盘 {event.name},即将开始录音~")
elif event.name == stop_trigger_key:
logger.info(f"检测到单击键盘 {event.name},即将停止录音~")
stop_do_listen_and_comment_thread_event.set()
return
else:
return
if not is_recording:
# 是否启用连续对话模式
if config.get("talk", "continuous_talk"):
stop_do_listen_and_comment_thread_event.clear()
do_listen_and_comment_thread = threading.Thread(
target=do_listen_and_comment, args=(True,)
)
do_listen_and_comment_thread.start()
else:
stop_do_listen_and_comment_thread_event.clear()
do_listen_and_comment_thread = threading.Thread(
target=do_listen_and_comment, args=(False,)
)
do_listen_and_comment_thread.start()
else:
logger.warning("正在录音中...请勿重复点击录音捏!")
# 按键监听
def key_listener():
# 注册按键按下事件的回调函数
keyboard.on_press(on_key_press)
try:
# 进入监听状态,等待按键按下
keyboard.wait()
except KeyboardInterrupt:
os._exit(0)
# 直接运行语音对话
def direct_run_talk():
global \
do_listen_and_comment_thread, \
stop_do_listen_and_comment_thread_event, \
is_recording
if not is_recording:
# 是否启用连续对话模式
if config.get("talk", "continuous_talk"):
stop_do_listen_and_comment_thread_event.clear()
do_listen_and_comment_thread = threading.Thread(
target=do_listen_and_comment, args=(True,)
)
do_listen_and_comment_thread.start()
else:
stop_do_listen_and_comment_thread_event.clear()
do_listen_and_comment_thread = threading.Thread(
target=do_listen_and_comment, args=(False,)
)
do_listen_and_comment_thread.start()
# 从配置文件中读取触发键的字符串配置
trigger_key = config.get("talk", "trigger_key")
stop_trigger_key = config.get("talk", "stop_trigger_key")
# 是否启用了 按键监听
if config.get("talk", "key_listener_enable"):
logger.info(
f"单击键盘 {trigger_key} 按键进行录音喵~ 由于其他任务还要启动,如果按键没有反应,请等待一段时间(如果使用本地ASR,请等待模型加载完成后使用)"
)
# 是否启用了直接运行对话,如果启用了,将在首次运行时直接进行语音识别,而不需手动点击开始按键。针对有些系统按键无法触发的情况下,配合连续对话和唤醒词使用
if config.get("talk", "direct_run_talk"):
logger.info("直接运行对话模式,首次运行时将直接进行语音识别,而不需手动点击开始按键(如果使用本地ASR,请等待模型加载完成后使用)")
direct_run_talk()
# 创建并启动按键监听线程,放着也是在聊天模式下,让程序一直阻塞用的
thread = threading.Thread(target=key_listener)
thread.start()
# 定时任务
def schedule_task(index):
global config, common, my_handle, last_liveroom_data, last_username_list
logger.debug("定时任务执行中...")
hour, min = common.get_bj_time(6)
if 0 <= hour and hour < 6:
time = f"凌晨{hour}点{min}分"
elif 6 <= hour and hour < 9:
time = f"早晨{hour}点{min}分"
elif 9 <= hour and hour < 12:
time = f"上午{hour}点{min}分"
elif hour == 12:
time = f"中午{hour}点{min}分"
elif 13 <= hour and hour < 18:
time = f"下午{hour - 12}点{min}分"
elif 18 <= hour and hour < 20:
time = f"傍晚{hour - 12}点{min}分"
elif 20 <= hour and hour < 24:
time = f"晚上{hour - 12}点{min}分"
# 根据对应索引从列表中随机获取一个值
if len(config.get("schedule")[index]["copy"]) <= 0:
return None
random_copy = random.choice(config.get("schedule")[index]["copy"])
# 假设有多个未知变量,用户可以在此处定义动态变量
variables = {
"time": time,
"user_num": "N",
"last_username": last_username_list[-1],
}
# 有用户数据情况的平台特殊处理
if platform in ["dy", "tiktok"]:
variables["user_num"] = last_liveroom_data["OnlineUserCount"]
# 使用字典进行字符串替换
if any(var in random_copy for var in variables):
content = random_copy.format(
**{var: value for var, value in variables.items() if var in random_copy}