forked from Ikaros-521/AI-Vtuber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
my_handle.py
2862 lines (2291 loc) · 135 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, sys, threading, json, random
import difflib
import logging
from datetime import datetime
import traceback
import importlib
import pyautogui
import copy
import re
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 SingletonMeta(type):
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances:
cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class My_handle(metaclass=SingletonMeta):
common = None
config = None
audio = None
my_translate = None
# 是否在数据处理中
is_handleing = 0
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
}
}
# 答谢板块文案数据临时存储
thanks_entrance_copy = []
thanks_gift_copy = []
thanks_follow_copy = []
def __init__(self, config_path):
logging.info("初始化My_handle...")
try:
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"
# }
# 数据丢弃部分相关的实现
self.data_lock = threading.Lock()
self.timers = {}
self.db = None
# 设置会话初始值
self.session_config = None
self.sessions = {}
self.current_key_index = 0
# 点歌模块
self.choose_song_song_lists = None
"""
新增LLM后,这边先定义下各个变量,下面会用到
"""
self.chatgpt = None
self.claude = None
self.claude2 = None
self.chatglm = None
self.qwen = None
self.chat_with_file = None
self.text_generation_webui = None
self.sparkdesk = None
self.langchain_chatglm = None
self.langchain_chatchat = None
self.zhipu = None
self.bard_api = None
self.yiyan = None
self.tongyi = None
self.tongyixingchen = None
self.my_qianfan = None
self.my_wenxinworkshop = None
self.gemini = None
self.qanything = None
self.koboldcpp = None
self.anythingllm = None
self.image_recognition_model = None
self.chat_type_list = ["chatgpt", "claude", "claude2", "chatglm", "qwen", "chat_with_file", "text_generation_webui", \
"sparkdesk", "langchain_chatglm", "langchain_chatchat", "zhipu", "bard", "yiyan", "tongyi", \
"tongyixingchen", "my_qianfan", "my_wenxinworkshop", "gemini", "qanything", "koboldcpp", "anythingllm"]
# 配置加载
self.config_load()
logging.info(f"配置数据加载成功。")
except Exception as e:
logging.error(traceback.format_exc())
# 是否位于数据处理状态
def is_handle_empty(self):
return My_handle.is_handleing
# 音频队列、播放相关情况
def is_audio_queue_empty(self):
return My_handle.audio.is_audio_queue_empty()
def get_chat_model(self, chat_type, config):
if chat_type == "claude":
self.claude = GPT_MODEL.get(chat_type)
if not self.claude.reset_claude():
logging.error("重置Claude会话失败喵~")
elif chat_type == "claude2":
GPT_MODEL.set_model_config(chat_type, config.get(chat_type))
self.claude2 = GPT_MODEL.get(chat_type)
if self.claude2.get_organization_id() is None:
logging.error("重置Claude2会话失败喵~")
else:
if chat_type in ["chatterbot", "chat_with_file"]:
# 对这些类型做特殊处理
pass
else:
GPT_MODEL.set_model_config(chat_type, config.get(chat_type))
self.__dict__[chat_type] = GPT_MODEL.get(chat_type)
def get_vision_model(self, chat_type, config):
GPT_MODEL.set_vision_model_config(chat_type, config)
self.image_recognition_model = GPT_MODEL.get(chat_type)
def handle_chat_type(self):
chat_type = My_handle.config.get("chat_type")
self.get_chat_model(chat_type, My_handle.config)
if 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"]
)
except Exception as e:
logging.info(e)
exit(0)
elif 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 chat_type == "game":
self.game = importlib.import_module("game." + My_handle.config.get("game", "module_name"))
# 配置加载
def config_load(self):
self.session_config = {'msg': [{"role": "system", "content": My_handle.config.get('chatgpt', 'preset')}]}
# 设置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"))
# 聊天相关类实例化
self.handle_chat_type()
# 判断是否使能了SD
if My_handle.config.get("sd")["enable"]:
from utils.sd import SD
self.sd = SD(My_handle.config.get("sd"))
# 日志文件路径
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.debug('创建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.debug('创建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.debug('创建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.debug('创建integral(积分)表')
except Exception as e:
logging.error(traceback.format_exc())
# 重载config
def reload_config(self, config_path):
My_handle.config = Config(config_path)
My_handle.audio.reload_config(config_path)
My_handle.my_translate.reload_config(config_path)
self.config_load()
# 回传给webui,用于聊天内容显示
def webui_show_chat_log_callback(self, data_type: str, data: dict, resp_content: str):
"""回传给webui,用于聊天内容显示
Args:
data_type (str): 数据内容的类型(多指LLM)
data (dict): 数据JSON
resp_content (str): 显示的聊天内容的文本
"""
try:
if My_handle.config.get("talk", "show_chat_log") == True:
if "ori_username" not in data:
data["ori_username"] = data["username"]
if "ori_content" not in data:
data["ori_content"] = data["content"]
# 返回给webui的数据
return_webui_json = {
"type": "llm",
"data": {
"type": data_type,
"username": data["ori_username"],
"content_type": "answer",
"content": f"错误:{data_type}无返回,请查看日志" if resp_content is None else resp_content,
"timestamp": My_handle.common.get_bj_time(0)
}
}
tmp_json = My_handle.common.send_request(f'http://{My_handle.config.get("webui", "ip")}:{My_handle.config.get("webui", "port")}/callback', "POST", return_webui_json, timeout=30)
except Exception as e:
logging.error(traceback.format_exc())
# 获取房间号
def get_room_id(self):
return My_handle.config.get("room_display_id")
# 音频合成处理
def audio_synthesis_handle(self, data_json):
"""音频合成处理
Args:
data_json (dict): 传递的json数据
核心参数:
type目前有
reread_top_priority 最高优先级-复读
comment 弹幕
local_qa_audio 本地问答音频
song 歌曲
reread 复读
key_mapping 按键映射
integral 积分
read_comment 念弹幕
gift 礼物
entrance 用户入场
follow 用户关注
schedule 定时任务
idle_time_task 闲时任务
abnormal_alarm 异常报警
image_recognition_schedule 图像识别定时任务
"""
if "content" in data_json:
if data_json['content']:
# 替换文本内容中\n为空
data_json['content'] = data_json['content'].replace('\n', '')
# 如果虚拟身体-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)
logging.debug(f'data_json={data_json}')
# 数据类型不在需要触发助播条件的范围内,则直接返回
if data_json["type"] not in My_handle.config.get("assistant_anchor", "type"):
return
# 1、匹配本地问答库 触发后不执行后面的其他功能
if My_handle.config.get("assistant_anchor", "local_qa", "text", "enable") == True:
# 根据类型,执行不同的问答匹配算法
if My_handle.config.get("assistant_anchor", "local_qa", "text", "format") == "text":
tmp = self.find_answer(data_json["content"], My_handle.config.get("assistant_anchor", "local_qa", "text", "file_path"), My_handle.config.get("assistant_anchor", "local_qa", "text", "similarity"))
else:
tmp = self.find_similar_answer(data_json["content"], My_handle.config.get("assistant_anchor", "local_qa", "text", "file_path"), My_handle.config.get("assistant_anchor", "local_qa", "text", "similarity"))
if tmp != None:
logging.info(f'触发本地问答库-文本 [{My_handle.config.get("assistant_anchor", "username")}]: {data_json["content"]}')
# 将问答库中设定的参数替换为指定内容,开发者可以自定义替换内容
# 假设有多个未知变量,用户可以在此处定义动态变量
variables = {
'cur_time': My_handle.common.get_bj_time(5),
'username': My_handle.config.get("assistant_anchor", "username")
}
# 使用字典进行字符串替换
if any(var in tmp for var in variables):
tmp = tmp.format(**{var: value for var, value in variables.items() if var in 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'[{My_handle.config.get("assistant_anchor", "username")} 提问]:{data_json["content"]}\n[AI回复{My_handle.config.get("assistant_anchor", "username")}]:{resp_content_joined}\n' + tmp_content)
elif My_handle.config.get("comment_log_type") == "问题":
f.write(f'[{My_handle.config.get("assistant_anchor", "username")} 提问]:{data_json["content"]}\n' + tmp_content)
elif My_handle.config.get("comment_log_type") == "回答":
f.write(f'[AI回复{My_handle.config.get("assistant_anchor", "username")}]:{resp_content_joined}\n' + tmp_content)
message = {
"type": "assistant_anchor_text",
"tts_type": My_handle.config.get("assistant_anchor", "audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("assistant_anchor", "audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": My_handle.config.get("assistant_anchor", "username"),
"content": resp_content
}
if "insert_index" in message:
message["insert_index"] = data_json["insert_index"]
My_handle.audio.audio_synthesis(message)
return True
# 如果开启了助播功能,则根据当前播放内容的文本信息,进行助播音频的播放
if My_handle.config.get("assistant_anchor", "enable") == True:
# 2、匹配本地问答音频库 触发后不执行后面的其他功能
if My_handle.config.get("assistant_anchor", "local_qa", "audio", "enable") == True:
# 输出当前用户发送的弹幕消息
# logging.info(f"[{username}]: {content}")
# 获取本地问答音频库文件夹内所有的音频文件名
local_qa_audio_filename_list = My_handle.audio.get_dir_audios_filename(My_handle.config.get("assistant_anchor", "local_qa", "audio", "file_path"), type=1)
local_qa_audio_list = My_handle.audio.get_dir_audios_filename(My_handle.config.get("assistant_anchor", "local_qa", "audio", "file_path"), type=0)
if My_handle.config.get("assistant_anchor", "local_qa", "audio", "type") == "相似度匹配":
# 不含拓展名,在本地音频名列表中做查找
local_qv_audio_filename = My_handle.common.find_best_match(data_json["content"], local_qa_audio_filename_list, My_handle.config.get("assistant_anchor", "local_qa", "audio", "similarity"))
elif My_handle.config.get("assistant_anchor", "local_qa", "audio", "type") == "包含关系":
# 在本地音频名列表中查找是否包含于当前这个传入的文本内容
local_qv_audio_filename = My_handle.common.find_substring_in_list(data_json["content"], local_qa_audio_filename_list)
# print(f"local_qv_audio_filename={local_qv_audio_filename}")
# 找到了匹配的结果
if local_qv_audio_filename is not None:
logging.info(f'触发 助播 本地问答库-语音 [{My_handle.config.get("assistant_anchor", "username")}]: {data_json["content"]}')
# 把结果从原文件名列表中在查找一遍,补上拓展名。相似度设置为0,就能必定有返回的结果
local_qv_audio_filename = My_handle.common.find_best_match(local_qv_audio_filename, local_qa_audio_list, 0)
# 寻找对应的文件
resp_content = My_handle.audio.search_files(My_handle.config.get("assistant_anchor", "local_qa", "audio", "file_path"), local_qv_audio_filename)
if resp_content != []:
logging.debug(f"匹配到的音频原相对路径:{resp_content[0]}")
# 拼接音频文件路径
resp_content = f'{My_handle.config.get("assistant_anchor", "local_qa", "audio", "file_path")}/{resp_content[0]}'
logging.info(f"匹配到的音频路径:{resp_content}")
message = {
"type": "assistant_anchor_audio",
"tts_type": My_handle.config.get("assistant_anchor", "audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("assistant_anchor", "audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": My_handle.config.get("assistant_anchor", "username"),
"content": data_json["content"],
"file_path": resp_content
}
if "insert_index" in message:
message["insert_index"] = data_json["insert_index"]
My_handle.audio.audio_synthesis(message)
return True
# 从本地问答库中搜索问题的答案(文本数据是一问一答的单行格式)
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
# 本地问答库 文本模式 根据相似度查找答案(文本数据是json格式)
def find_similar_answer(self, input_str, qa_file_path, min_similarity=0.8):
"""本地问答库 文本模式 根据相似度查找答案(文本数据是json格式)
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 json.JSONDecodeError:
logging.error(traceback.format_exc())
logging.error(f"本地问答库 文本模式,JSON文件:{file_path},加载失败,文件JSON格式出错,请进行修改匹配格式!")
return None
except FileNotFoundError:
logging.error(traceback.format_exc())
logging.error(f"本地问答库 文本模式,JSON文件:{file_path}不存在!")
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: 是否触发并处理
"""
username = data["username"]
content = data["content"]
# 合并字符串末尾连续的* 主要针对获取不到用户名的情况
username = My_handle.common.merge_consecutive_asterisks(username)
# 最大保留的用户名长度
username = username[:self.config.get("local_qa", "text", "username_max_len")]
# 1、匹配本地问答库 触发后不执行后面的其他功能
if My_handle.config.get("local_qa", "text", "enable") == True:
# 根据类型,执行不同的问答匹配算法
if My_handle.config.get("local_qa", "text", "type") == "text":
tmp = self.find_answer(content, My_handle.config.get("local_qa", "text", "file_path"), My_handle.config.get("local_qa", "text", "similarity"))
else:
tmp = self.find_similar_answer(content, My_handle.config.get("local_qa", "text", "file_path"), My_handle.config.get("local_qa", "text", "similarity"))
if tmp != None:
logging.info(f"触发本地问答库-文本 [{username}]: {content}")
# 将问答库中设定的参数替换为指定内容,开发者可以自定义替换内容
# 假设有多个未知变量,用户可以在此处定义动态变量
variables = {
'cur_time': My_handle.common.get_bj_time(5),
'username': username
}
# 使用字典进行字符串替换
if any(var in tmp for var in variables):
tmp = tmp.format(**{var: value for var, value in variables.items() if var in 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"[{username} 提问]:{content}\n[AI回复{username}]:{resp_content_joined}\n" + tmp_content)
elif My_handle.config.get("comment_log_type") == "问题":
f.write(f"[{username} 提问]:{content}\n" + tmp_content)
elif My_handle.config.get("comment_log_type") == "回答":
f.write(f"[AI回复{username}]:{resp_content_joined}\n" + tmp_content)
message = {
"type": "comment",
"tts_type": My_handle.config.get("audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": username,
"content": resp_content
}
self.webui_show_chat_log_callback("本地问答-文本", data, resp_content)
self.audio_synthesis_handle(message)
return True
# 2、匹配本地问答音频库 触发后不执行后面的其他功能
if My_handle.config.get("local_qa")["audio"]["enable"] == True:
# 输出当前用户发送的弹幕消息
# logging.info(f"[{username}]: {content}")
# 获取本地问答音频库文件夹内所有的音频文件名
local_qa_audio_filename_list = My_handle.audio.get_dir_audios_filename(My_handle.config.get("local_qa", "audio", "file_path"), type=1)
local_qa_audio_list = My_handle.audio.get_dir_audios_filename(My_handle.config.get("local_qa", "audio", "file_path"), type=0)
# 不含拓展名做查找
local_qv_audio_filename = My_handle.common.find_best_match(content, local_qa_audio_filename_list, My_handle.config.get("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"触发本地问答库-语音 [{username}]: {content}")
# 把结果从原文件名列表中在查找一遍,补上拓展名
local_qv_audio_filename = My_handle.common.find_best_match(local_qv_audio_filename, local_qa_audio_list, 0)
# 寻找对应的文件
resp_content = My_handle.audio.search_files(My_handle.config.get("local_qa", "audio", "file_path"), local_qv_audio_filename)
if resp_content != []:
logging.debug(f"匹配到的音频原相对路径:{resp_content[0]}")
# 拼接音频文件路径
resp_content = f'{My_handle.config.get("local_qa", "audio", "file_path")}/{resp_content[0]}'
logging.info(f"匹配到的音频路径:{resp_content}")
message = {
"type": "local_qa_audio",
"tts_type": My_handle.config.get("audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": username,
"content": content,
"file_path": resp_content
}
self.webui_show_chat_log_callback("本地问答-音频", data, resp_content)
self.audio_synthesis_handle(message)
return True
return False
# 点歌模式 处理
def choose_song_handle(self, data):
"""点歌模式 处理
Args:
data (dict): 用户名 弹幕数据
Returns:
bool: 是否触发并处理
"""
username = data["username"]
content = data["content"]
# 合并字符串末尾连续的* 主要针对获取不到用户名的情况
username = My_handle.common.merge_consecutive_asterisks(username)
if My_handle.config.get("choose_song")["enable"] == True:
start_cmd = My_handle.common.starts_with_any(content, My_handle.config.get("choose_song", "start_cmd"))
stop_cmd = My_handle.common.starts_with_any(content, My_handle.config.get("choose_song", "stop_cmd"))
random_cmd = My_handle.common.starts_with_any(content, My_handle.config.get("choose_song", "random_cmd"))
# 判断随机点歌命令是否正确
if random_cmd:
resp_content = My_handle.common.random_search_a_audio_file(My_handle.config.get("choose_song", "song_path"))
if resp_content is None:
return True
logging.info(f"随机到的音频路径:{resp_content}")
message = {
"type": "song",
"tts_type": My_handle.config.get("audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": username,
"content": resp_content
}
self.audio_synthesis_handle(message)
self.webui_show_chat_log_callback("点歌", data, resp_content)
return True
# 判断点歌命令是否正确
elif start_cmd:
logging.info(f"[{username}]: {content}")
# 获取本地音频文件夹内所有的音频文件名(不含拓展名)
choose_song_song_lists = My_handle.audio.get_dir_audios_filename(My_handle.config.get("choose_song", "song_path"), 1)
# 去除命令前缀
content = content[len(start_cmd):]
# 说明用户仅发送命令,没有发送歌名,说明用户不会用
if content == "":
resp_content = f'点歌命令错误,命令为 {My_handle.config.get("choose_song", "start_cmd")}+歌名'
message = {
"type": "comment",
"tts_type": My_handle.config.get("audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": username,
"content": resp_content
}
self.audio_synthesis_handle(message)
self.webui_show_chat_log_callback("点歌", data, resp_content)
return True
# 判断是否有此歌曲
song_filename = My_handle.common.find_best_match(content, choose_song_song_lists, similarity=My_handle.config.get("choose_song", "similarity"))
if song_filename is None:
# resp_content = f"抱歉,我还没学会唱{content}"
# 根据配置的 匹配失败回复文案来进行合成
resp_content = My_handle.config.get("choose_song", "match_fail_copy").format(content=content)
logging.info(f"[AI回复{username}]:{resp_content}")
message = {
"type": "comment",
"tts_type": My_handle.config.get("audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": username,
"content": resp_content
}
self.audio_synthesis_handle(message)
self.webui_show_chat_log_callback("点歌", data, resp_content)
return True
resp_content = My_handle.audio.search_files(My_handle.config.get('choose_song', 'song_path'), song_filename, True)
if resp_content == []:
return True
logging.debug(f"匹配到的音频原相对路径:{resp_content[0]}")
# 拼接音频文件路径
resp_content = f"{My_handle.config.get('choose_song', 'song_path')}/{resp_content[0]}"
resp_content = os.path.abspath(resp_content)
logging.info(f"点歌成功!匹配到的音频路径:{resp_content}")
message = {
"type": "song",
"tts_type": My_handle.config.get("audio_synthesis_type"),
"data": My_handle.config.get(My_handle.config.get("audio_synthesis_type")),
"config": My_handle.config.get("filter"),
"username": username,
"content": resp_content
}
self.webui_show_chat_log_callback("点歌", data, resp_content)
self.audio_synthesis_handle(message)
return True
# 判断取消点歌命令是否正确
elif stop_cmd:
My_handle.audio.stop_current_audio()
return True
return False
"""
]@@@@@ =@@ @@^ =@@@@@@]. .@@` ./@@@ ,@@@^ /@^
@@^ @@* =@@ @@^ =@@ ,@@\ =@@ @@^
\@@]. =@@@@@.=@@@@@` =@@@@@@@. @@^ ./@@@@\. =@@ .@@^.@@.@@@@@@@@@@@.@@ @@^ /@@@@^ @@^ ./@@@@@] @@/@@@@.
,\@@\ @@* .]]/@@ =@@. =@\ @@^ @@\]]/@^ =@@ @@^.@@. =@@ @@^ .@@ @@^ @@\` @@^ @@^ \@^ @@` \@^
@@^ @@* ,@@` =@@ =@@ =@/ @@^ @@` =@@ ./@/ .@@. =@@ @@^ .@@. @@^ ,\@@ @@^ @@^ /@^ @@* =@^
.@@@@@@/ \@@@.@@@@@@@ =@@@@@@/ @@^ .\@@@@@. =@@@@@@/` .@@. =@@ @@^ =@@@@@@^.@@@@@^ @@^ .\@@@@@` @@* =@^
"""
# 画图模式 SD 处理
def sd_handle(self, data):
"""画图模式 SD 处理
Args:
data (dict): 用户名 弹幕数据
Returns:
bool: 是否触发并处理
"""
username = data["username"]
content = data["content"]
# 合并字符串末尾连续的* 主要针对获取不到用户名的情况
username = My_handle.common.merge_consecutive_asterisks(username)
if content.startswith(My_handle.config.get("sd", "trigger")):
# 违禁检测
content = self.prohibitions_handle(content)
if content is None:
return
if My_handle.config.get("sd", "enable") == False:
logging.info("您还未启用SD模式,无法使用画画功能")
return True
else:
# 输出当前用户发送的弹幕消息
logging.info(f"[{username}]: {content}")
# 删除文本中的命令前缀
content = content[len(My_handle.config.get("sd", "trigger")):]
if My_handle.config.get("sd", "translate_type") != "none":
# 判断翻译类型 进行翻译工作
tmp = My_handle.my_translate.trans(content, My_handle.config.get("sd", "translate_type"))
if tmp:
content = tmp
"""
根据聊天类型执行不同逻辑
"""
chat_type = My_handle.config.get("sd", "prompt_llm", "type")
if chat_type in self.chat_type_list:
content = My_handle.config.get("sd", "prompt_llm", "before_prompt") + \
content + My_handle.config.get("after_prompt")
data_json = {
"username": username,
"content": content,
"ori_username": data["username"],
"ori_content": data["content"]
}
resp_content = self.llm_handle(chat_type, data_json)
if resp_content is not None:
logging.info(f"[AI回复{username}]:{resp_content}")
else:
resp_content = ""
logging.warning(f"警告:{chat_type}无返回")
elif chat_type == "none" or chat_type == "reread" or chat_type == "game":
resp_content = content
else:
resp_content = content
logging.info(f"传给SD接口的内容:{resp_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起始,如果是则返回None
if My_handle.config.get("filter", "before_filter_str") and any(
content.startswith(prefix) for prefix in My_handle.config.get("filter", "before_filter_str")):
return None
# 判断弹幕是否以xx结尾,如果是则返回None
if My_handle.config.get("filter", "after_filter_str") and any(
content.endswith(prefix) for prefix in My_handle.config.get("filter", "after_filter_str")):
return None
# 判断弹幕是否以xx起始,如果不是则返回None
if My_handle.config.get("filter", "before_must_str") and not any(
content.startswith(prefix) for prefix in My_handle.config.get("filter", "before_must_str")):
return None
else:
for prefix in My_handle.config.get("filter", "before_must_str"):
if content.startswith(prefix):
content = content[len(prefix):] # 删除匹配的开头
break