forked from Ikaros-521/AI-Vtuber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
my_handle.py
2260 lines (1843 loc) · 101 KB
/
my_handle.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, threading, json, random
import difflib
import logging
from datetime import datetime
import traceback
import importlib
import pyautogui
from .config import Config
from .common import Common
from .audio import Audio
from .gpt_model.gpt import GPT_MODEL
from .logger import Configure_logger
from .db import SQLiteDB
from .my_translate import My_Translate
"""
___ _
|_ _| | ____ _ _ __ ___ ___
| || |/ / _` | '__/ _ \/ __|
| || < (_| | | | (_) \__ \
|___|_|\_\__,_|_| \___/|___/
"""
class My_handle():
common = None
config = None
audio = None
my_translate = None
abnormal_alarm_data = {
"platform": {
"error_count": 0
},
"llm": {
"error_count": 0
},
"tts": {
"error_count": 0
},
"svc": {
"error_count": 0
},
"visual_body": {
"error_count": 0
},
"other": {
"error_count": 0
}
}
def __init__(self, config_path):
logging.info("初始化My_handle...")
if My_handle.common is None:
My_handle.common = Common()
if My_handle.config is None:
My_handle.config = Config(config_path)
if My_handle.audio is None:
My_handle.audio = Audio(config_path)
if My_handle.my_translate is None:
My_handle.my_translate = My_Translate(config_path)
# 日志文件路径
file_path = "./log/log-" + My_handle.common.get_bj_time(1) + ".txt"
Configure_logger(file_path)
self.proxy = None
# self.proxy = {
# "http": "http://127.0.0.1:10809",
# "https": "http://127.0.0.1:10809"
# }
try:
# 数据丢弃部分相关的实现
self.data_lock = threading.Lock()
self.timers = {}
# 设置会话初始值
self.session_config = {'msg': [{"role": "system", "content": My_handle.config.get('chatgpt', 'preset')}]}
self.sessions = {}
self.current_key_index = 0
# 直播间号
self.room_id = My_handle.config.get("room_display_id")
self.before_prompt = My_handle.config.get("before_prompt")
self.after_prompt = My_handle.config.get("after_prompt")
# 过滤配置
self.filter_config = My_handle.config.get("filter")
# 答谢
self.thanks_config = My_handle.config.get("thanks")
self.chat_type = My_handle.config.get("chat_type")
self.need_lang = My_handle.config.get("need_lang")
# 优先本地问答
self.local_qa = My_handle.config.get("local_qa")
self.local_qa_audio_list = None
# 音频合成使用技术
My_handle.audio_synthesis_type = My_handle.config.get("audio_synthesis_type")
# Stable Diffusion
self.sd_config = My_handle.config.get("sd")
# 点歌模块
self.choose_song_config = My_handle.config.get("choose_song")
self.choose_song_song_lists = None
logging.info(f"配置数据加载成功。")
except Exception as e:
logging.error(traceback.format_exc())
# 设置GPT_Model全局模型列表
GPT_MODEL.set_model_config("openai", My_handle.config.get("openai"))
GPT_MODEL.set_model_config("chatgpt", My_handle.config.get("chatgpt"))
GPT_MODEL.set_model_config("claude", My_handle.config.get("claude"))
"""
新增LLM后,这边先定义下各个变量,下面会用到
"""
self.chatgpt = None
self.claude = None
self.claude2 = None
self.chatglm = None
self.chat_with_file = None
self.text_generation_webui = None
self.sparkdesk = None
self.langchain_chatglm = None
self.zhipu = None
self.bard_api = None
self.yiyan = None
self.tongyi = None
# 聊天相关类实例化
if self.chat_type == "chatgpt":
self.chatgpt = GPT_MODEL.get("chatgpt")
elif self.chat_type == "claude":
self.claude = GPT_MODEL.get(self.chat_type)
# 初次运行 先重置下会话
if not self.claude.reset_claude():
logging.error("重置Claude会话失败喵~")
elif self.chat_type == "claude2":
GPT_MODEL.set_model_config("claude2", My_handle.config.get("claude2"))
self.claude2 = GPT_MODEL.get(self.chat_type)
# 初次运行 先重置下会话
if self.claude2.get_organization_id() is None:
logging.error("重置Claude2会话失败喵~")
elif self.chat_type == "chatterbot":
from chatterbot import ChatBot # 导入聊天机器人库
self.chatterbot_config = My_handle.config.get("chatterbot")
try:
self.bot = ChatBot(
self.chatterbot_config["name"], # 聊天机器人名字
database_uri='sqlite:///' + self.chatterbot_config["db_path"] # 数据库URI,数据库用于存储对话历史
)
except Exception as e:
logging.info(e)
exit(0)
elif self.chat_type == "chatglm":
GPT_MODEL.set_model_config("chatglm", My_handle.config.get("chatglm"))
self.chatglm = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "chat_with_file":
from utils.chat_with_file.chat_with_file import Chat_with_file
self.chat_with_file = Chat_with_file(My_handle.config.get("chat_with_file"))
elif self.chat_type == "text_generation_webui":
GPT_MODEL.set_model_config("text_generation_webui", My_handle.config.get("text_generation_webui"))
self.text_generation_webui = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "sparkdesk":
GPT_MODEL.set_model_config("sparkdesk", My_handle.config.get("sparkdesk"))
self.sparkdesk = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "langchain_chatglm":
GPT_MODEL.set_model_config("langchain_chatglm", My_handle.config.get("langchain_chatglm"))
self.langchain_chatglm = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "zhipu":
GPT_MODEL.set_model_config("zhipu", My_handle.config.get("zhipu"))
self.zhipu = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "bard":
GPT_MODEL.set_model_config("bard", My_handle.config.get("bard"))
self.bard_api = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "yiyan":
GPT_MODEL.set_model_config("yiyan", My_handle.config.get("yiyan"))
self.yiyan = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "tongyi":
GPT_MODEL.set_model_config("tongyi", My_handle.config.get("tongyi"))
self.tongyi = GPT_MODEL.get(self.chat_type)
elif self.chat_type == "game":
self.game = importlib.import_module("game." + My_handle.config.get("game", "module_name"))
# exit(0)
# 判断是否使能了SD
if self.sd_config["enable"]:
from utils.sd import SD
self.sd = SD(self.sd_config)
# 判断是否使能了点歌模式
if self.choose_song_config["enable"]:
# 获取本地音频文件夹内所有的音频文件名
self.choose_song_song_lists = My_handle.audio.get_dir_audios_filename(self.choose_song_config["song_path"])
# 日志文件路径
self.log_file_path = "./log/log-" + My_handle.common.get_bj_time(1) + ".txt"
if os.path.isfile(self.log_file_path):
logging.info(f'{self.log_file_path} 日志文件已存在,跳过')
else:
with open(self.log_file_path, 'w') as f:
f.write('')
logging.info(f'{self.log_file_path} 日志文件已创建')
self.comment_file_path = "./log/comment-" + My_handle.common.get_bj_time(1) + ".txt"
if os.path.isfile(self.comment_file_path):
logging.info(f'{self.comment_file_path} 弹幕文件已存在,跳过')
else:
with open(self.comment_file_path, 'w') as f:
f.write('')
logging.info(f'{self.comment_file_path} 弹幕文件已创建')
"""
............. '>)xcn)I
}}}}}}}}}}}}](v0kaaakad\..
++++++~~++<_xpahhhZ0phah>
_________+(OhhkamuCbkkkh+
?????????nbhkhkn|makkkhQ^
[[[[[[[}UhkbhZ]fbhkkkhb<
1{1{1{1ChkkaXicohkkkhk]
))))))JhkkhrICakkkkap-
\\\\|ckkkat;0akkkka0>
ttt/fpkka/;Oakhhaku"
jjjjUmkau^QabwQX\< '!<++~>iI .;>++++<>I' :+}}{?;
xxxcpdkO"capmmZ/^ +Y-;,,;-Lf ItX/+l:",;>1cx> .`"x#d>` .`.
uuvqwkh+1ahaaL_ 'Zq; ;~ '/bQ! "uhc: . 1oZ' "vj. ^'
ccc0kaz!kawX}' .\hbv?: .jop; .C*L^ )oO` .':I^. ."_L!^^. ':;,'
XXXXph_cU_" >rZhbC\! "qaC... faa~ )oO` ;-jqj .l[mb1]_' ^(|}\Ow{
XXXz00i+ '!1Ukkc, 'JoZ` . uop; )oO' >ou .Lp" . ,0j^^>Yvi
XXXzLn. . ^> lC#( lLot. _kq- . 1o0' >on .Qp, }*|><i^ .
YYYXQ| ,O]^. "XQI . `10c~^. '!t0f: .t*q;....'l1. ._#c.. .Qkl`I_"Iw0~"`,<|i.
(|((f1 ^t1]++-}(?` '>}}}/rrx1]~^ ^?jvv/]--]{r) .i{x/+; ]Xr1_;. :(vnrj\i.
'1.. .''. . .Itq*Z}` ..
+; . "}XmQf-i!;.
. ';><iI"
"""
try:
# 数据库
self.db = SQLiteDB(My_handle.config.get("database", "path"))
logging.info(f'创建数据库:{My_handle.config.get("database", "path")}')
# 创建弹幕表
create_table_sql = '''
CREATE TABLE IF NOT EXISTS danmu (
username TEXT NOT NULL,
content TEXT NOT NULL,
ts DATETIME NOT NULL
)
'''
self.db.execute(create_table_sql)
logging.info('创建danmu(弹幕)表')
create_table_sql = '''
CREATE TABLE IF NOT EXISTS entrance (
username TEXT NOT NULL,
ts DATETIME NOT NULL
)
'''
self.db.execute(create_table_sql)
logging.info('创建entrance(入场)表')
create_table_sql = '''
CREATE TABLE IF NOT EXISTS gift (
username TEXT NOT NULL,
gift_name TEXT NOT NULL,
gift_num INT NOT NULL,
unit_price REAL NOT NULL,
total_price REAL NOT NULL,
ts DATETIME NOT NULL
)
'''
self.db.execute(create_table_sql)
logging.info('创建gift(礼物)表')
create_table_sql = '''
CREATE TABLE IF NOT EXISTS integral (
platform TEXT NOT NULL,
username TEXT NOT NULL,
uid TEXT NOT NULL,
integral INT NOT NULL,
view_num INT NOT NULL,
sign_num INT NOT NULL,
last_sign_ts DATETIME NOT NULL,
total_price INT NOT NULL,
last_ts DATETIME NOT NULL
)
'''
self.db.execute(create_table_sql)
logging.info('创建integral(积分)表')
except Exception as e:
logging.error(traceback.format_exc())
def get_room_id(self):
return self.room_id
# 音频合成处理
def audio_synthesis_handle(self, data_json):
"""音频合成处理
Args:
data_json (dict): 传递的json数据
核心参数:
type目前有
comment 弹幕
local_qa_audio 本地问答音频
song 歌曲
reread 复读
direct_reply 直接回复
read_comment 念弹幕
gift 礼物
entrance 用户入场
follow 用户关注
idle_time_task 闲时任务
abnormal_alarm 异常报警
"""
# 如果虚拟身体-Unity,则发送数据到中转站
if My_handle.config.get("visual_body") == "unity":
# 判断 'config' 是否存在于字典中
if 'config' in data_json:
# 删除 'config' 对应的键值对
data_json.pop('config')
data_json["password"] = My_handle.config.get("unity", "password")
resp_json = My_handle.common.send_request(My_handle.config.get("unity", "api_ip_port"), "POST", data_json)
if resp_json:
if resp_json["code"] == 200:
logging.info("请求unity中转站成功")
else:
logging.info(f"请求unity中转站出错,{resp_json['message']}")
else:
logging.error("请求unity中转站失败")
else:
# 音频合成(edge-tts / vits_fast)并播放
My_handle.audio.audio_synthesis(data_json)
# 从本地问答库中搜索问题的答案
def find_answer(self, question, qa_file_path, similarity=1):
"""从本地问答库中搜索问题的答案
Args:
question (str): 问题文本
qa_file_path (str): 问答库的路径
similarity (float): 相似度
Returns:
str: 答案文本 或 None
"""
with open(qa_file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
q_list = [lines[i].strip() for i in range(0, len(lines), 2)]
q_to_answer_index = {q: i + 1 for i, q in enumerate(q_list)}
q = My_handle.common.find_best_match(question, q_list, similarity)
# print(f"q={q}")
if q is not None:
answer_index = q_to_answer_index.get(q)
# print(f"answer_index={answer_index}")
if answer_index is not None and answer_index < len(lines):
return lines[answer_index * 2 - 1].strip()
return None
# 本地问答库 文本模式 根据相似度查找答案
def find_similar_answer(self, input_str, qa_file_path, min_similarity=0.8):
"""本地问答库 文本模式 根据相似度查找答案
Args:
input_str (str): 输入的待查找字符串
qa_file_path (str): 问答库的路径
min_similarity (float, optional): 最低匹配相似度. 默认 0.8.
Returns:
response (str): 匹配到的结果,如果匹配不到则返回None
"""
def load_data_from_file(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
except (FileNotFoundError, json.JSONDecodeError):
return None
# 从文件加载数据
data = load_data_from_file(qa_file_path)
if data is None:
return None
# 存储相似度与回答的元组列表
similarity_responses = []
# 遍历json中的每个条目,找到与输入字符串相似的关键词
for entry in data:
for keyword in entry.get("关键词", []):
similarity = difflib.SequenceMatcher(None, input_str, keyword).ratio()
similarity_responses.append((similarity, entry.get("回答", [])))
# 过滤相似度低于设定阈值的回答
similarity_responses = [(similarity, response) for similarity, response in similarity_responses if similarity >= min_similarity]
# 如果没有符合条件的回答,返回None
if not similarity_responses:
return None
# 按相似度降序排序
similarity_responses.sort(reverse=True, key=lambda x: x[0])
# 获取相似度最高的回答列表
top_response = similarity_responses[0][1]
# 随机选择一个回答
response = random.choice(top_response)
return response
# 本地问答库 处理
def local_qa_handle(self, data):
"""本地问答库 处理
Args:
data (dict): 用户名 弹幕数据
Returns:
bool: 是否触发并处理
"""
user_name = data["username"]
content = data["content"]
# 合并字符串末尾连续的* 主要针对获取不到用户名的情况
user_name = My_handle.common.merge_consecutive_asterisks(user_name)
# 1、匹配本地问答库 触发后不执行后面的其他功能
if self.local_qa["text"]["enable"] == True:
# 根据类型,执行不同的问答匹配算法
if self.local_qa["text"]["type"] == "text":
tmp = self.find_answer(content, self.local_qa["text"]["file_path"], self.local_qa["text"]["similarity"])
else:
tmp = self.find_similar_answer(content, self.local_qa["text"]["file_path"], self.local_qa["text"]["similarity"])
if tmp != None:
logging.info(f"触发本地问答库-文本 [{user_name}]: {content}")
# 将问答库中设定的参数替换为指定内容,开发者可以自定义替换内容
if "{cur_time}" in tmp:
tmp = tmp.format(cur_time=My_handle.common.get_bj_time(5))
if "{username}" in tmp:
tmp = tmp.format(username=user_name)
else:
tmp = tmp
logging.info(f"本地问答库-文本回答为: {tmp}")
resp_content = tmp
# 将 AI 回复记录到日志文件中
with open(self.comment_file_path, "r+", encoding="utf-8") as f:
tmp_content = f.read()
# 将指针移到文件头部位置(此目的是为了让直播中读取日志文件时,可以一直让最新内容显示在顶部)
f.seek(0, 0)
# 不过这个实现方式,感觉有点低效
# 设置单行最大字符数,主要目的用于接入直播弹幕显示时,弹幕过长导致的显示溢出问题
max_length = 20
resp_content_substrings = [resp_content[i:i + max_length] for i in
range(0, len(resp_content), max_length)]
resp_content_joined = '\n'.join(resp_content_substrings)
# 根据 弹幕日志类型进行各类日志写入
if My_handle.config.get("comment_log_type") == "问答":
f.write(f"[{user_name} 提问]:{content}\n[AI回复{user_name}]:{resp_content_joined}\n" + tmp_content)
elif My_handle.config.get("comment_log_type") == "问题":
f.write(f"[{user_name} 提问]:{content}\n" + tmp_content)
elif My_handle.config.get("comment_log_type") == "回答":
f.write(f"[AI回复{user_name}]:{resp_content_joined}\n" + tmp_content)
message = {
"type": "comment",
"tts_type": My_handle.audio_synthesis_type,
"data": My_handle.config.get(My_handle.audio_synthesis_type),
"config": self.filter_config,
"user_name": user_name,
"content": resp_content
}
self.audio_synthesis_handle(message)
return True
# 2、匹配本地问答音频库 触发后不执行后面的其他功能
if self.local_qa["audio"]["enable"] == True:
# 输出当前用户发送的弹幕消息
# logging.info(f"[{user_name}]: {content}")
# 获取本地问答音频库文件夹内所有的音频文件名
local_qa_audio_filename_list = My_handle.audio.get_dir_audios_filename(self.local_qa["audio"]["file_path"], type=1)
self.local_qa_audio_list = My_handle.audio.get_dir_audios_filename(self.local_qa["audio"]["file_path"], type=0)
# 不含拓展名做查找
local_qv_audio_filename = My_handle.common.find_best_match(content, local_qa_audio_filename_list, self.local_qa["audio"]["similarity"])
# print(f"local_qv_audio_filename={local_qv_audio_filename}")
# 找到了匹配的结果
if local_qv_audio_filename is not None:
logging.info(f"触发本地问答库-语音 [{user_name}]: {content}")
# 把结果从原文件名列表中在查找一遍,补上拓展名
local_qv_audio_filename = My_handle.common.find_best_match(local_qv_audio_filename, self.local_qa_audio_list, 0)
# 寻找对应的文件
resp_content = My_handle.audio.search_files(self.local_qa["audio"]["file_path"], local_qv_audio_filename)
if resp_content != []:
logging.debug(f"匹配到的音频原相对路径:{resp_content[0]}")
# 拼接音频文件路径
resp_content = f'{self.local_qa["audio"]["file_path"]}/{resp_content[0]}'
logging.info(f"匹配到的音频路径:{resp_content}")
message = {
"type": "local_qa_audio",
"tts_type": My_handle.audio_synthesis_type,
"data": My_handle.config.get(My_handle.audio_synthesis_type),
"config": self.filter_config,
"user_name": user_name,
"content": content,
"file_path": resp_content
}
self.audio_synthesis_handle(message)
return True
return False
# 点歌模式 处理
def choose_song_handle(self, data):
"""点歌模式 处理
Args:
data (dict): 用户名 弹幕数据
Returns:
bool: 是否触发并处理
"""
user_name = data["username"]
content = data["content"]
# 合并字符串末尾连续的* 主要针对获取不到用户名的情况
user_name = My_handle.common.merge_consecutive_asterisks(user_name)
if self.choose_song_config["enable"] == True:
# 判断点歌命令是否正确
if content.startswith(self.choose_song_config["start_cmd"]):
logging.info(f"[{user_name}]: {content}")
# 去除命令前缀
content = content[len(self.choose_song_config["start_cmd"]):]
# 判断是否有此歌曲
song_filename = My_handle.common.find_best_match(content, self.choose_song_song_lists)
if song_filename is None:
# resp_content = f"抱歉,我还没学会唱{content}"
# 根据配置的 匹配失败回复文案来进行合成
resp_content = self.choose_song_config["match_fail_copy"].format(content=content)
logging.info(f"[AI回复{user_name}]:{resp_content}")
message = {
"type": "comment",
"tts_type": My_handle.audio_synthesis_type,
"data": My_handle.config.get(My_handle.audio_synthesis_type),
"config": self.filter_config,
"user_name": user_name,
"content": resp_content
}
self.audio_synthesis_handle(message)
return True
resp_content = My_handle.audio.search_files(self.choose_song_config['song_path'], song_filename)
if resp_content == []:
return True
logging.debug(f"匹配到的音频原相对路径:{resp_content[0]}")
# 拼接音频文件路径
resp_content = f"{self.choose_song_config['song_path']}/{resp_content[0]}"
resp_content = os.path.abspath(resp_content)
logging.info(f"匹配到的音频路径:{resp_content}")
message = {
"type": "song",
"tts_type": My_handle.audio_synthesis_type,
"data": My_handle.config.get(My_handle.audio_synthesis_type),
"config": self.filter_config,
"user_name": user_name,
"content": resp_content
}
self.audio_synthesis_handle(message)
return True
# 判断取消点歌命令是否正确
elif content.startswith(self.choose_song_config["stop_cmd"]):
My_handle.audio.stop_current_audio()
return True
# 判断随机点歌命令是否正确
elif content == self.choose_song_config["random_cmd"]:
resp_content = My_handle.common.random_search_a_audio_file(self.choose_song_config['song_path'])
if resp_content is None:
return True
logging.info(f"随机到的音频路径:{resp_content}")
message = {
"type": "song",
"tts_type": My_handle.audio_synthesis_type,
"data": My_handle.config.get(My_handle.audio_synthesis_type),
"config": self.filter_config,
"user_name": user_name,
"content": resp_content
}
self.audio_synthesis_handle(message)
return True
return False
# 画图模式 SD 处理
def sd_handle(self, data):
"""画图模式 SD 处理
Args:
data (dict): 用户名 弹幕数据
Returns:
bool: 是否触发并处理
"""
user_name = data["username"]
content = data["content"]
# 合并字符串末尾连续的* 主要针对获取不到用户名的情况
user_name = My_handle.common.merge_consecutive_asterisks(user_name)
if content.startswith(self.sd_config["trigger"]):
# 含有违禁词/链接
if My_handle.common.profanity_content(content) or My_handle.common.check_sensitive_words2(
self.filter_config["badwords_path"], content) or \
My_handle.common.is_url_check(content):
logging.warning(f"违禁词/链接:{content}")
return
if self.sd_config["enable"] == False:
logging.info("您还未启用SD模式,无法使用画画功能")
return True
else:
# 输出当前用户发送的弹幕消息
logging.info(f"[{user_name}]: {content}")
content = content[len(self.sd_config["trigger"]):]
# 根据设定的LLM
if self.sd_config["prompt_llm"]["type"] == "chatgpt":
if self.chatgpt is None:
self.chatgpt = GPT_MODEL.get("chatgpt")
content = self.sd_config["prompt_llm"]["before_prompt"] + \
content + self.after_prompt
# 调用gpt接口,获取返回内容
resp_content = self.chatgpt.get_gpt_resp(user_name, content)
if resp_content is not None:
# 输出 ChatGPT 返回的回复消息
logging.info(f"[AI回复{user_name}]:{resp_content}")
else:
resp_content = ""
logging.warning("警告:chatgpt无返回")
elif self.sd_config["prompt_llm"]["type"] == "claude":
if self.claude is None:
self.claude = GPT_MODEL.get(self.chat_type)
# 初次运行 先重置下会话
if not self.claude.reset_claude():
logging.error("重置Claude会话失败喵~")
content = self.before_prompt + content + self.after_prompt
resp_content = self.claude.get_claude_resp(content)
if resp_content is not None:
# 输出 返回的回复消息
logging.info(f"[AI回复{user_name}]:{resp_content}")
else:
resp_content = ""
logging.warning("警告:claude无返回")
elif self.sd_config["prompt_llm"]["type"] == "claude2":
if self.claude2 is None:
self.claude2 = GPT_MODEL.get(self.chat_type)
# 初次运行 先重置下会话
if self.claude2.get_organization_id() is None:
logging.error("重置Claude2会话失败喵~")
content = self.before_prompt + content + self.after_prompt
resp_content = self.claude2.get_claude2_resp(content)
if resp_content is not None:
# 输出 返回的回复消息
logging.info(f"[AI回复{user_name}]:{resp_content}")
else:
resp_content = ""
logging.warning("警告:claude2无返回")
elif self.sd_config["prompt_llm"]["type"] == "chatglm":
if self.chatglm is None:
self.chatglm = GPT_MODEL.get(self.chat_type)
# 生成回复
resp_content = self.chatglm.get_chatglm_resp(content)
if resp_content is not None:
# 输出 返回的回复消息
logging.info(f"[AI回复{user_name}]:{resp_content}")
else:
resp_content = ""
logging.warning("警告:chatglm无返回")
elif self.sd_config["prompt_llm"]["type"] == "text_generation_webui":
if self.text_generation_webui is None:
self.text_generation_webui = GPT_MODEL.get(self.chat_type)
# 生成回复
resp_content = self.text_generation_webui.get_text_generation_webui_resp(content)
if resp_content is not None:
# 输出 返回的回复消息
logging.info(f"[AI回复{user_name}]:{resp_content}")
else:
resp_content = ""
logging.warning("警告:text_generation_webui无返回")
elif self.sd_config["prompt_llm"]["type"] == "none":
resp_content = content
else:
resp_content = content
self.sd.process_input(resp_content)
return True
return False
# 弹幕格式检查和特殊字符替换
def comment_check_and_replace(self, content):
"""弹幕格式检查和特殊字符替换
Args:
content (str): 待处理的弹幕内容
Returns:
str: 处理完毕后的弹幕内容/None
"""
# 判断弹幕是否以xx起始,如果不是则返回
if self.filter_config["before_must_str"] and not any(
content.startswith(prefix) for prefix in self.filter_config["before_must_str"]):
return None
else:
for prefix in self.filter_config["before_must_str"]:
if content.startswith(prefix):
content = content[len(prefix):] # 删除匹配的开头
break
# 判断弹幕是否以xx结尾,如果不是则返回
if self.filter_config["after_must_str"] and not any(
content.endswith(prefix) for prefix in self.filter_config["after_must_str"]):
return None
else:
for prefix in self.filter_config["after_must_str"]:
if content.endswith(prefix):
content = content[:-len(prefix)] # 删除匹配的结尾
break
# 全为标点符号
if My_handle.common.is_punctuation_string(content):
return None
# 换行转为,
content = content.replace('\n', ',')
# 语言检测
if My_handle.common.lang_check(content, self.need_lang) is None:
logging.warning("语言检测不通过,已过滤")
return None
return content
# 违禁处理
def prohibitions_handle(self, content):
"""违禁处理
Args:
content (str): 带判断的字符串内容
Returns:
bool: 是否违禁词 是True 否False
"""
# 含有违禁词/链接
if My_handle.common.profanity_content(content) or My_handle.common.is_url_check(content):
logging.warning(f"违禁词/链接:{content}")
return True
# 违禁词过滤
if self.filter_config["badwords_path"] != "":
if My_handle.common.check_sensitive_words2(self.filter_config["badwords_path"], content):
logging.warning(f"本地违禁词:{content}")
return True
# 同拼音违禁词过滤
if self.filter_config["bad_pinyin_path"] != "":
if My_handle.common.check_sensitive_words3(self.filter_config["bad_pinyin_path"], content):
logging.warning(f"同音违禁词:{content}")
return True
return False
# 直接复读
def reread_handle(self, data):
"""复读处理
Args:
data (dict): 包含用户名,弹幕内容
Returns:
_type_: 寂寞
"""
user_name = data["user_name"]
content = data["content"]
logging.info(f"复读内容:{content}")
# 音频合成时需要用到的重要数据
message = {
"type": "reread",
"tts_type": My_handle.audio_synthesis_type,
"data": My_handle.config.get(My_handle.audio_synthesis_type),
"config": self.filter_config,
"user_name": user_name,
"content": content
}
self.audio_synthesis_handle(message)
# LLM处理
def llm_handle(self, chat_type, data):
"""LLM统一处理
Args:
chat_type (str): 聊天类型
data (str): dict,含用户名和内容
Returns:
str: LLM返回的结果
"""
resp_content = None
if chat_type == "chatgpt":
# 调用gpt接口,获取返回内容
resp_content = self.chatgpt.get_gpt_resp(data["user_name"], data["content"])
elif chat_type == "claude":
resp_content = self.claude.get_claude_resp(data["content"])
elif chat_type == "claude2":
resp_content = self.claude2.get_claude2_resp(data["content"])
elif chat_type == "chatterbot":
# 生成回复
resp_content = self.bot.get_response(data["content"]).text
elif chat_type == "chatglm":
resp_content = self.chatglm.get_chatglm_resp(data["content"])
elif chat_type == "chat_with_file":
resp_content = self.chat_with_file.get_model_resp(data["content"])
elif chat_type == "text_generation_webui":
# 生成回复
resp_content = self.text_generation_webui.get_text_generation_webui_resp(data["content"])
elif chat_type == "sparkdesk":
# 生成回复
resp_content = self.sparkdesk.get_sparkdesk_resp(data["content"])
elif chat_type == "langchain_chatglm":
# 生成回复
resp_content = self.langchain_chatglm.get_resp(data["content"])
elif chat_type == "zhipu":
# 生成回复
resp_content = self.zhipu.get_resp(data["content"])
elif chat_type == "bard":
# 生成回复
resp_content = self.bard_api.get_resp(data["content"])
elif chat_type == "yiyan":
# 生成回复
resp_content = self.yiyan.get_resp(data["content"])
elif chat_type == "tongyi":
# 生成回复
resp_content = self.tongyi.get_resp(data["content"])
elif chat_type == "reread":
# 复读机
resp_content = data["content"]
elif chat_type == "none":
# 不启用
pass
else:
resp_content = data["content"]
return resp_content
# 积分处理
def integral_handle(self, type, data):
"""积分处理
Args:
type (str): 消息数据类型(comment/gift/entrance)
data (dict): 平台侧传入的data数据,直接拿来做解析
Returns:
bool: 是否正常触发了积分事件,是True 否False
"""
user_name = data["username"]
if My_handle.config.get("integral", "enable"):
# 根据消息类型进行对应处理
if "comment" == type:
content = data["content"]
# 是否开启了签到功能
if My_handle.config.get("integral", "sign", "enable"):
# 判断弹幕内容是否是命令
if content in My_handle.config.get("integral", "sign", "cmd"):
# 查询数据库中是否有当前用户的积分记录(缺个UID)
common_sql = '''
SELECT * FROM integral WHERE username =?
'''
integral_data = self.db.fetch_all(common_sql, (user_name,))
logging.debug(f"integral_data={integral_data}")
# 获取文案并合成语音,传入签到天数自动检索
def get_copywriting_and_audio_synthesis(sign_num):
# 判断当前签到天数在哪个签到数区间内,根据不同的区间提供不同的文案回复
for integral_sign_copywriting in My_handle.config.get("integral", "sign", "copywriting"):
# 在此区间范围内,所以你的配置一定要对,不然这里就崩溃了!!!
if int(integral_sign_copywriting["sign_num_interval"].split("-")[0]) <= \
sign_num <= \
int(integral_sign_copywriting["sign_num_interval"].split("-")[1]):
# 匹配文案
resp_content = random.choice(integral_sign_copywriting["copywriting"])
logging.debug(f"resp_content={resp_content}")
data_json = {
"user_name": data["username"],
"get_integral": int(My_handle.config.get("integral", "sign", "get_integral")),
"sign_num": sign_num + 1
}