lingbionlp commited on
Commit
9022b4b
1 Parent(s): a3ebfa7

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +6 -6
  2. app.py +447 -0
  3. model.py +82 -0
  4. requirements.txt +18 -0
README.md CHANGED
@@ -1,13 +1,13 @@
1
  ---
2
- title: Taiyi LLM
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.12.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Taiyi Demo
3
+ emoji: 💻
4
+ colorFrom: green
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 3.44.4
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from typing import Iterator
3
+ from model import run
4
+ import re
5
+ import copy
6
+ import time
7
+
8
+ ROLE_TEMP = 0
9
+ DESCRIPTION = """
10
+ <br>
11
+ <div align="center" style="font-size: 13pt;">
12
+ 🤗 <a href="https://huggingface.co/DUTIR-BioNLP/Taiyi-LLM" rel="nofollow">Hugging Face</a>&nbsp;&nbsp; | &nbsp;&nbsp;🤖 <a href="" rel="nofollow">ModelScope</a>&nbsp;&nbsp; | &nbsp;&nbsp;<img src="https://pic.imgdb.cn/item/651401a4c458853aef46f7f5.png" style="width: 13pt; display: inline-block;"> <a href="https://github.com/DUTIR-BioNLP/Taiyi-LLM">Github</a>
13
+ <br>
14
+ <br>
15
+ </div>
16
+ <br>
17
+ <center><font size=4>🚀<b style="color:red">Taiyi</b> is a bilingual (Chinese and English) biomedical large language model released by the Information Retrieval Laboratory of Dalian University of Technology.</font></center>
18
+ <br>
19
+ <center><font size=4>👆You can use the <b style="color: red">Enter</b> key to create a new line, and you can also hold down the <b style="color: red">Shift + Enter</b> keys to submit.</font></center>
20
+ <br>
21
+ """
22
+
23
+ BUTTON_DES = """
24
+ - <font size=3><b style="color:red">Retry</b>: If you are not satisfied with the current output of the model, you could use the Retry button to regenerate the response.</font>
25
+
26
+ - <font size=3><b style="color:red">Undo</b>: You can use the Undo button to revert the previous input.</font>
27
+
28
+ - <font size=3><b style="color:red">Clean</b>: Clear the history of the chat and start a new chat. If the topic of your conversation changes, it is recommended to use the Clean button to start a new chat.</font>
29
+
30
+ - <font size=3><b style="color:red">Submit</b>: Submit the text in the input box to the model.</font>
31
+ """
32
+
33
+ CONTRY_NUM = """
34
+ <br>
35
+ <center><a href="https://info.flagcounter.com/w63t"><img src="https://s11.flagcounter.com/mini/w63t/bg_FFFFFF/txt_000000/border_CCCCCC/flags_0/" alt="Flag Counter" border="0"></a></center>
36
+ <center><font size=3>⚠️ Please read the <a href="https://github.com/DUTIR-BioNLP/Taiyi-LLM#disclaimer" rel="nofollow">Disclaimer</a> on Github before you strat trying Taiyi.</font></center>
37
+ """
38
+
39
+
40
+ def check_ch_en(text):
41
+ ch_pat = re.compile(u'[\u4e00-\u9fa5]')
42
+ en_pat = re.compile(r'[a-zA-Z]')
43
+ has_ch = ch_pat.search(text)
44
+ has_en = en_pat.search(text)
45
+ if has_ch and has_en:
46
+ return True
47
+ elif has_ch:
48
+ return True
49
+ elif has_en:
50
+ return True
51
+ else:
52
+ return False
53
+
54
+ def clear_and_save_textbox(message: str):
55
+ return '', message
56
+
57
+ def Delete_Specified_String(history):
58
+
59
+ # 创建一个新的二维列表,用于存储不包含'你的输入无效'回答的问答对
60
+ filtered_history = []
61
+
62
+ # 遍历原始二维列表
63
+ for pair in history:
64
+ if pair[1] != '您的输入无效,请重新输入,谢谢!':
65
+ filtered_history.append(pair)
66
+
67
+ # 现在filtered_history中包含不包含'你的输入无效'回答的问答对
68
+
69
+ return filtered_history
70
+
71
+ def delete_prev_fn(history):
72
+ try:
73
+ message, _ = history.pop()
74
+ except IndexError:
75
+ message = ''
76
+ return history, message or ''
77
+
78
+
79
+ def remove_continuous_duplicate_sentences(text):
80
+ # 使用正则表达式分割文本,以句号、逗号、分号或换行符为分隔符
81
+ sentences = re.split(r'([。,;,\n])', text)
82
+
83
+ # 初始化一个新的文本列表,用于存储去除连续重复句子后的结果
84
+ new_sentences = [sentences[0]] # 将第一个句子添加到列表中
85
+
86
+ # 遍历句子列表,仅添加不与前一个句子相同的句子
87
+ for i in range(2, len(sentences), 2):
88
+ if sentences[i] != sentences[i - 2]:
89
+ new_sentences.append(sentences[i - 1] + sentences[i])
90
+
91
+ # 重新构建文本,使用原始标点符号连接句子
92
+ new_text = ''.join(new_sentences)
93
+
94
+ return new_text
95
+
96
+
97
+ def generate(
98
+ message: str,
99
+ history,
100
+ max_new_tokens: int,
101
+ temperature: float,
102
+ top_p: float
103
+ ):
104
+
105
+ # 检查是否为空字符
106
+ if not check_ch_en(message):
107
+ generator = "您的输入无效,请重新输入,谢谢!"
108
+ return history+[(message.replace('\n', '\n\n'), generator)]
109
+
110
+ # 检查history中是否包含了后处理的信息
111
+ history = Delete_Specified_String(history)
112
+ generator = run(message, history, max_new_tokens, temperature, top_p)
113
+ generator = remove_continuous_duplicate_sentences(generator)
114
+ history.append((message.replace('\n', '\n\n'), generator.replace('HuatuoGPT', '太一')))
115
+ return history
116
+
117
+
118
+ def change_textbox(choice):
119
+ global ROLE_TEMP
120
+ #根据不同输入对输出控件进行更新
121
+ if choice == "中文":
122
+ ROLE_TEMP = 1
123
+ role_state = gr.update(visible=True, value="请扮演一名医疗专家,回答后续问题。")
124
+
125
+ message = role_state['value']
126
+ history = []
127
+ response = generate(message,history,500, 0.10, 0.9)
128
+ return response
129
+ elif choice == "English":
130
+ ROLE_TEMP = 2
131
+ role_state = gr.update(visible=True, value="Act as a medical expert to answer the questions.")
132
+
133
+ message = role_state['value']
134
+ history = []
135
+ response = generate(message,history,500, 0.10, 0.9)
136
+ return response
137
+ else:
138
+ ROLE_TEMP = 0
139
+ message = ""
140
+ history = []
141
+ return []
142
+
143
+
144
+ def change_default_text():
145
+ return textbox.update(placeholder='Type a message...')
146
+
147
+
148
+ def role_process():
149
+ if ROLE_TEMP == 1:
150
+ message = "请扮演一名医疗专家,回答后续问题。"
151
+ history = []
152
+ response = generate(message,history,500, 0.10, 0.9)
153
+ return response
154
+ elif ROLE_TEMP == 2:
155
+ message = "Act as a medical expert to answer the questions."
156
+ history = []
157
+ response = generate(message,history,500, 0.10, 0.9)
158
+ return response
159
+ elif ROLE_TEMP == 0:
160
+ message = ""
161
+ history = []
162
+ return []
163
+
164
+
165
+
166
+
167
+ # 处理示例问题的函数
168
+ def process_example(message: str):
169
+ generator = generate(message, [], 500, 0.10, 0.9)
170
+
171
+ return '', generator
172
+
173
+
174
+ custom_css = """
175
+ #banner-image {
176
+ margin-left: auto;
177
+ margin-right: auto;
178
+ width: 65%;
179
+ height: 65%
180
+ }
181
+
182
+ #
183
+
184
+ """
185
+ with gr.Blocks(css=custom_css) as demo:
186
+
187
+ gr.Image("Images/LOGO.png", elem_id="banner-image", show_label=False, container=False)
188
+ with gr.Column():
189
+ gr.Markdown(DESCRIPTION)
190
+
191
+ with gr.Accordion(label = '⚠️ - About these buttons', open = False):
192
+ gr.Markdown(BUTTON_DES)
193
+
194
+ with gr.Group():
195
+ chatbot = gr.Chatbot(
196
+ label = 'Chatbot',
197
+ avatar_images=("Images/yonghu.png", "Images/robort.jpg"),
198
+ bubble_full_width=False
199
+ )
200
+
201
+ radio = gr.Radio(
202
+ ["中文", "English","None"],
203
+ value="None",
204
+ label="RolePlay(角色扮演)"
205
+ )
206
+ textbox = gr.Textbox(
207
+ container=False,
208
+ show_label=False,
209
+ placeholder="Select Chinese/English button to let Taiyi act as a Chinese/English medical assistant for a better medical QA and chat experience, and other BioNLP tasks can be typed a message directly. \n可选择医疗助手角色扮演,问答对话聊天效果更佳,其他任务可直接输入。",
210
+ lines=6
211
+ )
212
+
213
+ radio.change(fn=change_textbox, inputs=radio, outputs=chatbot)
214
+ radio.change(fn=change_default_text, outputs=textbox)
215
+
216
+
217
+ with gr.Row():
218
+ retry_button = gr.Button('🔄 Retry', variant='secondary')
219
+ undo_button = gr.Button('↩️ Undo', variant='secondary')
220
+ clear_button = gr.Button('🗑️ Clear', variant='secondary')
221
+ submit_button = gr.Button('🚩 Submit',variant='primary')
222
+
223
+
224
+ saved_input = gr.State()
225
+
226
+ with gr.Accordion(label = 'Advanced options', open = False):
227
+ max_new_tokens = gr.Slider(
228
+ label='Max new tokens',
229
+ minimum=1,
230
+ maximum=800,
231
+ step=1,
232
+ value=500,
233
+ interactive=True,
234
+ )
235
+ temperature = gr.Slider(
236
+ label='Temperature',
237
+ minimum=0,
238
+ maximum=1,
239
+ step=0.05,
240
+ value=0.10,
241
+ interactive=True,
242
+ )
243
+ top_p = gr.Slider(
244
+ label='Top-p (nucleus sampling)',
245
+ minimum=0,
246
+ maximum=1.0,
247
+ step=0.1,
248
+ value=0.9,
249
+ interactive=True,
250
+ )
251
+
252
+
253
+ with gr.Accordion(label = 'Examples', open = False):
254
+ gr.Examples(
255
+ examples=[
256
+ '最近肚子总是隐隐作痛,感觉胀胀的,吃下去的东西都没法吸收,胃疼的特别厉害,偶尔伴有恶心想吐的感觉,请问是什么回事?',
257
+ 'What is the best treatment for sleep problems?'
258
+ ],
259
+ inputs=textbox,
260
+ outputs=[textbox, chatbot],
261
+ fn=process_example,
262
+ cache_examples=False,
263
+ label='Question Answering'
264
+ )
265
+
266
+ gr.Examples(
267
+ examples=[
268
+ "患者:小孩受凉了,流清鼻涕,咳嗽,应该是风寒咳嗽,去药店买哪种药好呢\n医生:你好,宝宝咳嗽,流涕比较常见,西医角度上呼吸道感染可能性大,中医上叫做风寒咳嗽,请问宝宝除了咳嗽有没有其他不适症状呢?例如发热等,请详细描述一下,我好帮你诊治分析病情\n患者:精神状态好,也没有发热,就是喉咙有一点痛,咳嗽\n医生:先帮你分析一下病情,宝宝受凉之后免疫力降低,就会被细菌或病毒侵袭体内,气道分泌物增多,支气管平滑肌痉挛,咳嗽,咳痰,咽通。\n医生:目前没有发热,宝宝病情不重,不用过分紧张的。\n医生:我帮推荐治疗方法\n医生:宝宝目前多大了?有没有再医院看过?做过化验检查\n患者:嗯\n患者:7岁,没去医院,做过很多检查,平常就是爱咳嗽,喉哝发炎\n患者:医生说,扁桃体偏大\n医生:近期这次有没有去���院看过?做过检查\n医生:如果宝宝没有其他不适?可以口服氨溴索,桔贝合剂效果好\n医生:另外如果条件允许,可以做做雾化吸入治疗直接作用与支气管粘膜,效果更直接\n患者:不用做雾化吧,吃点药就行了\n医生:也可以先吃药\n患者:近期没有去过\n医生:你们这次没有去医院看过?\n患者:要吃消炎的吗\n患者:没\n患者:要吃消炎药吗\n医生:你好,可以先不吃的\n患者:那家里有蒲地蓝,可以吃吗\n患者:口服液\n患者:喉哝痛要吃吗\n医生:先治疗看看,可以吃的,假如宝宝出现发热或咳嗽加重,医院就诊,复查血常规和胸片,那个时候再考虑加抗生素\n患者:另外买个止咳的,行吗\n医生:我们的观点是宝宝小,尽量少吃消炎药,可以先吃那几个药三天看看效果\n患者:嗯谢谢\n根据上述对话,给出诊疗报告\n说明:诊疗报告分为主诉, 现病史, 辅助检查, 既往史, 诊断, 建议这六个章节。"
269
+ ],
270
+ inputs=textbox,
271
+ outputs=[textbox, chatbot],
272
+ fn=process_example,
273
+ cache_examples=False,
274
+ label='Medical Report Generation'
275
+ )
276
+
277
+ gr.Examples(
278
+ examples=[
279
+ '从下面文本中识别出指定的实体类型:\n治疗以选用大环内酯类抗生素,沙眼衣原体肺炎也可用磺胺二甲基异唑,年长儿和成人用氟喹诺酮类效果也很好。\n实体类型:疾病,药物',
280
+ 'Extract the gene, disease entities from the following text:\nIdentification of a novel FBN1 gene mutation in a Chinese family with Marfan syndrome.'
281
+ ],
282
+ inputs=textbox,
283
+ outputs=[textbox, chatbot],
284
+ fn=process_example,
285
+ cache_examples=False,
286
+ label='Name Entity Recognition'
287
+ )
288
+
289
+ gr.Examples(
290
+ examples=[
291
+ "给出句子中药物治疗关系类型的实体对:慢性阻塞性肺疾病@减少急性加重:有高质量的证据证实,β2 受体激动剂在减少 12-52 周急性加重方面比安慰剂更有效。",
292
+ "Find the relations of drug entity pairs in the text:\nMitotane has been reported to accelerate the metabolism of warfarin by the mechanism of hepatic microsomal enzyme induction, leading to an increase in dosage requirements for warfarin. Therefore, physicians should closely monitor patients for a change in anticoagulant dosage requirements when administering Mitotane to patients on coumarin-type anticoagulants. In addition, Mitotane should be given with caution to patients receiving other drugs susceptible to the influence of hepatic enzyme induction.\nRelation Types: ADVISE, MECHANISM, EFFECT, INT"
293
+ ],
294
+ inputs=textbox,
295
+ outputs=[textbox, chatbot],
296
+ fn=process_example,
297
+ cache_examples=False,
298
+ label='Relation Extraction'
299
+ )
300
+
301
+ gr.Examples(
302
+ examples=[
303
+ "找出指定的临床发现事件属性:\n因患者需期末考试,故予以口服“雷贝拉唑钠肠溶片”治疗,现腹痛情况明显好转。\n事件抽取说明:临床发现事件由主体词,发生状态,描述词和解剖部位组成",
304
+ 'Input text: "Contaminated drinking water is responsible for causing diarrheal diseases that kill millions of people a year.\nEven Types: Treatment of disease, Cause of disease\nRole Types: Cause, Theme\nPlease extract events from the input text.'
305
+ ],
306
+ inputs=textbox,
307
+ outputs=[textbox, chatbot],
308
+ fn=process_example,
309
+ cache_examples=False,
310
+ label='Event Extraction'
311
+ )
312
+
313
+ gr.Examples(
314
+ examples=[
315
+ "将下面中文文本翻译成英文:\n光动力疗法(PDT)作为一种新兴的肿瘤治疗手段,因其不良反应较少、靶向性好、可重复治疗等优点,已广泛应用于临床多种肿瘤的治疗。相比于手术、化疗及放疗等传统治疗策略,光动力疗法不仅可杀伤原位肿瘤,还可通过激活机体的免疫效应对转移瘤发挥抑制作用。然而,PDT诱导免疫效应的高低受多种因素影响,包括光敏剂在细胞内的定位和剂量、光参数、肿瘤内的氧浓度、免疫功能的完整性等。本文针对PDT介导抗肿瘤免疫效应的相关机制,以及PDT免疫效应的主要影响因素进行综述,以探讨PDT用于肿瘤治疗的未来发展方向。",
316
+ "Translate the following text into Chinese:\nNon-Alcoholic Fatty Liver Disease (NAFLD) is defined as increased liver fat percentage, and is the most common chronic liver disease in children. Rather than NAFLD, Metabolic-Associated Fatty Liver Disease (MAFLD), defined as increased liver fat with presence of adverse cardio-metabolic measures, might have more clinical relevance in children. We assessed the prevalence, risk-factors and cardio-metabolic outcomes of MAFLD at school-age."
317
+ ],
318
+ inputs=textbox,
319
+ outputs=[textbox, chatbot],
320
+ fn=process_example,
321
+ cache_examples=False,
322
+ label='Machine Translation'
323
+ )
324
+
325
+ gr.Examples(
326
+ examples=[
327
+ "请给下面摘要起标题:\n气管食管瘘是指气管或支气管与食管之间的病理性瘘道,包括气管-食管瘘和支气管-食管瘘,临床以气管-食管瘘较多见。气管食管瘘致病原因较多,可引起严重的并发症,是对患者生活质量影响显著、治疗困难和病死率较高的疾病。气管食管瘘目前治疗方式较多,但多数疗效欠佳,对新兴治疗手段的需求迫切。胸腹部X线摄影检出鼻胃管滞留是气管食管瘘诊断的金标准,其主要治疗方法包括外科手术治疗、支架置入、局部生物胶水封闭、干细胞治疗等。本文综述近年气管食管瘘诊断与治疗的主要研究进展,旨在为该病的临床诊治提供参考。",
328
+ "Output a title for the following abstract:\nThe incidence of diabetes mellitus has been increasing, prompting the search for non-invasive diagnostic methods. Although current methods exist, these have certain limitations, such as low reliability and accuracy, difficulty in individual patient adjustment, and discomfort during use. This paper presents a novel approach for diagnosing diabetes using high-frequency ultrasound (HFU) and a convolutional neural network (CNN). This method is based on the observation that glucose in red blood cells (RBCs) forms glycated hemoglobin (HbA1c) and accumulates on its surface. The study incubated RBCs with different glucose concentrations, collected acoustic reflection signals from them using a custom-designed 90-MHz transducer, and analyzed the signals using a CNN. The CNN was applied to the frequency spectra and spectrograms of the signal to identify correlations between changes in RBC properties owing to glucose concentration and signal features. The results confirmed the efficacy of the CNN-based approach with a classification accuracy of 0.98. This non-invasive diagnostic technology using HFU and CNN holds promise for in vivo diagnosis without the need for blood collection."
329
+ ],
330
+ inputs=textbox,
331
+ outputs=[textbox, chatbot],
332
+ fn=process_example,
333
+ cache_examples=False,
334
+ label='Title Generation'
335
+ )
336
+
337
+ gr.Examples(
338
+ examples=[
339
+ "现有以下文本:\n治皮肤病费用大概多少?\n请将上述文本分类至指定类别中:医疗费用,后果表述,指标解读,病情诊断,就医建议,疾病描述,其他,治疗方案,病因分析,功效作用,注意事项",
340
+ 'Document triage: "Will my mask from sherwin williams paint store with filters protect me from corona virus along with paint fumes?"\nLabels: patient, doctor'
341
+ ],
342
+ inputs=textbox,
343
+ outputs=[textbox, chatbot],
344
+ fn=process_example,
345
+ cache_examples=False,
346
+ label='Text Classification'
347
+ )
348
+
349
+ gr.Examples(
350
+ examples=[
351
+ "语句1:乙肝小二阳会转成小三阳吗?\n语句2:乙肝小三阳会不会转成肝硬化、肝癌?\n请从下面选项中评估这段文本的语义相似度:语义不相同,语义相同",
352
+ "1. How can someone's happiness level affect someone's health?\n2. Can staying happy improve my health? What specific steps should I take?\nAssess the semantic similarity of the text pairs based on the following labels: dissimilar, similar"
353
+ ],
354
+ inputs=textbox,
355
+ outputs=[textbox, chatbot],
356
+ fn=process_example,
357
+ cache_examples=False,
358
+ label='Text Semantic Similarity'
359
+ )
360
+
361
+
362
+ textbox.submit(
363
+ fn=clear_and_save_textbox,
364
+ inputs=textbox,
365
+ outputs=[textbox, saved_input],
366
+ api_name=False,
367
+ queue=False,
368
+ ).success(
369
+ fn=generate,
370
+ inputs=[
371
+ saved_input,
372
+ chatbot,
373
+ max_new_tokens,
374
+ temperature,
375
+ top_p,
376
+ ],
377
+ outputs=chatbot,
378
+ api_name=False,
379
+ )
380
+
381
+ button_event_preprocess = submit_button.click(
382
+ fn=clear_and_save_textbox,
383
+ inputs=textbox,
384
+ outputs=[textbox, saved_input],
385
+ api_name=False,
386
+ queue=False,
387
+ ).success(
388
+ fn=generate,
389
+ inputs=[
390
+ saved_input,
391
+ chatbot,
392
+ max_new_tokens,
393
+ temperature,
394
+ top_p,
395
+ ],
396
+ outputs=chatbot,
397
+ api_name=False,
398
+ )
399
+
400
+ retry_button.click(
401
+ fn=delete_prev_fn,
402
+ inputs=chatbot,
403
+ outputs=[chatbot, saved_input],
404
+ api_name=False,
405
+ queue=False,
406
+ ).then(
407
+ fn=generate,
408
+ inputs=[
409
+ saved_input,
410
+ chatbot,
411
+ max_new_tokens,
412
+ temperature,
413
+ top_p,
414
+ ],
415
+ outputs=chatbot,
416
+ api_name=False,
417
+ )
418
+
419
+ undo_button.click(
420
+ fn=delete_prev_fn,
421
+ inputs=chatbot,
422
+ outputs=[chatbot, saved_input],
423
+ api_name=False,
424
+ queue=False,
425
+ ).then(
426
+ fn=lambda x: x,
427
+ inputs=[saved_input],
428
+ outputs=textbox,
429
+ api_name=False,
430
+ queue=False,
431
+ )
432
+
433
+
434
+ clear_button.click(
435
+ fn=lambda: ([], ''),
436
+ outputs=[chatbot, saved_input],
437
+ queue=False,
438
+ api_name=False,
439
+ ).then(
440
+ fn=role_process,
441
+ outputs=[chatbot],
442
+ api_name=False
443
+ )
444
+
445
+ gr.HTML(CONTRY_NUM)
446
+
447
+ demo.queue().launch()
model.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ import torch
3
+
4
+
5
+ from peft import PeftModel
6
+
7
+ model_name = "DUTIR-BioNLP/Taiyi-LLM"
8
+ model = AutoModelForCausalLM.from_pretrained(
9
+ model_name,
10
+ trust_remote_code=True,
11
+ low_cpu_mem_usage=True,
12
+ torch_dtype=torch.float16 #torch_dtype=torch.float16
13
+ )
14
+
15
+ model.eval()
16
+
17
+ tokenizer = AutoTokenizer.from_pretrained(
18
+ model_name,
19
+ trust_remote_code=True
20
+ )
21
+
22
+
23
+ import logging
24
+ logging.disable(logging.WARNING)
25
+ tokenizer.pad_token_id = tokenizer.eod_id
26
+ tokenizer.bos_token_id = tokenizer.eod_id
27
+ tokenizer.eos_token_id = tokenizer.eod_id
28
+
29
+
30
+
31
+ # 开始对话
32
+ history_max_len = 1000
33
+ utterance_id = 0
34
+
35
+
36
+ def run(message: str,
37
+ history: str,
38
+ max_new_tokens: int = 500,
39
+ temperature: float = 0.10,
40
+ top_p: float = 0.9,
41
+ repetition_penalty: float = 1.0):
42
+
43
+ list1 = []
44
+ for question, response in history:
45
+
46
+ question = tokenizer(question, return_tensors="pt", add_special_tokens=False).input_ids
47
+ # eos_token_id = [tokenizer.eos_token_id]
48
+ eos_token_id = torch.tensor([[tokenizer.eos_token_id]], dtype=torch.long)
49
+ response = tokenizer(response, return_tensors="pt", add_special_tokens=False).input_ids
50
+ all_token = torch.concat((question, eos_token_id, response, eos_token_id), dim=1)
51
+ list1.extend(all_token)
52
+ connect_tensor = torch.tensor([])
53
+ for tensor in list1:
54
+ connect_tensor = torch.concat((connect_tensor, tensor), dim=0)
55
+
56
+ history_token_ids = connect_tensor.reshape(1,-1)
57
+
58
+
59
+
60
+ user_input = message
61
+
62
+ input_ids = tokenizer(user_input, return_tensors="pt", add_special_tokens=False).input_ids
63
+ bos_token_id = torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long)
64
+ eos_token_id = torch.tensor([[tokenizer.eos_token_id]], dtype=torch.long)
65
+ user_input_ids = torch.concat([bos_token_id,input_ids, eos_token_id], dim=1)
66
+
67
+ input_token_ids = torch.concat((history_token_ids, user_input_ids), dim=1)
68
+ model_input_ids = input_token_ids[:, -history_max_len:].to(torch.int)
69
+
70
+ with torch.no_grad():
71
+ outputs = model.generate(
72
+ input_ids=model_input_ids, max_new_tokens=max_new_tokens, do_sample=True, top_p=top_p,
73
+ temperature=temperature, repetition_penalty=repetition_penalty, eos_token_id=tokenizer.eos_token_id
74
+ )
75
+
76
+
77
+ model_input_ids_len = model_input_ids.size(1)
78
+ response_ids = outputs[:, model_input_ids_len:]
79
+ history_token_ids = torch.concat((history_token_ids, response_ids.cpu()), dim=1)
80
+ response = tokenizer.batch_decode(response_ids)
81
+ return response[0].strip().replace(tokenizer.eos_token, "").replace("\n", "\n\n")
82
+
requirements.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.21.0
2
+ transformers==4.31.0
3
+ peft==0.4.0
4
+ bitsandbytes==0.39.0
5
+ loguru==0.7.0
6
+ numpy==1.24.3
7
+ pandas==2.0.3
8
+ tqdm==4.62.3
9
+ deepspeed==0.9.5
10
+ tensorboard==2.14.0
11
+ sentencepiece==0.1.99
12
+ transformers_stream_generator==0.0.4
13
+ tiktoken==0.5.1
14
+ einops==0.6.1
15
+ torch==1.13.0
16
+ scipy==1.10.1
17
+ gradio==3.44.4
18
+ pydantic==1.10.12