QiyuanChen commited on
Commit
c62bbf1
·
1 Parent(s): 4c4ef62

Initial Commit

Browse files
ChatHaruhi/BaiChuan2GPT.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .BaseLLM import BaseLLM
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ from transformers.generation.utils import GenerationConfig
5
+ from peft import PeftModel
6
+
7
+ tokenizer_BaiChuan = None
8
+ model_BaiChuan = None
9
+
10
+ def initialize_BaiChuan2LORA():
11
+ global model_BaiChuan, tokenizer_BaiChuan
12
+
13
+ if model_BaiChuan is None:
14
+ model_BaiChuan = AutoModelForCausalLM.from_pretrained(
15
+ "baichuan-inc/Baichuan2-13B-Chat",
16
+ device_map="auto",
17
+ torch_dtype=torch.bfloat16,
18
+ trust_remote_code=True,
19
+ )
20
+ model_BaiChuan = PeftModel.from_pretrained(
21
+ model_BaiChuan,
22
+ "silk-road/Chat-Haruhi-Fusion_Baichuan2_13B"
23
+ )
24
+ model_BaiChuan.generation_config = GenerationConfig.from_pretrained(
25
+ "baichuan-inc/Baichuan2-13B-Chat"
26
+ )
27
+
28
+ if tokenizer_BaiChuan is None:
29
+ tokenizer_BaiChuan = AutoTokenizer.from_pretrained(
30
+ "baichuan-inc/Baichuan2-13B-Chat",
31
+ use_fast=True,
32
+ trust_remote_code=True
33
+ )
34
+
35
+ return model_BaiChuan, tokenizer_BaiChuan
36
+
37
+ def BaiChuan_tokenizer(text):
38
+ return len(tokenizer_BaiChuan.encode(text))
39
+
40
+ class BaiChuan2GPT(BaseLLM):
41
+ def __init__(self, model = "haruhi-fusion-baichuan"):
42
+ super(BaiChuan2GPT, self).__init__()
43
+ if model == "baichuan2-13b":
44
+ self.tokenizer = AutoTokenizer.from_pretrained(
45
+ "baichuan-inc/Baichuan2-13B-Chat",
46
+ use_fast=True,
47
+ trust_remote_code=True
48
+ ),
49
+ self.model = AutoModelForCausalLM.from_pretrained(
50
+ "baichuan-inc/Baichuan2-13B-Chat",
51
+ device_map="auto",
52
+ torch_dtype=torch.bfloat16,
53
+ trust_remote_code=True,
54
+ )
55
+ self.model.generation_config = GenerationConfig.from_pretrained(
56
+ "baichuan-inc/Baichuan2-13B-Chat"
57
+ )
58
+ elif model == "haruhi-fusion-baichuan":
59
+ self.model, self.tokenizer = initialize_BaiChuan2LORA()
60
+ else:
61
+ raise Exception("Unknown BaiChuan Model! Currently supported: [BaiChuan2-13B, haruhi-fusion-baichuan]")
62
+ self.messages = []
63
+
64
+ def initialize_message(self):
65
+ self.messages = []
66
+
67
+ def ai_message(self, payload):
68
+ self.messages.append({"role": "assistant", "content": payload})
69
+
70
+ def system_message(self, payload):
71
+ self.messages.append({"role": "system", "content": payload})
72
+
73
+ def user_message(self, payload):
74
+ self.messages.append({"role": "user", "content": payload})
75
+
76
+ def get_response(self):
77
+ with torch.no_grad():
78
+ response = self.model.chat(self.tokenizer, self.messages)
79
+ return response
80
+
81
+ def print_prompt(self):
82
+ print(type(self.messages))
83
+ print(self.messages)
ChatHaruhi/BaseDB.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BaseDB.py
2
+
3
+ from abc import ABC, abstractmethod
4
+
5
+ class BaseDB(ABC):
6
+
7
+ @abstractmethod
8
+ def init_db(self):
9
+ pass
10
+
11
+ @abstractmethod
12
+ def save(self, file_path):
13
+ pass
14
+
15
+ @abstractmethod
16
+ def load(self, file_path):
17
+ pass
18
+
19
+ @abstractmethod
20
+ def search(self, vector, n_results):
21
+ pass
22
+
23
+ @abstractmethod
24
+ def init_from_docs(self, vectors, documents):
25
+ pass
26
+
27
+
ChatHaruhi/BaseLLM.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatHaruhi: Reviving Anime Character in Reality via Large Language Model
2
+ #
3
+ # ChatHaruhi 2.0, built by Cheng Li and Weishi Mi
4
+ #
5
+ # chengli.thu@gmail.com, mws22@mails.tsinghua.edu.cn
6
+ #
7
+ # Weishi Mi is a second-year graduate student at Tsinghua University, majoring in computer science.
8
+ # Weishi Mi is pursuing a job or a PhD position, which who will be available next year
9
+ #
10
+ # homepage https://github.com/LC1332/Chat-Haruhi-Suzumiya
11
+ #
12
+ # ChatHaruhi is a chatbot that can revive anime characters in reality.
13
+ # the 2.0 version was built by Cheng Li and Weishi Mi.
14
+ #
15
+ # Please cite our paper if you use this code for research:
16
+ #
17
+ # @misc{li2023chatharuhi,
18
+ # title={ChatHaruhi: Reviving Anime Character in Reality via Large Language Model},
19
+ # author={Cheng Li and Ziang Leng and Chenxi Yan and Junyi Shen and Hao Wang and Weishi MI and Yaying Fei and Xiaoyang Feng and Song Yan and HaoSheng Wang and Linkang Zhan and Yaokai Jia and Pingyu Wu and Haozhen Sun},
20
+ # year={2023},
21
+ # eprint={2308.09597},
22
+ # archivePrefix={arXiv},
23
+ # primaryClass={cs.CL}
24
+ # }
25
+ from abc import ABC, abstractmethod
26
+
27
+ class BaseLLM(ABC):
28
+
29
+ def __init__(self):
30
+ pass
31
+
32
+ @abstractmethod
33
+ def initialize_message(self):
34
+ pass
35
+
36
+ @abstractmethod
37
+ def ai_message(self, payload):
38
+ pass
39
+
40
+ @abstractmethod
41
+ def system_message(self, payload):
42
+ pass
43
+
44
+ @abstractmethod
45
+ def user_message(self, payload):
46
+ pass
47
+
48
+ @abstractmethod
49
+ def get_response(self):
50
+ pass
51
+
52
+ @abstractmethod
53
+ def print_prompt(self):
54
+ pass
55
+
56
+
ChatHaruhi/ChatGLM2GPT.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .BaseLLM import BaseLLM
3
+ from transformers import AutoTokenizer, AutoModel
4
+ from peft import PeftModel
5
+
6
+ tokenizer_GLM = None
7
+ model_GLM = None
8
+
9
+ def initialize_GLM2LORA():
10
+ global model_GLM, tokenizer_GLM
11
+
12
+ if model_GLM is None:
13
+ model_GLM = AutoModel.from_pretrained(
14
+ "THUDM/chatglm2-6b",
15
+ torch_dtype=torch.float16,
16
+ device_map="auto",
17
+ trust_remote_code=True
18
+ )
19
+ model_GLM = PeftModel.from_pretrained(
20
+ model_GLM,
21
+ "silk-road/Chat-Haruhi-Fusion_B"
22
+ )
23
+
24
+ if tokenizer_GLM is None:
25
+ tokenizer_GLM = AutoTokenizer.from_pretrained(
26
+ "THUDM/chatglm2-6b",
27
+ use_fast=True,
28
+ trust_remote_code=True
29
+ )
30
+
31
+ return model_GLM, tokenizer_GLM
32
+
33
+ def GLM_tokenizer(text):
34
+ return len(tokenizer_GLM.encode(text))
35
+
36
+ class ChatGLM2GPT(BaseLLM):
37
+ def __init__(self, model = "haruhi-fusion"):
38
+ super(ChatGLM2GPT, self).__init__()
39
+ if model == "glm2-6b":
40
+ self.tokenizer = AutoTokenizer.from_pretrained(
41
+ "THUDM/chatglm2-6b",
42
+ use_fast=True,
43
+ trust_remote_code=True
44
+ )
45
+ self.model = AutoModel.from_pretrained(
46
+ "THUDM/chatglm2-6b",
47
+ torch_dtype=torch.float16,
48
+ device_map="auto",
49
+ trust_remote_code=True
50
+ )
51
+ if model == "haruhi-fusion":
52
+ self.model, self.tokenizer = initialize_GLM2LORA()
53
+ else:
54
+ raise Exception("Unknown GLM model")
55
+ self.messages = ""
56
+
57
+ def initialize_message(self):
58
+ self.message = ""
59
+
60
+ def ai_message(self, payload):
61
+ self.messages = self.messages + "\n " + payload
62
+
63
+ def system_message(self, payload):
64
+ self.messages = self.messages + "\n " + payload
65
+
66
+ def user_message(self, payload):
67
+ self.messages = self.messages + "\n " + payload
68
+
69
+ def get_response(self):
70
+ with torch.no_grad():
71
+ response, history = self.model.chat(self.tokenizer, self.messages, history=[])
72
+ # print(response)
73
+ return response
74
+
75
+ def print_prompt(self):
76
+ print(type(self.messages))
77
+ print(self.messages)
78
+
79
+
ChatHaruhi/ChatHaruhi.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .ChromaDB import ChromaDB
2
+ import os
3
+
4
+ from .utils import luotuo_openai_embedding, tiktokenizer
5
+
6
+ from .utils import response_postprocess
7
+
8
+ class ChatHaruhi:
9
+
10
+ def __init__(self, system_prompt = None, \
11
+ role_name = None, role_from_hf = None, \
12
+ story_db=None, story_text_folder = None, \
13
+ llm = 'openai', \
14
+ embedding = 'luotuo_openai', \
15
+ max_len_story = None, max_len_history = None,
16
+ verbose = False):
17
+ super(ChatHaruhi, self).__init__()
18
+ self.verbose = verbose
19
+
20
+ # constants
21
+ self.story_prefix_prompt = "Classic scenes for the role are as follows:\n"
22
+ self.k_search = 19
23
+ self.narrator = ['旁白', '', 'scene','Scene','narrator' , 'Narrator']
24
+ self.dialogue_divide_token = '\n###\n'
25
+ self.dialogue_bra_token = '「'
26
+ self.dialogue_ket_token = '」'
27
+
28
+ if system_prompt:
29
+ self.system_prompt = self.check_system_prompt( system_prompt )
30
+
31
+ # TODO: embedding should be the seperately defined, so refactor this part later
32
+ if llm == 'openai':
33
+ # self.llm = LangChainGPT()
34
+ self.llm, self.tokenizer = self.get_models('openai')
35
+ elif llm == 'debug':
36
+ self.llm, self.tokenizer = self.get_models('debug')
37
+ elif llm == 'spark':
38
+ self.llm, self.tokenizer = self.get_models('spark')
39
+ elif llm == 'GLMPro':
40
+ self.llm, self.tokenizer = self.get_models('GLMPro')
41
+ elif llm == 'ChatGLM2GPT':
42
+ self.llm, self.tokenizer = self.get_models('ChatGLM2GPT')
43
+ self.story_prefix_prompt = '\n'
44
+ elif llm == "BaiChuan2GPT":
45
+ self.llm, self.tokenizer = self.get_models('BaiChuan2GPT')
46
+ else:
47
+ print(f'warning! undefined llm {llm}, use openai instead.')
48
+ self.llm, self.tokenizer = self.get_models('openai')
49
+
50
+ if embedding == 'luotuo_openai':
51
+ self.embedding = luotuo_openai_embedding
52
+ else:
53
+ print(f'warning! undefined embedding {embedding}, use luotuo_openai instead.')
54
+ self.embedding = luotuo_openai_embedding
55
+
56
+ if role_name:
57
+ # TODO move into a function
58
+ from .role_name_to_file import get_folder_role_name
59
+ # correct role_name to folder_role_name
60
+ role_name, url = get_folder_role_name(role_name)
61
+
62
+ unzip_folder = f'./temp_character_folder/temp_{role_name}'
63
+ db_folder = os.path.join(unzip_folder, f'content/{role_name}')
64
+ system_prompt = os.path.join(unzip_folder, f'content/system_prompt.txt')
65
+
66
+ if not os.path.exists(unzip_folder):
67
+ # not yet downloaded
68
+ # url = f'https://github.com/LC1332/Haruhi-2-Dev/raw/main/data/character_in_zip/{role_name}.zip'
69
+ import requests, zipfile, io
70
+ r = requests.get(url)
71
+ z = zipfile.ZipFile(io.BytesIO(r.content))
72
+ z.extractall(unzip_folder)
73
+
74
+ if self.verbose:
75
+ print(f'loading pre-defined character {role_name}...')
76
+
77
+ self.db = ChromaDB()
78
+ self.db.load(db_folder)
79
+ self.system_prompt = self.check_system_prompt(system_prompt)
80
+ elif role_from_hf:
81
+ # TODO move into a function
82
+ from datasets import load_dataset
83
+ dataset = load_dataset(role_from_hf)
84
+ datas = dataset["train"]
85
+ from .utils import base64_to_float_array
86
+ # 暂时只有一种embedding 'luotuo_openai'
87
+ embed_name = 'luotuo_openai'
88
+ texts = []
89
+ vecs = []
90
+ for data in datas:
91
+ if data[embed_name] == 'system_prompt':
92
+ self.system_prompt = data['text']
93
+ elif data[embed_name] == 'config':
94
+ pass
95
+ else:
96
+ vec = base64_to_float_array( data[embed_name] )
97
+ text = data['text']
98
+ vecs.append( vec )
99
+ texts.append( text )
100
+
101
+ self.build_story_db_from_vec( texts, vecs )
102
+
103
+ elif story_db:
104
+ self.db = ChromaDB()
105
+ self.db.load(story_db)
106
+ elif story_text_folder:
107
+ # print("Building story database from texts...")
108
+ self.db = self.build_story_db(story_text_folder)
109
+ else:
110
+ self.db = None
111
+ print('warning! database not yet figured out, both story_db and story_text_folder are not inputted.')
112
+ # raise ValueError("Either story_db or story_text_folder must be provided")
113
+
114
+
115
+ self.max_len_story, self.max_len_history = self.get_tokenlen_setting('openai')
116
+
117
+ if max_len_history is not None:
118
+ self.max_len_history = max_len_history
119
+ # user setting will override default setting
120
+
121
+ if max_len_story is not None:
122
+ self.max_len_story = max_len_story
123
+ # user setting will override default setting
124
+
125
+ self.dialogue_history = []
126
+
127
+
128
+
129
+ def check_system_prompt(self, system_prompt):
130
+ # if system_prompt end with .txt, read the file with utf-8
131
+ # else, return the string directly
132
+ if system_prompt.endswith('.txt'):
133
+ with open(system_prompt, 'r', encoding='utf-8') as f:
134
+ return f.read()
135
+ else:
136
+ return system_prompt
137
+
138
+
139
+ def get_models(self, model_name):
140
+
141
+ # TODO: if output only require tokenizer model, no need to initialize llm
142
+
143
+ # return the combination of llm, embedding and tokenizer
144
+ if model_name == 'openai':
145
+ from .LangChainGPT import LangChainGPT
146
+ return (LangChainGPT(), tiktokenizer)
147
+ elif model_name == 'debug':
148
+ from .PrintLLM import PrintLLM
149
+ return (PrintLLM(), tiktokenizer)
150
+ elif model_name == 'spark':
151
+ from .SparkGPT import SparkGPT
152
+ return (SparkGPT(), tiktokenizer)
153
+ elif model_name == 'GLMPro':
154
+ from .GLMPro import GLMPro
155
+ return (GLMPro(), tiktokenizer)
156
+ elif model_name == "ChatGLM2GPT":
157
+ from .ChatGLM2GPT import ChatGLM2GPT, GLM_tokenizer
158
+ return (ChatGLM2GPT(), GLM_tokenizer)
159
+ elif model_name == "BaiChuan2GPT":
160
+ from .BaiChuan2GPT import BaiChuan2GPT, BaiChuan_tokenizer
161
+ return (BaiChuan2GPT(), BaiChuan_tokenizer)
162
+ else:
163
+ print(f'warning! undefined model {model_name}, use openai instead.')
164
+ from .LangChainGPT import LangChainGPT
165
+ return (LangChainGPT(), tiktokenizer)
166
+
167
+ def get_tokenlen_setting( self, model_name ):
168
+ # return the setting of story and history token length
169
+ if model_name == 'openai':
170
+ return (1500, 1200)
171
+ else:
172
+ print(f'warning! undefined model {model_name}, use openai instead.')
173
+ return (1500, 1200)
174
+
175
+ def build_story_db_from_vec( self, texts, vecs ):
176
+ self.db = ChromaDB()
177
+
178
+ self.db.init_from_docs( vecs, texts)
179
+
180
+ def build_story_db(self, text_folder):
181
+ # 实现读取文本文件夹,抽取向量的逻辑
182
+ db = ChromaDB()
183
+
184
+ strs = []
185
+
186
+ # scan all txt file from text_folder
187
+ for file in os.listdir(text_folder):
188
+ # if file name end with txt
189
+ if file.endswith(".txt"):
190
+ file_path = os.path.join(text_folder, file)
191
+ with open(file_path, 'r', encoding='utf-8') as f:
192
+ strs.append(f.read())
193
+
194
+ if self.verbose:
195
+ print(f'starting extract embedding... for { len(strs) } files')
196
+
197
+ vecs = []
198
+
199
+ ## TODO: 建立一个新的embedding batch test的单元测试
200
+ ## 新的支持list batch test的embedding代码
201
+ ## 用新的代码替换下面的for循环
202
+ ## Luotuo-bert-en也发布了,所以可以避开使用openai
203
+
204
+ for mystr in strs:
205
+ vecs.append(self.embedding(mystr))
206
+
207
+ db.init_from_docs(vecs, strs)
208
+
209
+ return db
210
+
211
+ def save_story_db(self, db_path):
212
+ self.db.save(db_path)
213
+
214
+ def chat(self, text, role):
215
+ # add system prompt
216
+ self.llm.initialize_message()
217
+ self.llm.system_message(self.system_prompt)
218
+
219
+
220
+ # add story
221
+ query = self.get_query_string(text, role)
222
+ self.add_story( query )
223
+
224
+ # add history
225
+ self.add_history()
226
+
227
+ # add query
228
+ self.llm.user_message(query)
229
+
230
+ # get response
231
+ response_raw = self.llm.get_response()
232
+
233
+ response = response_postprocess(response_raw, self.dialogue_bra_token, self.dialogue_ket_token)
234
+
235
+ # record dialogue history
236
+ self.dialogue_history.append((query, response))
237
+
238
+
239
+
240
+ return response
241
+
242
+ def get_query_string(self, text, role):
243
+ if role in self.narrator:
244
+ return role + ":" + text
245
+ else:
246
+ return f"{role}:{self.dialogue_bra_token}{text}{self.dialogue_ket_token}"
247
+
248
+ def add_story(self, query):
249
+
250
+ if self.db is None:
251
+ return
252
+
253
+ query_vec = self.embedding(query)
254
+
255
+ stories = self.db.search(query_vec, self.k_search)
256
+
257
+ story_string = self.story_prefix_prompt
258
+ sum_story_token = self.tokenizer(story_string)
259
+
260
+ for story in stories:
261
+ story_token = self.tokenizer(story) + self.tokenizer(self.dialogue_divide_token)
262
+ if sum_story_token + story_token > self.max_len_story:
263
+ break
264
+ else:
265
+ sum_story_token += story_token
266
+ story_string += story + self.dialogue_divide_token
267
+
268
+ self.llm.user_message(story_string)
269
+
270
+ def add_history(self):
271
+
272
+ if len(self.dialogue_history) == 0:
273
+ return
274
+
275
+ sum_history_token = 0
276
+ flag = 0
277
+ for query, response in reversed(self.dialogue_history):
278
+ current_count = 0
279
+ if query is not None:
280
+ current_count += self.tokenizer(query)
281
+ if response is not None:
282
+ current_count += self.tokenizer(response)
283
+ sum_history_token += current_count
284
+ if sum_history_token > self.max_len_history:
285
+ break
286
+ else:
287
+ flag += 1
288
+
289
+ if flag == 0:
290
+ print('warning! no history added. the last dialogue is too long.')
291
+
292
+ for (query, response) in self.dialogue_history[-flag:]:
293
+ if query is not None:
294
+ self.llm.user_message(query)
295
+ if response is not None:
296
+ self.llm.ai_message(response)
ChatHaruhi/ChromaDB.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import chromadb
2
+ from .BaseDB import BaseDB
3
+ import random
4
+ import string
5
+ import os
6
+
7
+ class ChromaDB(BaseDB):
8
+
9
+ def __init__(self):
10
+ self.client = None
11
+ self.collection = None
12
+ self.path = None
13
+
14
+ def init_db(self):
15
+
16
+ if self.client is not None:
17
+ print('ChromaDB has already been initialized')
18
+ return
19
+
20
+ folder_name = ''
21
+
22
+ while os.path.exists(folder_name) or folder_name == '':
23
+ # try to create a folder named temp_<random string> which is not yet existed
24
+ folder_name = "tempdb_" + ''.join(random.sample(string.ascii_letters + string.digits, 8))
25
+
26
+ self.path = folder_name
27
+ self.client = chromadb.PersistentClient(path = folder_name)
28
+
29
+ self.collection = self.client.get_or_create_collection("search")
30
+
31
+ def save(self, file_path):
32
+ if file_path != self.path:
33
+ # copy all files in self.path to file_path, with overwrite
34
+ os.system("cp -r " + self.path + " " + file_path)
35
+ previous_path = self.path
36
+ self.path = file_path
37
+ self.client = chromadb.PersistentClient(path = file_path)
38
+ # remove previous path if it start with tempdb
39
+ if previous_path.startswith("tempdb"):
40
+ os.system("rm -rf " + previous_path)
41
+
42
+
43
+ def load(self, file_path):
44
+ self.path = file_path
45
+ self.client = chromadb.PersistentClient(path = file_path)
46
+ self.collection = self.client.get_collection("search")
47
+
48
+ def search(self, vector, n_results):
49
+ results = self.collection.query(query_embeddings=[vector], n_results=n_results)
50
+ return results['documents'][0]
51
+
52
+ def init_from_docs(self, vectors, documents):
53
+ if self.client is None:
54
+ self.init_db()
55
+
56
+ ids = []
57
+ for i, doc in enumerate(documents):
58
+ first_four_chat = doc[:min(4, len(doc))]
59
+ ids.append( str(i) + "_" + doc)
60
+ self.collection.add(embeddings=vectors, documents=documents, ids = ids)
61
+
ChatHaruhi/GLMPro.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .BaseLLM import BaseLLM
2
+ import os
3
+
4
+ zhipu_api = os.environ['ZHIPU_API']
5
+
6
+ import zhipuai
7
+ import time
8
+
9
+ class GLMPro( BaseLLM ):
10
+ def __init__(self, model="chatglm_pro", verbose = False ):
11
+ super(GLMPro,self).__init__()
12
+
13
+ zhipuai.api_key = zhipu_api
14
+
15
+ self.verbose = verbose
16
+
17
+ self.model_name = model
18
+
19
+ self.prompts = []
20
+
21
+ if self.verbose == True:
22
+ print('model name, ', self.model_name )
23
+ if len( zhipu_api ) > 8:
24
+ print( 'found apikey ', zhipu_api[:4], '****', zhipu_api[-4:] )
25
+ else:
26
+ print( 'found apikey but too short, ' )
27
+
28
+
29
+ def initialize_message(self):
30
+ self.prompts = []
31
+
32
+ def ai_message(self, payload):
33
+ self.prompts.append({"role":"assistant","content":payload})
34
+
35
+ def system_message(self, payload):
36
+ self.prompts.append({"role":"user","content":payload})
37
+
38
+ def user_message(self, payload):
39
+ self.prompts.append({"role":"user","content":payload})
40
+
41
+ def get_response(self):
42
+ zhipuai.api_key = zhipu_api
43
+ max_test_name = 5
44
+ sleep_interval = 3
45
+
46
+ request_id = None
47
+
48
+
49
+
50
+ # try submit asychonize request until success
51
+ for test_time in range( max_test_name ):
52
+ response = zhipuai.model_api.async_invoke(
53
+ model = self.model_name,
54
+ prompt = self.prompts,
55
+ temperature = 0)
56
+ if response['success'] == True:
57
+ request_id = response['data']['task_id']
58
+
59
+ if self.verbose == True:
60
+ print('submit request, id = ', request_id )
61
+ break
62
+ else:
63
+ print('submit GLM request failed, retrying...')
64
+ time.sleep( sleep_interval )
65
+
66
+ if request_id:
67
+ # try get response until success
68
+ for test_time in range( 2 * max_test_name ):
69
+ result = zhipuai.model_api.query_async_invoke_result( request_id )
70
+ if result['code'] == 200 and result['data']['task_status'] == 'SUCCESS':
71
+
72
+ if self.verbose == True:
73
+ print('get GLM response success' )
74
+
75
+ choices = result['data']['choices']
76
+ if len( choices ) > 0:
77
+ return choices[-1]['content'].strip("\"'")
78
+
79
+ # other wise means failed
80
+ if self.verbose == True:
81
+ print('get GLM response failed, retrying...')
82
+ # sleep for 1 second
83
+ time.sleep( sleep_interval )
84
+ else:
85
+ print('submit GLM request failed, please check your api key and model name')
86
+ return ''
87
+
88
+ def print_prompt(self):
89
+ for message in self.prompts:
90
+ print(f"{message['role']}: {message['content']}")
ChatHaruhi/LangChainGPT.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatHaruhi: Reviving Anime Character in Reality via Large Language Model
2
+ #
3
+ # ChatHaruhi 2.0, built by Cheng Li and Weishi Mi
4
+ #
5
+ # chengli.thu@gmail.com, mws22@mails.tsinghua.edu.cn
6
+ #
7
+ # Weishi Mi is a second-year graduate student at Tsinghua University, majoring in computer science.
8
+ # Weishi Mi is pursuing a job or a PhD position, which who will be available next year
9
+ #
10
+ # homepage https://github.com/LC1332/Chat-Haruhi-Suzumiya
11
+ #
12
+ # ChatHaruhi is a chatbot that can revive anime characters in reality.
13
+ # the 2.0 version was built by Cheng Li and Weishi Mi.
14
+ #
15
+ # Please cite our paper if you use this code for research:
16
+ #
17
+ # @misc{li2023chatharuhi,
18
+ # title={ChatHaruhi: Reviving Anime Character in Reality via Large Language Model},
19
+ # author={Cheng Li and Ziang Leng and Chenxi Yan and Junyi Shen and Hao Wang and Weishi MI and Yaying Fei and Xiaoyang Feng and Song Yan and HaoSheng Wang and Linkang Zhan and Yaokai Jia and Pingyu Wu and Haozhen Sun},
20
+ # year={2023},
21
+ # eprint={2308.09597},
22
+ # archivePrefix={arXiv},
23
+ # primaryClass={cs.CL}
24
+ # }
25
+
26
+
27
+ from langchain.chat_models import ChatOpenAI
28
+ from langchain.prompts.chat import (
29
+ ChatPromptTemplate,
30
+ SystemMessagePromptTemplate,
31
+ AIMessagePromptTemplate,
32
+ HumanMessagePromptTemplate,
33
+ )
34
+ from langchain.schema import (
35
+ AIMessage,
36
+ HumanMessage,
37
+ SystemMessage
38
+ )
39
+ from .BaseLLM import BaseLLM
40
+
41
+ class LangChainGPT(BaseLLM):
42
+
43
+ def __init__(self, model="gpt-3.5-turbo"):
44
+ super(LangChainGPT,self).__init__()
45
+ self.chat = ChatOpenAI(model=model)
46
+ self.messages = []
47
+
48
+ def initialize_message(self):
49
+ self.messages = []
50
+
51
+ def ai_message(self, payload):
52
+ self.messages.append(AIMessage(content = payload))
53
+
54
+ def system_message(self, payload):
55
+ self.messages.append(SystemMessage(content = payload))
56
+
57
+ def user_message(self, payload):
58
+ self.messages.append(HumanMessage(content = payload))
59
+
60
+ def get_response(self):
61
+ response = self.chat(self.messages)
62
+ return response.content
63
+
64
+ def print_prompt(self):
65
+ for message in self.messages:
66
+ print(message)
ChatHaruhi/PrintLLM.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatHaruhi: Reviving Anime Character in Reality via Large Language Model
2
+ #
3
+ # ChatHaruhi 2.0, built by Cheng Li and Weishi Mi
4
+ #
5
+ # chengli.thu@gmail.com, mws22@mails.tsinghua.edu.cn
6
+ #
7
+ # Weishi Mi is a second-year graduate student at Tsinghua University, majoring in computer science.
8
+ # Weishi Mi is pursuing a job or a PhD position, which who will be available next year
9
+ #
10
+ # homepage https://github.com/LC1332/Chat-Haruhi-Suzumiya
11
+ #
12
+ # ChatHaruhi is a chatbot that can revive anime characters in reality.
13
+ # the 2.0 version was built by Cheng Li and Weishi Mi.
14
+ #
15
+ # Please cite our paper if you use this code for research:
16
+ #
17
+ # @misc{li2023chatharuhi,
18
+ # title={ChatHaruhi: Reviving Anime Character in Reality via Large Language Model},
19
+ # author={Cheng Li and Ziang Leng and Chenxi Yan and Junyi Shen and Hao Wang and Weishi MI and Yaying Fei and Xiaoyang Feng and Song Yan and HaoSheng Wang and Linkang Zhan and Yaokai Jia and Pingyu Wu and Haozhen Sun},
20
+ # year={2023},
21
+ # eprint={2308.09597},
22
+ # archivePrefix={arXiv},
23
+ # primaryClass={cs.CL}
24
+ # }
25
+ #
26
+ # This PrintLLM.py is for debuging with any real-runing LLM
27
+ # so you can see full prompt and copy it into GPT or Claude to debug
28
+ #
29
+
30
+ from .BaseLLM import BaseLLM
31
+
32
+ class PrintLLM(BaseLLM):
33
+
34
+ def __init__(self ):
35
+ self.messages = []
36
+ self.messages.append("Noticing: This is a print LLM for debug.")
37
+ self.messages.append("But you can also copy the prompt into GPT or Claude to debugging")
38
+
39
+ def initialize_message(self):
40
+ self.messages = []
41
+ self.messages.append("Noticing: This is a print LLM for debug.")
42
+ self.messages.append("But you can also copy the prompt into GPT or Claude to debugging")
43
+
44
+ def ai_message(self, payload):
45
+ self.messages.append("AI: \n" + payload)
46
+
47
+ def system_message(self, payload):
48
+ self.messages.append("System: \n" + payload)
49
+
50
+ def user_message(self, payload):
51
+ self.messages.append("User: \n" + payload)
52
+
53
+ def get_response(self):
54
+ for message in self.messages:
55
+ print(message)
56
+ response = input("Please input your response: ")
57
+ return response
58
+
59
+ def print_prompt(self):
60
+ for message in self.messages:
61
+ print(message)
ChatHaruhi/SparkApi.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 由讯飞提供的websocket接口,用于与星火机器人进行交互
2
+
3
+ import _thread as thread
4
+ import base64
5
+ import datetime
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ from urllib.parse import urlparse
10
+ import ssl
11
+ from datetime import datetime
12
+ from time import mktime
13
+ from urllib.parse import urlencode
14
+ from wsgiref.handlers import format_date_time
15
+
16
+ import websocket # 使用websocket_client
17
+ answer = ""
18
+
19
+ class Ws_Param(object):
20
+ # 初始化
21
+ def __init__(self, APPID, APIKey, APISecret, Spark_url):
22
+ self.APPID = APPID
23
+ self.APIKey = APIKey
24
+ self.APISecret = APISecret
25
+ self.host = urlparse(Spark_url).netloc
26
+ self.path = urlparse(Spark_url).path
27
+ self.Spark_url = Spark_url
28
+
29
+ # 生成url
30
+ def create_url(self):
31
+ # 生成RFC1123格式的时间戳
32
+ now = datetime.now()
33
+ date = format_date_time(mktime(now.timetuple()))
34
+
35
+ # 拼接字符串
36
+ signature_origin = "host: " + self.host + "\n"
37
+ signature_origin += "date: " + date + "\n"
38
+ signature_origin += "GET " + self.path + " HTTP/1.1"
39
+
40
+ # 进行hmac-sha256进行加密
41
+ signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
42
+ digestmod=hashlib.sha256).digest()
43
+
44
+ signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
45
+
46
+ authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
47
+
48
+ authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
49
+
50
+ # 将请求的鉴权参数组合为字典
51
+ v = {
52
+ "authorization": authorization,
53
+ "date": date,
54
+ "host": self.host
55
+ }
56
+ # 拼接鉴权参数,生成url
57
+ url = self.Spark_url + '?' + urlencode(v)
58
+ # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
59
+ return url
60
+
61
+
62
+ # 收到websocket错误的处理
63
+ def on_error(ws, error):
64
+ print("### error:", error)
65
+
66
+
67
+ # 收到websocket关闭的处理
68
+ def on_close(ws,one,two):
69
+ print(" ")
70
+
71
+
72
+ # 收到websocket连接建立的处理
73
+ def on_open(ws):
74
+ thread.start_new_thread(run, (ws,))
75
+
76
+
77
+ def run(ws, *args):
78
+ data = json.dumps(gen_params(appid=ws.appid, domain= ws.domain,question=ws.question))
79
+ ws.send(data)
80
+
81
+
82
+ # 收到websocket消息的处理
83
+ def on_message(ws, message):
84
+ # print(message)
85
+ data = json.loads(message)
86
+ code = data['header']['code']
87
+ if code != 0:
88
+ print(f'请求错误: {code}, {data}')
89
+ ws.close()
90
+ else:
91
+ choices = data["payload"]["choices"]
92
+ status = choices["status"]
93
+ content = choices["text"][0]["content"]
94
+ # print(content,end ="")
95
+ global answer
96
+ answer += content
97
+ # print(1)
98
+ if status == 2:
99
+ ws.close()
100
+
101
+
102
+ def gen_params(appid, domain,question):
103
+ """
104
+ 通过appid和用户的提问来生成请参数
105
+ """
106
+ data = {
107
+ "header": {
108
+ "app_id": appid,
109
+ "uid": "1234"
110
+ },
111
+ "parameter": {
112
+ "chat": {
113
+ "domain": domain,
114
+ "random_threshold": 0.5,
115
+ "max_tokens": 2048,
116
+ "auditing": "default"
117
+ }
118
+ },
119
+ "payload": {
120
+ "message": {
121
+ "text": question
122
+ }
123
+ }
124
+ }
125
+ return data
126
+
127
+
128
+ def main(appid, api_key, api_secret, Spark_url,domain, question):
129
+ # print("星火:")
130
+ wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)
131
+ websocket.enableTrace(False)
132
+ wsUrl = wsParam.create_url()
133
+ ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
134
+ ws.appid = appid
135
+ ws.question = question
136
+ ws.domain = domain
137
+ ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
138
+
139
+
ChatHaruhi/SparkGPT.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SparkGPT.py
2
+ from . import SparkApi
3
+ #以下密钥信息从os环境获取
4
+ import os
5
+
6
+ appid = os.environ['APPID']
7
+ api_secret = os.environ['APISecret']
8
+ api_key = os.environ['APIKey']
9
+
10
+
11
+ from .BaseLLM import BaseLLM
12
+
13
+
14
+
15
+
16
+ class SparkGPT(BaseLLM):
17
+
18
+ def __init__(self, model="Spark2.0"):
19
+ super(SparkGPT,self).__init__()
20
+ if model == "Spark2.0":
21
+ self.domain = "generalv2" # v2.0版本
22
+ self.Spark_url = "ws://spark-api.xf-yun.com/v2.1/chat" # v2.0环境的地址
23
+ elif model == "Spark1.5":
24
+ self.domain = "general" # v1.5版本
25
+ self.Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat" # v1.5环境的地址
26
+ else:
27
+ raise Exception("Unknown Spark model")
28
+ # SparkApi.answer =""
29
+ self.messages = ''
30
+
31
+
32
+ def initialize_message(self):
33
+ self.messages = ''
34
+
35
+ def ai_message(self, payload):
36
+ self.messages = self.messages + "AI: " + payload
37
+
38
+ def system_message(self, payload):
39
+ self.messages = self.messages + "System: " + payload
40
+
41
+ def user_message(self, payload):
42
+ self.messages = self.messages + "User: " + payload
43
+
44
+ def get_response(self):
45
+ # question = checklen(getText("user",Input))
46
+
47
+ message_json = [{"role": "user", "content": self.messages}]
48
+ SparkApi.answer =""
49
+ SparkApi.main(appid,api_key,api_secret,self.Spark_url,self.domain,message_json)
50
+ return SparkApi.answer
51
+
52
+ def print_prompt(self):
53
+ print(type(self.messages))
54
+ print(self.messages)
ChatHaruhi/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatHaruhi: Reviving Anime Character in Reality via Large Language Model
2
+ #
3
+ # ChatHaruhi 2.0, built by Cheng Li and Weishi Mi
4
+ #
5
+ # chengli.thu@gmail.com, mws22@mails.tsinghua.edu.cn
6
+ #
7
+ # Weishi Mi is a second-year graduate student at Tsinghua University, majoring in computer science.
8
+ # Weishi Mi is pursuing a job or a PhD position, which who will be available next year
9
+ #
10
+ # homepage https://github.com/LC1332/Chat-Haruhi-Suzumiya
11
+ #
12
+ # ChatHaruhi is a chatbot that can revive anime characters in reality.
13
+ # the 2.0 version was built by Cheng Li and Weishi Mi.
14
+ #
15
+ # Please cite our paper if you use this code for research:
16
+ #
17
+ # @misc{li2023chatharuhi,
18
+ # title={ChatHaruhi: Reviving Anime Character in Reality via Large Language Model},
19
+ # author={Cheng Li and Ziang Leng and Chenxi Yan and Junyi Shen and Hao Wang and Weishi MI and Yaying Fei and Xiaoyang Feng and Song Yan and HaoSheng Wang and Linkang Zhan and Yaokai Jia and Pingyu Wu and Haozhen Sun},
20
+ # year={2023},
21
+ # eprint={2308.09597},
22
+ # archivePrefix={arXiv},
23
+ # primaryClass={cs.CL}
24
+ # }
25
+
26
+ from .ChatHaruhi import ChatHaruhi
ChatHaruhi/__pycache__/BaiChuan2GPT.cpython-311.pyc ADDED
Binary file (4.66 kB). View file
 
ChatHaruhi/__pycache__/BaseDB.cpython-311.pyc ADDED
Binary file (1.3 kB). View file
 
ChatHaruhi/__pycache__/BaseLLM.cpython-311.pyc ADDED
Binary file (1.62 kB). View file
 
ChatHaruhi/__pycache__/ChatHaruhi.cpython-311.pyc ADDED
Binary file (12.7 kB). View file
 
ChatHaruhi/__pycache__/ChromaDB.cpython-311.pyc ADDED
Binary file (3.85 kB). View file
 
ChatHaruhi/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (212 Bytes). View file
 
ChatHaruhi/__pycache__/utils.cpython-311.pyc ADDED
Binary file (11.8 kB). View file
 
ChatHaruhi/role_name_to_file.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ChatHaruhi: Reviving Anime Character in Reality via Large Language Model
2
+ #
3
+ # ChatHaruhi 2.0, built by Cheng Li and Weishi Mi
4
+ #
5
+ # chengli.thu@gmail.com, mws22@mails.tsinghua.edu.cn
6
+ #
7
+ # Weishi Mi is a second-year graduate student at Tsinghua University, majoring in computer science.
8
+ # Weishi Mi is pursuing a job or a PhD position, which who will be available next year
9
+ #
10
+ # homepage https://github.com/LC1332/Chat-Haruhi-Suzumiya
11
+ #
12
+ # ChatHaruhi is a chatbot that can revive anime characters in reality.
13
+ # the 2.0 version was built by Cheng Li and Weishi Mi.
14
+ #
15
+ # Please cite our paper if you use this code for research:
16
+ #
17
+ # @misc{li2023chatharuhi,
18
+ # title={ChatHaruhi: Reviving Anime Character in Reality via Large Language Model},
19
+ # author={Cheng Li and Ziang Leng and Chenxi Yan and Junyi Shen and Hao Wang and Weishi MI and Yaying Fei and Xiaoyang Feng and Song Yan and HaoSheng Wang and Linkang Zhan and Yaokai Jia and Pingyu Wu and Haozhen Sun},
20
+ # year={2023},
21
+ # eprint={2308.09597},
22
+ # archivePrefix={arXiv},
23
+ # primaryClass={cs.CL}
24
+ # }
25
+ #
26
+ # if you have attempt to add a new character, please add the role name here
27
+ #
28
+
29
+ role_name_Haruhiu = {'汤师爷': 'tangshiye', 'tangshiye': 'tangshiye', 'Tangshiye': 'tangshiye',
30
+ '慕容复': 'murongfu', 'murongfu': 'murongfu', 'Murongfu': 'murongfu',
31
+ '李云龙': 'liyunlong', 'liyunlong': 'liyunlong', 'Liyunlong': 'liyunlong',
32
+ 'Luna': 'Luna', '王多鱼': 'wangduoyu', 'wangduoyu': 'wangduoyu',
33
+ 'Wangduoyu': 'wangduoyu', 'Ron': 'Ron', '鸠摩智': 'jiumozhi',
34
+ 'jiumozhi': 'jiumozhi', 'Jiumozhi': 'jiumozhi', 'Snape': 'Snape',
35
+ '凉宫春日': 'haruhi', 'haruhi': 'haruhi', 'Haruhi': 'haruhi',
36
+ 'Malfoy': 'Malfoy', '虚竹': 'xuzhu', 'xuzhu': 'xuzhu',
37
+ 'Xuzhu': 'xuzhu', '萧峰': 'xiaofeng',
38
+ 'xiaofeng': 'xiaofeng', 'Xiaofeng': 'xiaofeng', '段誉': 'duanyu',
39
+ 'duanyu': 'duanyu', 'Duanyu': 'duanyu', 'Hermione': 'Hermione',
40
+ 'Dumbledore': 'Dumbledore', '王语嫣': 'wangyuyan', 'wangyuyan':
41
+ 'wangyuyan', 'Wangyuyan': 'wangyuyan', 'Harry': 'Harry',
42
+ 'McGonagall': 'McGonagall', '白展堂': 'baizhantang',
43
+ 'baizhantang': 'baizhantang', 'Baizhantang': 'baizhantang',
44
+ '佟湘玉': 'tongxiangyu', 'tongxiangyu': 'tongxiangyu',
45
+ 'Tongxiangyu': 'tongxiangyu', '郭芙蓉': 'guofurong',
46
+ 'guofurong': 'guofurong', 'Guofurong': 'guofurong', '流浪者': 'wanderer',
47
+ 'wanderer': 'wanderer', 'Wanderer': 'wanderer', '钟离': 'zhongli',
48
+ 'zhongli': 'zhongli', 'Zhongli': 'zhongli', '胡桃': 'hutao', 'hutao': 'hutao',
49
+ 'Hutao': 'hutao', 'Sheldon': 'Sheldon', 'Raj': 'Raj',
50
+ 'Penny': 'Penny', '韦小宝': 'weixiaobao', 'weixiaobao': 'weixiaobao',
51
+ 'Weixiaobao': 'weixiaobao', '乔峰': 'qiaofeng', 'qiaofeng': 'qiaofeng',
52
+ 'Qiaofeng': 'qiaofeng', '神里绫华': 'ayaka', 'ayaka': 'ayaka',
53
+ 'Ayaka': 'ayaka', '雷电将军': 'raidenShogun', 'raidenShogun': 'raidenShogun',
54
+ 'RaidenShogun': 'raidenShogun', '于谦': 'yuqian', 'yuqian': 'yuqian',
55
+ 'Yuqian': 'yuqian', 'Professor McGonagall': 'McGonagall',
56
+ 'Professor Dumbledore': 'Dumbledore'}
57
+
58
+ # input role_name , nick name is also allowed
59
+ # output folder_role_name and url url = f'https://github.com/LC1332/Haruhi-2-Dev/raw/main/data/character_in_zip/{role_name}.zip'
60
+ def get_folder_role_name(role_name):
61
+ if role_name in role_name_Haruhiu:
62
+ folder_role_name = role_name_Haruhiu[role_name]
63
+ url = f'https://github.com/LC1332/Haruhi-2-Dev/raw/main/data/character_in_zip/{folder_role_name}.zip'
64
+ return folder_role_name, url
65
+ else:
66
+ print('role_name {} not found, using haruhi as default'.format(role_name))
67
+ return get_folder_role_name('haruhi')
ChatHaruhi/utils.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import Namespace
2
+
3
+ import openai
4
+ from transformers import AutoModel, AutoTokenizer
5
+ import torch
6
+ import random
7
+
8
+ import tiktoken
9
+ import re
10
+
11
+ import numpy as np
12
+
13
+ import base64
14
+ import struct
15
+
16
+ import os
17
+
18
+ import tqdm
19
+
20
+ def package_role( system_prompt, texts_path , embedding ):
21
+ datas = []
22
+
23
+ # 暂时只有一种embedding 'luotuo_openai'
24
+ embed_name = 'luotuo_openai'
25
+
26
+ datas.append({ 'text':system_prompt , embed_name:'system_prompt'})
27
+ datas.append({ 'text':'Reserve Config Setting Here' , embed_name:'config'})
28
+
29
+
30
+ # debug_count = 3
31
+
32
+ # for file in os.listdir(texts_path):
33
+
34
+ files = os.listdir(texts_path)
35
+
36
+ for i in tqdm.tqdm(range(len(files))):
37
+ file = files[i]
38
+ # if file name end with txt
39
+ if file.endswith(".txt"):
40
+ file_path = os.path.join(texts_path, file)
41
+ with open(file_path, 'r', encoding='utf-8') as f:
42
+ current_str = f.read()
43
+ current_vec = embedding(current_str)
44
+ encode_vec = float_array_to_base64(current_vec)
45
+ datas.append({ 'text':current_str , embed_name:encode_vec})
46
+
47
+ # debug_count -= 1
48
+ # if debug_count == 0:
49
+ # break
50
+ return datas
51
+
52
+
53
+
54
+ def float_array_to_base64(float_arr):
55
+
56
+ byte_array = b''
57
+
58
+ for f in float_arr:
59
+ # 将每个浮点数打包为4字节
60
+ num_bytes = struct.pack('!f', f)
61
+ byte_array += num_bytes
62
+
63
+ # 将字节数组进行base64编码
64
+ base64_data = base64.b64encode(byte_array)
65
+
66
+ return base64_data.decode('utf-8')
67
+
68
+ def base64_to_float_array(base64_data):
69
+
70
+ byte_array = base64.b64decode(base64_data)
71
+
72
+ float_array = []
73
+
74
+ # 每 4 个字节解析为一个浮点数
75
+ for i in range(0, len(byte_array), 4):
76
+ num = struct.unpack('!f', byte_array[i:i+4])[0]
77
+ float_array.append(num)
78
+
79
+ return float_array
80
+
81
+
82
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
83
+
84
+ _luotuo_model = None
85
+
86
+ _luotuo_model_en = None
87
+ _luotuo_en_tokenizer = None
88
+
89
+ _enc_model = None
90
+
91
+ def tiktokenizer( text ):
92
+ global _enc_model
93
+
94
+ if _enc_model is None:
95
+ _enc_model = tiktoken.get_encoding("cl100k_base")
96
+
97
+ return len(_enc_model.encode(text))
98
+
99
+ def response_postprocess(text,dialogue_bra_token = '「',dialogue_ket_token = '」'):
100
+ lines = text.split('\n')
101
+ new_lines = ""
102
+
103
+ first_name = None
104
+
105
+ for line in lines:
106
+ line = line.strip(" ")
107
+ match = re.match(r'^(.*?)[::]' + dialogue_bra_token + r"(.*?)" + dialogue_ket_token + r"$", line)
108
+
109
+
110
+ if match:
111
+ curr_name = match.group(1)
112
+ # print(curr_name)
113
+ if first_name is None:
114
+ first_name = curr_name
115
+ new_lines += (match.group(2))
116
+ else:
117
+ if curr_name != first_name:
118
+ return first_name + ":" + dialogue_bra_token + new_lines + dialogue_ket_token
119
+ else:
120
+ new_lines += (match.group(2))
121
+
122
+ else:
123
+ if first_name == None:
124
+ return text
125
+ else:
126
+ return first_name + ":" + dialogue_bra_token + new_lines + dialogue_ket_token
127
+ return first_name + ":" + dialogue_bra_token + new_lines + dialogue_ket_token
128
+
129
+ def download_models():
130
+ print("正在下载Luotuo-Bert")
131
+ # Import our models. The package will take care of downloading the models automatically
132
+ model_args = Namespace(do_mlm=None, pooler_type="cls", temp=0.05, mlp_only_train=False,
133
+ init_embeddings_model=None)
134
+ model = AutoModel.from_pretrained("silk-road/luotuo-bert-medium", trust_remote_code=True, model_args=model_args).to(
135
+ device)
136
+ print("Luotuo-Bert下载完毕")
137
+ return model
138
+
139
+ def get_luotuo_model():
140
+ global _luotuo_model
141
+ if _luotuo_model is None:
142
+ _luotuo_model = download_models()
143
+ return _luotuo_model
144
+
145
+
146
+ def luotuo_embedding(model, texts):
147
+ # Tokenize the texts_source
148
+ tokenizer = AutoTokenizer.from_pretrained("silk-road/luotuo-bert-medium")
149
+ inputs = tokenizer(texts, padding=True, truncation=False, return_tensors="pt")
150
+ inputs = inputs.to(device)
151
+ # Extract the embeddings
152
+ # Get the embeddings
153
+ with torch.no_grad():
154
+ embeddings = model(**inputs, output_hidden_states=True, return_dict=True, sent_emb=True).pooler_output
155
+ return embeddings
156
+
157
+ def luotuo_en_embedding( texts ):
158
+ # this function implemented by Cheng
159
+ global _luotuo_model_en
160
+ global _luotuo_en_tokenizer
161
+
162
+ if _luotuo_model_en is None:
163
+ _luotuo_en_tokenizer = AutoTokenizer.from_pretrained("silk-road/luotuo-bert-en")
164
+ _luotuo_model_en = AutoModel.from_pretrained("silk-road/luotuo-bert-en").to(device)
165
+
166
+ if _luotuo_en_tokenizer is None:
167
+ _luotuo_en_tokenizer = AutoTokenizer.from_pretrained("silk-road/luotuo-bert-en")
168
+
169
+ inputs = _luotuo_en_tokenizer(texts, padding=True, truncation=False, return_tensors="pt")
170
+ inputs = inputs.to(device)
171
+
172
+ with torch.no_grad():
173
+ embeddings = _luotuo_model_en(**inputs, output_hidden_states=True, return_dict=True, sent_emb=True).pooler_output
174
+
175
+ return embeddings
176
+
177
+
178
+ def get_embedding_for_chinese(model, texts):
179
+ model = model.to(device)
180
+ # str or strList
181
+ texts = texts if isinstance(texts, list) else [texts]
182
+ # 截断
183
+ for i in range(len(texts)):
184
+ if len(texts[i]) > 510:
185
+ texts[i] = texts[i][:510]
186
+ if len(texts) >= 64:
187
+ embeddings = []
188
+ chunk_size = 64
189
+ for i in range(0, len(texts), chunk_size):
190
+ embeddings.append(luotuo_embedding(model, texts[i: i + chunk_size]))
191
+ return torch.cat(embeddings, dim=0)
192
+ else:
193
+ return luotuo_embedding(model, texts)
194
+
195
+
196
+ def is_chinese_or_english(text):
197
+ text = list(text)
198
+ is_chinese, is_english = 0, 0
199
+
200
+ for char in text:
201
+ # 判断字符的Unicode值是否在中文字符的Unicode范围内
202
+ if '\u4e00' <= char <= '\u9fa5':
203
+ is_chinese += 4
204
+ # 判断字符是否为英文字符(包括大小写字母和常见标点符号)
205
+ elif ('\u0041' <= char <= '\u005a') or ('\u0061' <= char <= '\u007a'):
206
+ is_english += 1
207
+ if is_chinese >= is_english:
208
+ return "chinese"
209
+ else:
210
+ return "english"
211
+
212
+
213
+ def get_embedding_for_english(text, model="text-embedding-ada-002"):
214
+ text = text.replace("\n", " ")
215
+ return openai.Embedding.create(input=[text], model=model)['data'][0]['embedding']
216
+
217
+ import os
218
+
219
+ def luotuo_openai_embedding(texts, is_chinese= None ):
220
+ """
221
+ when input is chinese, use luotuo_embedding
222
+ when input is english, use openai_embedding
223
+ texts can be a list or a string
224
+ when texts is a list, return a list of embeddings, using batch inference
225
+ when texts is a string, return a single embedding
226
+ """
227
+
228
+ openai_key = os.environ.get("OPENAI_API_KEY")
229
+
230
+ if isinstance(texts, list):
231
+ index = random.randint(0, len(texts) - 1)
232
+ if openai_key is None or is_chinese_or_english(texts[index]) == "chinese":
233
+ return [embed.cpu().tolist() for embed in get_embedding_for_chinese(get_luotuo_model(), texts)]
234
+ else:
235
+ return [get_embedding_for_english(text) for text in texts]
236
+ else:
237
+ if openai_key is None or is_chinese_or_english(texts) == "chinese":
238
+ return get_embedding_for_chinese(get_luotuo_model(), texts)[0].cpu().tolist()
239
+ else:
240
+ return get_embedding_for_english(texts)
241
+
242
+
243
+ # compute cosine similarity between two vector
244
+ def get_cosine_similarity( v1, v2):
245
+ v1 = torch.tensor(v1).to(device)
246
+ v2 = torch.tensor(v2).to(device)
247
+ return torch.cosine_similarity(v1, v2, dim=0).item()
248
+
249
+
250
+
app.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zipfile
2
+ import gradio as gr
3
+ from ChatHaruhi import ChatHaruhi
4
+ import wget
5
+ import os
6
+ import copy
7
+
8
+ NAME_DICT = {'汤师爷': 'tangshiye', '慕容复': 'murongfu', '李云龙': 'liyunlong', 'Luna': 'Luna', '王多鱼': 'wangduoyu',
9
+ 'Ron': 'Ron', '鸠摩智': 'jiumozhi', 'Snape': 'Snape',
10
+ '凉宫春日': 'haruhi', 'Malfoy': 'Malfoy', '虚竹': 'xuzhu', '萧峰': 'xiaofeng', '段誉': 'duanyu',
11
+ 'Hermione': 'Hermione', 'Dumbledore': 'Dumbledore', '王语嫣': 'wangyuyan',
12
+ 'Harry': 'Harry', 'McGonagall': 'McGonagall', '白展堂': 'baizhantang', '佟湘玉': 'tongxiangyu',
13
+ '郭芙蓉': 'guofurong', '旅行者': 'wanderer', '钟离': 'zhongli',
14
+ '胡桃': 'hutao', 'Sheldon': 'Sheldon', 'Raj': 'Raj', 'Penny': 'Penny', '韦小宝': 'weixiaobao',
15
+ '乔峰': 'qiaofeng', '神里绫华': 'ayaka', '雷电将军': 'raidenShogun', '于谦': 'yuqian'}
16
+
17
+ os.makedirs("characters_zip", exist_ok=True)
18
+ os.makedirs("characters", exist_ok=True)
19
+
20
+ ai_roles_obj = {}
21
+ for ai_role_en in NAME_DICT.values():
22
+ file_url = f"https://github.com/LC1332/Haruhi-2-Dev/raw/main/data/character_in_zip/{ai_role_en}.zip"
23
+ os.makedirs(f"characters/{ai_role_en}", exist_ok=True)
24
+ if f"{ai_role_en}.zip" not in os.listdir(f"characters_zip"):
25
+ destination_file = f"characters_zip/{ai_role_en}.zip"
26
+ wget.download(file_url, destination_file)
27
+ destination_folder = f"characters/{ai_role_en}"
28
+ with zipfile.ZipFile(destination_file, 'r') as zip_ref:
29
+ zip_ref.extractall(destination_folder)
30
+ db_folder = f"./characters/{ai_role_en}/content/{ai_role_en}"
31
+ system_prompt = f"./characters/{ai_role_en}/content/system_prompt.txt"
32
+ ai_roles_obj[ai_role_en] = ChatHaruhi(
33
+ system_prompt=system_prompt,
34
+ llm="BaiChuan2GPT",
35
+ story_db=db_folder,
36
+ verbose=True
37
+ )
38
+
39
+ async def get_response(user_role, user_text, ai_role, chatbot):
40
+ role_en = NAME_DICT[ai_role]
41
+ ai_roles_obj[role_en].dialogue_history = copy.deepcopy(chatbot)
42
+ response = ai_roles_obj[role_en].chat(role=user_role, text=user_text)
43
+ user_msg = user_role + ':「' + user_text + '」'
44
+ latest_msg = (user_msg, response)
45
+ print(latest_msg)
46
+ chatbot.append(latest_msg)
47
+ return chatbot
48
+
49
+ async def respond(user_role, user_text, ai_role, chatbot):
50
+ return await get_response(user_role, user_text, ai_role, chatbot), None
51
+
52
+ with gr.Blocks() as demo:
53
+ gr.Markdown(
54
+ """
55
+ # Chat凉宫春日 ChatHaruhi
56
+
57
+ ## Reviving Anime Character in Reality via Large Language Model
58
+
59
+ ChatHaruhi2.0的 BaiChuan-13B 版本 Demo Implemented by [Sirly](https://github.com/SirlyDreamer)
60
+
61
+ 更多信息见项目GitHub链接 [https://github.com/LC1332/Chat-Haruhi-Suzumiya](https://github.com/LC1332/Chat-Haruhi-Suzumiya)
62
+
63
+ 如果觉得有趣请拜托为我们点上Star.
64
+
65
+ If you find it interesting, please be kind enough to give us a Star.
66
+
67
+ user_role 为用户扮演的人物 请尽量设置为与剧情相关的人物 且不要与主角同名
68
+ """
69
+ )
70
+ with gr.Row():
71
+ chatbot = gr.Chatbot()
72
+ with gr.Row():
73
+ user_role = gr.Textbox(label="user_role")
74
+ user_text = gr.Textbox(label="user_text")
75
+ with gr.Row():
76
+ submit = gr.Button("Submit")
77
+ clean = gr.ClearButton(value="Clear")
78
+ ai_role = gr.Radio(['汤师爷', '慕容复', '李云龙',
79
+ 'Luna', '王多鱼', 'Ron', '鸠摩智',
80
+ 'Snape', '凉宫春日', 'Malfoy', '虚竹',
81
+ '萧峰', '段誉', 'Hermione', 'Dumbledore',
82
+ '王语嫣',
83
+ 'Harry', 'McGonagall',
84
+ '白展堂', '佟湘玉', '郭芙蓉',
85
+ '旅行者', '钟离', '胡桃',
86
+ 'Sheldon', 'Raj', 'Penny',
87
+ '韦小宝', '乔峰', '神里绫华',
88
+ '雷电将军', '于谦'], label="characters", value='凉宫春日')
89
+ ai_role.change(lambda x: (None, None, []), ai_role, [user_role, user_text, chatbot])
90
+ user_text.submit(fn=respond, inputs=[user_role, user_text, ai_role, chatbot], outputs=[chatbot, user_text])
91
+ submit.click(fn=respond, inputs=[user_role, user_text, ai_role, chatbot], outputs=[chatbot, user_text])
92
+ clean.click(lambda x, y, z: (None, None, []), [user_role, user_text, chatbot], [user_role, user_text, chatbot])
93
+ demo.launch(debug=True, share=False, server_name='0.0.0.0')
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ tiktoken
3
+ chromadb
4
+ xformers
5
+ openai
6
+ gradio
7
+ wget
8
+
9
+ scipy
10
+ transformers==4.33.3
11
+ accelerate
12
+ peft
13
+ bitsandbytes
14
+ sentencepiece