-
Notifications
You must be signed in to change notification settings - Fork 1
/
chatglm_character_instruction_add_charas_gradio.py
1341 lines (1256 loc) · 49.5 KB
/
chatglm_character_instruction_add_charas_gradio.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
#### pip install gradio==3.50.2
import gradio as gr
import pandas as pd
import numpy as np
import os
import json
import re
from functools import partial
from rapidfuzz import fuzz
import imagehash
from datasets import load_dataset
from PIL import Image
character_img_ds = load_dataset("svjack/genshin-impact-character-image-add-some")
character_img_dict = dict(pd.Series(character_img_ds["train"]).map(lambda x: (x["name"], x["img"])).values.tolist())
partial_order_list = ['迭卡拉庇安',
'安德留斯',
'温妮莎',
'特瓦林',
'法尔伽',
'艾伦德林',
'鲁斯坦',
'奥兹',
'炎之魔女',
'杜林',
'克利普斯',
'归终',
'赫乌莉亚',
'奥赛尔',
'马科修斯',
'若陀龙王',
'浮舍',
'铜雀',
'削月筑阳真君',
'理水叠山真君',
'留云借风真君',
'歌尘浪市真君',
'移霄导天真君',
'天叔',
'跋掣',
'奥罗巴斯',
'狐斋宫',
'御舆千代',
'五百藏',
'百代',
'九条孝行',
'九条镰治',
'柊慎介',
'柊千里',
'哲平',
'散兵倾奇者',
'阿瑠',
'雪奈茨芙娜',
'阿赫玛尔',
'阿扎尔',
'迪娜泽黛',
'泽维尔']
partial_order_list += [
'那维莱特',
"芙宁娜",
'魈',
"可莉",
"提纳里",
#"行秋", "柯莱", "凝光", "北斗", "五郎",
'钟离',
'纳西妲',
'刻晴',
'优菈',
'八重神子',
#'可莉',
'夜兰',
'妮露',
'娜维娅',
'宵宫',
#'提纳里',
'林尼',
'枫原万叶',
'流浪者',
'温迪',
'珊瑚宫心海',
'琴',
'甘雨',
'申鹤',
'白术',
'神里绫人',
'神里绫华',
'胡桃',
'艾尔海森',
#'芙宁娜',
'荒泷一斗',
'莫娜',
'莱欧斯利',
'赛诺',
'达达利亚',
'迪卢克',
'迪希雅',
'阿贝多',
'雷电将军',
'七七'
]
im_list_a = []
im_list_b = []
for character_name, character_img in character_img_dict.items():
if character_name in partial_order_list:
im_list_a.append(character_img)
else:
im_list_b.append(character_img)
assert len(im_list_a) == len(partial_order_list)
im_list = pd.Series(partial_order_list).map(lambda x: character_img_dict[x]).values.tolist() + im_list_b
import jieba
def repeat_to_one_f(x):
req = None
for token in jieba.lcut(x):
#print("req :", req)
if len(set(token)) == 1:
token = token[0]
if req is None:
req = token
else:
if token in req:
continue
else:
while req.endswith(token[0]):
token = token[1:]
req = req + token
return req.strip()
def repeat_to_one_fb(x):
return sorted(map(repeat_to_one_f, [x, "".join(jieba.lcut(x)[::-1])]),
key = len
)[0]
repeat_to_one = repeat_to_one_fb
def process_row(x, names):
assert type(names) == type([])
x = x.strip()
if not x:
return x
first_char = x[0]
if first_char in map(lambda y: y[0], names):
return x
if first_char in [":", ":"]:
return x[1:]
if first_char in "".join(names):
req = {}
for name in names:
merged = name
find_it = False
for ele in jieba.lcut(x):
if merged.endswith(ele) and not find_it:
continue
else:
find_it = True
merged += ele
if find_it:
req[name] = merged
#print(req)
return sorted(req.items(), key = lambda t2: len(t2[1][len(t2[0]):]))[0][1]
return x
def process_info(x, maintain_chars = ",.。,;::;??\n——"):
req = re.findall(u"[0-9\u4e00-\u9fa5{}]+".format(maintain_chars) ,x)
return "".join(req)
from huggingface_hub import snapshot_download
if not os.path.exists("genshin-impact-character-add-some"):
path = snapshot_download(
repo_id="svjack/genshin-impact-character-add-some",
repo_type="dataset",
local_dir="genshin-impact-character-add-some",
local_dir_use_symlinks = False
)
if not os.path.exists("genshin_impact_character_glm6b_base_ggml"):
path = snapshot_download(
repo_id="svjack/genshin_impact_character_glm6b_base_ggml",
repo_type="model",
local_dir="genshin_impact_character_glm6b_base_ggml",
local_dir_use_symlinks = False
)
info_df = pd.read_csv("genshin-impact-character-add-some/genshin_impact_background_settings_constrained.csv")
info_df["info"] = info_df["info"].map(eval)
with open("genshin-impact-character-add-some/genshin_impact_character_setting.json", "r") as f:
character_setting_total_dict = json.load(f)
req_dict = {}
for k, v_dict in character_setting_total_dict.items():
req_dict[k] = {}
for kk, vv in v_dict.items():
if kk != "元素力":
req_dict[k][kk] = vv
character_setting_total_dict = req_dict
def get_character_background_list(info_dict):
text = []
if "角色详细" in info_dict["描述"]:
text.append(info_dict["描述"]["角色详细"])
if "更多描述" in info_dict["描述"]:
text.append(info_dict["描述"]["更多描述"])
return list(map(lambda x: x.replace(" ", "").replace("\n\n", "\n"), text))
def get_character_background(info_dict):
return "\n".join(get_character_background_list(info_dict))
pd.DataFrame(
pd.Series(character_setting_total_dict.values()).map(
lambda x: {
"性别": x['性别'],
"国籍": x["国籍"]
}
).values.tolist()).apply(lambda x: set(x), axis = 0).to_dict()
character_setting_total_dist_dict = {
'姓名': "",
'性别': {'少女女性', '少年男性', '成年女性', '成年男性'},
'国籍': {'枫丹', '璃月', '稻妻', '至冬', '蒙德', '须弥'},
'身份': "",
'性格特征': "",
'角色介绍': "",
}
def get_character_setting_total_dict(name):
from copy import deepcopy
req = deepcopy(character_setting_total_dist_dict)
if name in character_setting_total_dict:
for k, v in character_setting_total_dict[name].items():
req[k] = v
info_dict = dict(info_df[["title", "info"]].values.tolist())[name]
req["角色介绍"] = get_character_background(info_dict)
req["姓名"] = name
return req
prompt_format_dict = {
"Basic_Info": ["性别", "国籍", "身份", "性格特征"],
"两人同属{}": ["国籍"],
"{}来自{},{}来自{}。": ["姓名", "国籍", "姓名", "国籍"],
"下面是{}的一些基本信息\n{}": ["姓名", "Basic_Info"],
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"],
"续写下面的角色介绍,下面是角色介绍的开头。{}是{}。{}": ["姓名", "身份", "Text"],
"续写下面的角色故事,下面是角色故事的开头。{}是{}。{}": ["姓名", "身份", "Text"],
"续写下面获得神之眼的过程,下面是开头。{}是{}。{}": ["姓名", "身份", "Text"],
"{}给你写了一封信,信主题是{},信的内容是这样的。": ["姓名", "Text"],
"{}在进行有关{}的聊天时会说什么?": ["姓名", "Text"],
"{}在{}的时候会说什么?": ["姓名", "Text"],
"{}在{}时会说什么?": ["姓名", "Text"],
"关于{},{}会说什么?": ["Text", "姓名"],
"当你想要了解{}时": ["姓名"],
"关于{},{}会说什么?": ["姓名", "姓名"],
"从{}那里,可以获得哪些关于{}的信息?": ["姓名", "姓名"]
}
def single_character_prompt_func(name,
used_prompt_format_dict,
character_setting_rewrite_dict = {},
Text = "",
):
assert type(used_prompt_format_dict) == type({})
assert type(character_setting_rewrite_dict) == type({})
character_setting_total_dict = get_character_setting_total_dict(name)
for k, v in character_setting_rewrite_dict.items():
if k in character_setting_total_dict:
character_setting_total_dict[k] = v
key = list(used_prompt_format_dict.keys())[0]
assert key in prompt_format_dict
if key == "Basic_Info":
return "\n".join(
map(lambda k: "{}:{}".format(k, character_setting_total_dict[k]), prompt_format_dict[key])
)
elif key == "两人同属{}":
return "两人同属{}".format(character_setting_total_dict["国籍"])
elif key == "下面是{}的一些基本信息\n{}":
return "下面是{}的一些基本信息\n{}".format(name,
single_character_prompt_func(name,
{
"Basic_Info": ["性别", "国籍", "身份", "性格特征"]
},
character_setting_rewrite_dict
)
)
elif key == "下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}":
return "下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}".format(
name,
single_character_prompt_func(name,
{
"Basic_Info": ["性别", "国籍", "身份", "性格特征"]
},
character_setting_rewrite_dict
),
character_setting_total_dict["角色介绍"]
)
elif key == "续写下面的角色介绍,下面是角色介绍的开头。{}是{}。{}":
return "续写下面的角色介绍,下面是角色介绍的开头。{}是{}。{}".format(
name,
character_setting_total_dict["身份"],
Text
)
elif key == "续写下面的角色故事,下面是角色故事的开头。{}是{}。{}":
return "续写下面的角色故事,下面是角色介绍的开头。{}是{}。{}".format(
name,
character_setting_total_dict["身份"],
Text
)
elif key == "续写下面获得神之眼的过程,下面是开头。{}是{}。{}":
return "续写下面获得神之眼的过程,下面是开头。{}是{}。{}".format(
name,
character_setting_total_dict["身份"],
Text
)
elif key == "{}给你写了一封信,信主题是{},信的内容是这样的。":
return "{}给你写了一封信,信主题是{},信的内容是这样的。".format(
name,
Text
)
elif key == "{}在进行有关{}的聊天时会说什么?":
return "{}在进行有关{}的聊天时会说什么?".format(
name,
Text
)
elif key == "{}在{}的时候会说什么?":
return "{}在{}的时候会说什么?".format(
name,
Text
)
elif key == "{}在{}时会说什么?":
return "{}在{}时会说什么?".format(
name,
Text
)
elif key == "关于{},{}会说什么?":
return "关于{},{}会说什么?".format(
Text,
name,
)
elif key == "当你想要了解{}时":
return "当你想要了解{}时".format(
name,
)
return 1 / 0
def two_character_prompt_func(
name_1,
name_2,
used_prompt_format_dict,
character_setting_rewrite_dict_1 = {},
character_setting_rewrite_dict_2 = {},
):
assert type(character_setting_rewrite_dict_1) == type({})
character_setting_total_dict_1 = get_character_setting_total_dict(name_1)
for k, v in character_setting_rewrite_dict_1.items():
if k in character_setting_total_dict_1:
character_setting_total_dict_1[k] = v
character_setting_total_dict_2 = get_character_setting_total_dict(name_2)
for k, v in character_setting_rewrite_dict_2.items():
if k in character_setting_total_dict_2:
character_setting_total_dict_2[k] = v
key = list(used_prompt_format_dict.keys())[0]
assert key in prompt_format_dict
if key == "关于{},{}会说什么?":
return "关于{},{}会说什么?".format(name_1, name_2)
elif key == "从{}那里,可以获得哪些关于{}的信息?":
return "从{}那里,可以获得哪些关于{}的信息?".format(name_1, name_2)
elif key == "{}来自{},{}来自{}。":
return "{}来自{},{}来自{}。".format(name_1, character_setting_total_dict_1["国籍"],
name_2, character_setting_total_dict_2["国籍"],
)
return 1 / 0
def main_single_character_prompt_func(name,
used_prompt_format_dict,
character_setting_rewrite_dict = {},
Text = "",
):
key = list(used_prompt_format_dict.keys())[0]
assert key in prompt_format_dict
if key == "续写下面的角色介绍,下面是角色介绍的开头。{}是{}。{}":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}": ["姓名", "Basic_Info"]
},
character_setting_rewrite_dict,
Text
)
elif key == "续写下面的角色故事,下面是角色故事的开头。{}是{}。{}":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "续写下面获得神之眼的过程,下面是开头。{}是{}。{}":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "{}给你写了一封信,信主题是{},信的内容是这样的。":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "{}在进行有关{}的聊天时会说什么?":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "{}在{}的时候会说什么?":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "{}在{}时会说什么?":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "关于{},{}会说什么?":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
elif key == "当你想要了解{}时":
task_prompt = single_character_prompt_func(
name,
used_prompt_format_dict,
character_setting_rewrite_dict,
Text
)
info_prompt = single_character_prompt_func(
name,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict,
Text
)
return task_prompt, info_prompt
def main_two_character_prompt_func(
name_1,
name_2,
used_prompt_format_dict,
character_setting_rewrite_dict_1 = {},
character_setting_rewrite_dict_2 = {},
):
task_prompt = two_character_prompt_func(
name_1,
name_2,
used_prompt_format_dict,
character_setting_rewrite_dict_1,
character_setting_rewrite_dict_2)
info_prompt_1 = single_character_prompt_func(
name_1,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict_1,
)
info_prompt_2 = single_character_prompt_func(
name_2,
{
"下面是{}的一些基本信息\n{}\n这些是一段角色介绍\n{}": ["姓名", "Basic_Info", "角色介绍"]
},
character_setting_rewrite_dict_2,
)
character_setting_total_dict_1 = get_character_setting_total_dict(name_1)
for k, v in character_setting_rewrite_dict_1.items():
if k in character_setting_total_dict_1:
character_setting_total_dict_1[k] = v
character_setting_total_dict_2 = get_character_setting_total_dict(name_2)
for k, v in character_setting_rewrite_dict_2.items():
if k in character_setting_total_dict_2:
character_setting_total_dict_2[k] = v
country_prompt = ""
same_country = character_setting_total_dict_1["国籍"] == character_setting_total_dict_2["国籍"]
if same_country:
country_prompt = single_character_prompt_func(
name_1,
{
"两人同属{}": ["国籍"]
},
character_setting_rewrite_dict_1,
)
else:
country_prompt = two_character_prompt_func(
name_1,
name_2,
{
"{}来自{},{}来自{}。": ["姓名", "国籍", "姓名", "国籍"]
},
character_setting_rewrite_dict_1,
character_setting_rewrite_dict_2,
)
info_prompt = "\n".join(
[info_prompt_1, info_prompt_2, country_prompt]
)
return task_prompt, info_prompt
def main_single_character_prompt_func_cls(
name,
task,
character_setting_rewrite_dict = {},
Text = "",
):
assert task in ["介绍", "故事", "信", "聊天", "时候", "关于", "了解"]
if task == "介绍":
return main_single_character_prompt_func(
name,
{
"续写下面的角色介绍,下面是角色介绍的开头。{}是{}。{}": ["姓名", "身份", "Text"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "故事":
return main_single_character_prompt_func(
name,
{
"续写下面的角色故事,下面是角色故事的开头。{}是{}。{}": ["姓名", "身份", "Text"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "神之眼":
return main_single_character_prompt_func(
name,
{
"续写下面获得神之眼的过程,下面是开头。{}是{}。{}": ["姓名", "身份", "Text"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "信":
return main_single_character_prompt_func(
name,
{
"{}给你写了一封信,信主题是{},信的内容是这样的。": ["姓名", "Text"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "聊天":
return main_single_character_prompt_func(
name,
{
"{}在进行有关{}的聊天时会说什么?": ["姓名", "Text"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "时候":
return main_single_character_prompt_func(
name,
{
"{}在{}的时候会说什么?": ["姓名", "Text"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "关于":
return main_single_character_prompt_func(
name,
{
"关于{},{}会说什么?": ["Text", "姓名"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
elif task == "了解":
return main_single_character_prompt_func(
name,
{
"当你想要了解{}时": ["姓名"],
},
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
return 1 / 0
def main_two_character_prompt_func_cls(
name_1,
name_2,
task,
character_setting_rewrite_dict_1 = {},
character_setting_rewrite_dict_2 = {},
):
assert task in ["会说什么", "哪些信息"]
if task == "会说什么":
return main_two_character_prompt_func(
name_1,
name_2,
{
"关于{},{}会说什么?": ["姓名", "姓名"],
},
character_setting_rewrite_dict_1,
character_setting_rewrite_dict_2
)
elif task == "哪些信息":
return main_two_character_prompt_func(
name_1,
name_2,
{
"从{}那里,可以获得哪些关于{}的信息?": ["姓名", "姓名"]
},
character_setting_rewrite_dict_1,
character_setting_rewrite_dict_2
)
return 1 / 0
character_setting_total_dist_dict = {
'姓名': "",
'性别': {'少女女性', '少年男性', '成年女性', '成年男性'},
'国籍': {'枫丹', '璃月', '稻妻', '至冬', '蒙德', '须弥'},
'身份': "",
'性格特征': "",
'角色介绍': "",
}
all_single_task = ["介绍", "故事", "信", "聊天", "时候", "关于", "了解"]
all_two_task = ["会说什么", "哪些信息"]
all_genders = ['少女女性', '少年男性', '成年女性', '成年男性']
all_countries = ['蒙德','璃月', '稻妻', '须弥','枫丹', '至冬']
def get_single_name(images, evt: gr.SelectData, repo_card_im_dict = character_img_dict):
img_selected = images[evt.index]
#print(img_selected)
im_data = img_selected["name"]
im = Image.open(im_data)
im_hash = imagehash.average_hash(
im, hash_size = 1024
)
min_diff = int(1e10)
min_repo_name = ""
for repo_name, repo_card_image in repo_card_im_dict.items():
repo_img = repo_card_image
repo_img_hash = imagehash.average_hash(
repo_img, hash_size = 1024
)
diff = im_hash - repo_img_hash
if diff < min_diff:
min_diff = diff
min_repo_name = repo_name
print(im_data ,min_repo_name, min_diff)
assert len(min_repo_name) > 0
single_name = min_repo_name
return single_name
#def change_single_name(single_name):
def change_single_name(images, evt: gr.SelectData,):
single_name = get_single_name(images, evt)
if hasattr(single_name, "value"):
single_name_ = single_name.value
else:
single_name_ = single_name
character_setting_total_dict = get_character_setting_total_dict(single_name)
character_setting_total_dict = dict(map(lambda t2: (t2[0] ,t2[1] if type(t2[1]) == type("") else ""),
character_setting_total_dict.items()))
return character_setting_total_dict["姓名"], \
gr.Dropdown.update(value = character_setting_total_dict["性别"], choices = all_genders), \
gr.Dropdown.update(value = character_setting_total_dict["国籍"], choices = all_countries), \
character_setting_total_dict["身份"], \
character_setting_total_dict["性格特征"], character_setting_total_dict["角色介绍"]
def get_single_prompt(
single_name, select_gender, select_country, single_identity, single_disposition,
select_task, Text, single_introduction
):
if hasattr(single_name, "value"):
single_name_ = single_name.value
else:
single_name_ = single_name
if hasattr(select_gender, "value"):
select_gender_ = select_gender.value
else:
select_gender_ = select_gender
if hasattr(select_country, "value"):
select_country_ = select_country.value
else:
select_country_ = select_country
if hasattr(single_identity, "value"):
single_identity_ = single_identity.value
else:
single_identity_ = single_identity
if hasattr(single_disposition, "value"):
single_disposition_ = single_disposition.value
else:
single_disposition_ = single_disposition
if hasattr(select_task, "value"):
select_task_ = select_task.value
else:
select_task_ = select_task
if hasattr(Text, "value"):
Text_ = Text.value
else:
Text_ = Text
if hasattr(single_introduction, "value"):
single_introduction_ = single_introduction.value
else:
single_introduction_ = single_introduction
character_setting_rewrite_dict = {
'姓名': single_name_,
'性别': select_gender_,
'国籍': select_country_,
'身份': single_identity_,
'性格特征': single_disposition_,
'角色介绍': single_introduction_,
}
a, b = main_single_character_prompt_func_cls(
single_name_,
select_task_,
character_setting_rewrite_dict = character_setting_rewrite_dict,
Text = Text,
)
#a = a.replace("?", "").replace("?", "")
a = a.replace("?", "?")
req = "\n".join([b, a])
req = process_info(req)
return req
#return "\n".join([b, a])
def get_two_prompt(
single_name_1, select_gender_1, select_country_1, single_identity_1, single_disposition_1,
single_introduction_1,
single_name_2, select_gender_2, select_country_2, single_identity_2, single_disposition_2,
single_introduction_2, two_task,
):
assert two_task in ["会说什么", "哪些信息"]
if hasattr(single_name_1, "value"):
single_name_1_ = single_name_1.value
else:
single_name_1_ = single_name_1
if hasattr(select_gender_1, "value"):
select_gender_1_ = select_gender_1.value
else:
select_gender_1_ = select_gender_1
if hasattr(select_country_1, "value"):
select_country_1_ = select_country_1.value
else:
select_country_1_ = select_country_1
if hasattr(single_identity_1, "value"):
single_identity_1_ = single_identity_1.value
else:
single_identity_1_ = single_identity_1
if hasattr(single_disposition_1, "value"):
single_disposition_1_ = single_disposition_1.value
else:
single_disposition_1_ = single_disposition_1
if hasattr(single_introduction_1, "value"):
single_introduction_1_ = single_introduction_1.value
else:
single_introduction_1_ = single_introduction_1
if hasattr(single_name_2, "value"):
single_name_2_ = single_name_2.value
else:
single_name_2_ = single_name_2
if hasattr(select_gender_2, "value"):
select_gender_2_ = select_gender_2.value
else:
select_gender_2_ = select_gender_2
if hasattr(select_country_2, "value"):
select_country_2_ = select_country_2.value
else:
select_country_2_ = select_country_2
if hasattr(single_identity_2, "value"):
single_identity_2_ = single_identity_2.value
else:
single_identity_2_ = single_identity_2
if hasattr(single_disposition_2, "value"):
single_disposition_2_ = single_disposition_2.value
else:
single_disposition_2_ = single_disposition_2
if hasattr(single_introduction_2, "value"):
single_introduction_2_ = single_introduction_2.value
else:
single_introduction_2_ = single_introduction_2
character_setting_rewrite_dict_1 = {
'姓名': single_name_1_,
'性别': select_gender_1_,
'国籍': select_country_1_,
'身份': single_identity_1_,
'性格特征': single_disposition_1_,
'角色介绍': single_introduction_1_,
}
character_setting_rewrite_dict_2 = {
'姓名': single_name_2_,
'性别': select_gender_2_,
'国籍': select_country_2_,
'身份': single_identity_2_,
'性格特征': single_disposition_2_,
'角色介绍': single_introduction_2_,
}
a, b = main_two_character_prompt_func_cls(
single_name_1_,
single_name_2_,
two_task,
character_setting_rewrite_dict_1 = character_setting_rewrite_dict_1,
character_setting_rewrite_dict_2 = character_setting_rewrite_dict_2,
)
#a = a.replace("?", "").replace("?", "")
a = a.replace("?", "?")
req = "\n".join([b, a])
req = process_info(req)
return req
#return "\n".join([b, a])
import chatglm_cpp
from pathlib import Path
import pandas as pd
import re
def retrieve_sent_split(sent,
stops_split_pattern = "|".join(map(lambda x: r"\{}".format(x),
",." + ",。" + ":" + "n"))
):
if not sent.strip():
return []
split_list = re.split(stops_split_pattern, sent)
split_list = list(filter(lambda x: x.strip() ,split_list))
return split_list
def stop_criteria(sent, min_sub_len = 4):
#### chunk rec stop
split_list = retrieve_sent_split(sent)
split_list = list(filter(lambda x: len(x) >= min_sub_len,split_list))
if split_list:
if pd.Series(split_list).value_counts().max() >= 2:
print("stop in : {}".format(sent))
return "stop"
#### row rec stop
if list(filter(lambda x: x ,map(lambda x: x.strip(),sent.split("\n")))) and pd.Series(list(filter(lambda x: x ,map(lambda x: x.strip(),sent.split("\n"))))).value_counts().max() >= 2:
return "stop"
return "continue"
#model_file_path = "genshin_impact_character_glm6b_base_ggml/chatglm3-base-inst-7500-sm-ggml.bin"
model_file_path = "genshin_impact_character_glm6b_base_ggml/chatglm3-base-inst-6500-sm-ggml.bin"
print("load {}".format(model_file_path))
chatglm_llm = chatglm_cpp.Pipeline(Path(model_file_path))
def repeat_cmp_process(x, ratio_threshold = 0.3):
l = x.split("\n")
l = list(filter(lambda y: y.strip(), l))
req = []
for ele in l:
one_ele = repeat_to_one(ele)
if ele.strip() and (len(one_ele) / len(ele)) <= ratio_threshold:
req.append(one_ele)
else:
req.append(ele)
return "\n".join(req)
def text_process_before_yield(x, add_repeat_process = True):
import re
x = x.strip()
if len(x.split("\n")) <= 1:
#return repeat_to_one_fb(x)
if add_repeat_process:
return repeat_cmp_process(x)
return x
zh_list = re.findall(u"[\u4e00-\u9fa5]+" ,x)
if zh_list:
last_zh = zh_list[-1]
l = list(map(lambda y: y.strip() ,x.split("\n")))
l_rev = l[::-1]
l_rev_collect = []
find_it = False
for ele in l_rev:
if not ele.endswith(last_zh):
find_it = True
else:
pass
if find_it:
l_rev_collect.append(ele)
l_collect = l_rev_collect[::-1]
#print(l_collect)
req = "\n".join(l_collect)
'''
zh_list = re.findall(u"[\u4e00-\u9fa5]+" ,x)
if zh_list:
req = req[req.find(zh_list[0]):]
'''
#return repeat_to_one_fb(req)
if add_repeat_process:
return repeat_cmp_process(req)
return req
return ""
def chat_messages(message, history = [], chatglm_llm = chatglm_llm,
max_length = 128, show_process = True,
temperature = 0.5, top_p = 0.95, top_k = 40, do_sample = True,
):
#print("message :")
#print(message)
flatten_history = []
for a, b in history:
flatten_history.append(
chatglm_cpp.ChatMessage(role="user", content=a)
)
flatten_history.append(
chatglm_cpp.ChatMessage(role="assistant", content=b)
)