QiuLingYan commited on
Commit
b97255d
1 Parent(s): b51ab28

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +14 -0
  2. app.py +172 -0
  3. requirements.txt +4 -0
README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatYuan Large V2
3
+ emoji: 📊
4
+ colorFrom: red
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 3.23.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: creativeml-openrail-m
11
+ duplicated_from: ClueAI/ChatYuan-large-v2
12
+ ---
13
+
14
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import clueai
4
+ import torch
5
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
6
+ tokenizer = T5Tokenizer.from_pretrained("ClueAI/ChatYuan-large-v2")
7
+ model = T5ForConditionalGeneration.from_pretrained("ClueAI/ChatYuan-large-v2")
8
+ # 使用
9
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
10
+ model.to(device)
11
+
12
+ base_info = "用户:你是谁?\n小元:我是元语智能公司研发的AI智能助手, 在不违反原则的情况下,我可以回答你的任何问题。\n"
13
+ def preprocess(text):
14
+ text = f"{base_info}{text}"
15
+ text = text.replace("\n", "\\n").replace("\t", "\\t")
16
+ return text
17
+
18
+ def postprocess(text):
19
+ return text.replace("\\n", "\n").replace("\\t", "\t").replace('%20',' ')#.replace(" ", " ")
20
+
21
+
22
+
23
+ generate_config = {'do_sample': True, 'top_p': 0.9, 'top_k': 50, 'temperature': 0.7,
24
+ 'num_beams': 1, 'max_length': 1024, 'min_length': 3, 'no_repeat_ngram_size': 5,
25
+ 'length_penalty': 0.6, 'return_dict_in_generate': True, 'output_scores': True}
26
+ def answer(text, sample=True, top_p=0.9, temperature=0.7):
27
+ '''sample:是否抽样。生成任务,可以设置为True;
28
+ top_p:0-1之间,生成的内容越多样'''
29
+ text = preprocess(text)
30
+ encoding = tokenizer(text=[text], truncation=True, padding=True, max_length=1024, return_tensors="pt").to(device)
31
+ if not sample:
32
+ out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=1024, num_beams=1, length_penalty=0.6)
33
+ else:
34
+ out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_new_tokens=1024, do_sample=True, top_p=top_p, temperature=temperature, no_repeat_ngram_size=12)
35
+ #out=model.generate(**encoding, **generate_config)
36
+ out_text = tokenizer.batch_decode(out["sequences"], skip_special_tokens=True)
37
+ return postprocess(out_text[0])
38
+
39
+ def clear_session():
40
+ return '', None
41
+
42
+ def chatyuan_bot(input, history):
43
+ history = history or []
44
+ if len(history) > 5:
45
+ history = history[-5:]
46
+
47
+ context = "\n".join([f"用户:{input_text}\n小元:{answer_text}" for input_text, answer_text in history])
48
+ #print(context)
49
+
50
+ input_text = context + "\n用户:" + input + "\n小元:"
51
+ input_text = input_text.strip()
52
+ output_text = answer(input_text)
53
+ print("open_model".center(20, "="))
54
+ print(f"{input_text}\n{output_text}")
55
+ #print("="*20)
56
+ history.append((input, output_text))
57
+ #print(history)
58
+ return history, history
59
+ def chatyuan_bot_regenerate(input, history):
60
+
61
+ history = history or []
62
+
63
+ if history:
64
+ input=history[-1][0]
65
+ history=history[:-1]
66
+
67
+
68
+ if len(history) > 5:
69
+ history = history[-5:]
70
+
71
+ context = "\n".join([f"用户:{input_text}\n小元:{answer_text}" for input_text, answer_text in history])
72
+ #print(context)
73
+
74
+ input_text = context + "\n用户:" + input + "\n小元:"
75
+ input_text = input_text.strip()
76
+ output_text = answer(input_text)
77
+ print("open_model".center(20, "="))
78
+ print(f"{input_text}\n{output_text}")
79
+ history.append((input, output_text))
80
+ #print(history)
81
+ return history, history
82
+
83
+ block = gr.Blocks()
84
+
85
+ with block as demo:
86
+ gr.Markdown("""<h1><center>元语智能——ChatYuan</center></h1>
87
+ <font size=4>回答来自ChatYuan, 是模型生成的结果, 请谨慎辨别和参考, 不代表任何人观点 | Answer generated by ChatYuan model</font>
88
+ <font size=4>注意:gradio对markdown代码格式展示有限</font>
89
+ """)
90
+ chatbot = gr.Chatbot(label='ChatYuan')
91
+ message = gr.Textbox()
92
+ state = gr.State()
93
+ message.submit(chatyuan_bot, inputs=[message, state], outputs=[chatbot, state])
94
+ with gr.Row():
95
+ clear_history = gr.Button("👋 清除历史对话 | Clear History")
96
+ clear = gr.Button('🧹 清除发送框 | Clear Input')
97
+ send = gr.Button("🚀 发送 | Send")
98
+ regenerate = gr.Button("🚀 重新生成本次结果 | regenerate")
99
+
100
+
101
+ regenerate.click(chatyuan_bot_regenerate, inputs=[message, state], outputs=[chatbot, state])
102
+ send.click(chatyuan_bot, inputs=[message, state], outputs=[chatbot, state])
103
+ clear.click(lambda: None, None, message, queue=False)
104
+ clear_history.click(fn=clear_session , inputs=[], outputs=[chatbot, state], queue=False)
105
+
106
+
107
+ def ChatYuan(api_key, text_prompt):
108
+
109
+ cl = clueai.Client(api_key,
110
+ check_api_key=True)
111
+ # generate a prediction for a prompt
112
+ # 需要返回得分的话,指定return_likelihoods="GENERATION"
113
+ prediction = cl.generate(model_name='ChatYuan-large', prompt=text_prompt)
114
+ # print the predicted text
115
+ #print('prediction: {}'.format(prediction.generations[0].text))
116
+ response = prediction.generations[0].text
117
+ if response == '':
118
+ response = "很抱歉,我无法回答这个问题"
119
+
120
+ return response
121
+
122
+ def chatyuan_bot_api(api_key, input, history):
123
+ history = history or []
124
+
125
+ if len(history) > 5:
126
+ history = history[-5:]
127
+
128
+ context = "\n".join([f"用户:{input_text}\n小元:{answer_text}" for input_text, answer_text in history])
129
+ #print(context)
130
+
131
+ input_text = context + "\n用户:" + input + "\n小元:"
132
+ input_text = input_text.strip()
133
+ output_text = ChatYuan(api_key, input_text)
134
+ print("api".center(20, "="))
135
+ print(f"api_key:{api_key}\n{input_text}\n{output_text}")
136
+ #print("="*20)
137
+ history.append((input, output_text))
138
+ #print(history)
139
+ return history, history
140
+
141
+
142
+
143
+ block = gr.Blocks()
144
+
145
+ with block as demo_1:
146
+ gr.Markdown("""<h1><center>元语智能——ChatYuan</center></h1>
147
+ <font size=4>回答来自ChatYuan, 以上是模型生成的结果, 请谨慎辨别和参考, 不代表任何人观点 | Answer generated by ChatYuan model</font>
148
+ <font size=4>注意:gradio对markdown代码格式展示有限</font>
149
+ <font size=4>在使用此功能前,你需要有个API key. API key 可以通过这个<a href='https://www.clueai.cn/' target="_blank">平台</a>获取</font>
150
+ """)
151
+ api_key = gr.inputs.Textbox(label="请输入你的api-key(必填)", default="", type='password')
152
+ chatbot = gr.Chatbot(label='ChatYuan')
153
+ message = gr.Textbox()
154
+ state = gr.State()
155
+ message.submit(chatyuan_bot_api, inputs=[api_key,message, state], outputs=[chatbot, state])
156
+ with gr.Row():
157
+ clear_history = gr.Button("👋 清除历史对话 | Clear Context")
158
+ clear = gr.Button('🧹 清除发送框 | Clear Input')
159
+ send = gr.Button("🚀 发送 | Send")
160
+
161
+ send.click(chatyuan_bot_api, inputs=[api_key,message, state], outputs=[chatbot, state],api_name='send')
162
+ clear.click(lambda: None, None, message, queue=False)
163
+ clear_history.click(fn=clear_session , inputs=[], outputs=[chatbot, state], queue=False)
164
+
165
+ block = gr.Blocks()
166
+ with block as introduction:
167
+ gr.Markdown("""啥也没有
168
+ """)
169
+
170
+
171
+ gui = gr.TabbedInterface(interface_list=[demo], tab_names=["开源模型"])
172
+ gui.launch(quiet=True,show_api=True, share = False)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ SentencePiece
4
+ clueai