Eriberto yizhangliu commited on
Commit
47b1e4a
0 Parent(s):

Duplicate from yizhangliu/chatGPT

Browse files

Co-authored-by: yizhangliu <[email protected]>

Files changed (5) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +330 -0
  4. baidu_translate/module.py +104 -0
  5. requirements.txt +4 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ChatGPT
3
+ emoji: 📊
4
+ colorFrom: blue
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 3.12.0
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: yizhangliu/chatGPT
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyChatGPT import ChatGPT
2
+ import gradio as gr
3
+ import os, sys, json
4
+ from loguru import logger
5
+ import paddlehub as hub
6
+ import random
7
+
8
+
9
+ language_translation_model = hub.Module(directory=f'./baidu_translate')
10
+ def getTextTrans(text, source='zh', target='en'):
11
+ def is_chinese(string):
12
+ for ch in string:
13
+ if u'\u4e00' <= ch <= u'\u9fff':
14
+ return True
15
+ return False
16
+
17
+ if not is_chinese(text) and target == 'en':
18
+ return text
19
+
20
+ try:
21
+ text_translation = language_translation_model.translate(text, source, target)
22
+ return text_translation
23
+ except Exception as e:
24
+ return text
25
+
26
+ session_token = os.environ.get('SessionToken')
27
+ # logger.info(f"session_token_: {session_token}")
28
+
29
+ def get_api():
30
+ api = None
31
+ try:
32
+ api = ChatGPT(session_token)
33
+ # api.refresh_auth()
34
+ except Exception as e:
35
+ print(f'get_api_error:', e)
36
+ api = None
37
+ return api
38
+
39
+
40
+ def get_response_from_chatgpt(api, text):
41
+ if api is None:
42
+ return "Openai said: I'm too tired. Let me lie down for a few days. If you like, you can visit my home."
43
+ try:
44
+ resp = api.send_message(text)
45
+ # api.refresh_auth()
46
+ # api.reset_conversation()
47
+ response = resp['message']
48
+ conversation_id = resp['conversation_id']
49
+ parent_id = resp['parent_id']
50
+ # logger.info(f"response_: {response}")
51
+ logger.info(f"conversation_id_: [{conversation_id}] / parent_id: [{parent_id}]")
52
+ except:
53
+ response = "Openai said: I'm so tired. Let me lie down for a few days. If you like, you can visit my home."
54
+ return response
55
+
56
+ start_work = """async() => {
57
+ function isMobile() {
58
+ try {
59
+ document.createEvent("TouchEvent"); return true;
60
+ } catch(e) {
61
+ return false;
62
+ }
63
+ }
64
+ function getClientHeight()
65
+ {
66
+ var clientHeight=0;
67
+ if(document.body.clientHeight&&document.documentElement.clientHeight) {
68
+ var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
69
+ } else {
70
+ var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
71
+ }
72
+ return clientHeight;
73
+ }
74
+
75
+ function setNativeValue(element, value) {
76
+ const valueSetter = Object.getOwnPropertyDescriptor(element.__proto__, 'value').set;
77
+ const prototype = Object.getPrototypeOf(element);
78
+ const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
79
+
80
+ if (valueSetter && valueSetter !== prototypeValueSetter) {
81
+ prototypeValueSetter.call(element, value);
82
+ } else {
83
+ valueSetter.call(element, value);
84
+ }
85
+ }
86
+ function save_conversation(chatbot) {
87
+ var conversations = new Array();
88
+ for (var i = 0; i < chatbot.children.length; i++) {
89
+ conversations[i] = chatbot.children[i].innerHTML;
90
+ }
91
+ var json_str = JSON.stringify(conversations);
92
+ localStorage.setItem('chatgpt_conversations', json_str);
93
+ }
94
+ function load_conversation(chatbot) {
95
+ var json_str = localStorage.getItem('chatgpt_conversations');
96
+ if (json_str) {
97
+ conversations = JSON.parse(json_str);
98
+ for (var i = 0; i < conversations.length; i++) {
99
+ var new_div = document.createElement("div");
100
+ if((i%2)===0){
101
+ new_div.className = "px-3 py-2 rounded-[22px] rounded-br-none text-white text-sm chat-message svelte-rct66g";
102
+ new_div.style.backgroundColor = "#16a34a";
103
+ } else {
104
+ new_div.className = "px-3 py-2 rounded-[22px] rounded-bl-none place-self-start text-white text-sm chat-message svelte-rct66g";
105
+ new_div.style.backgroundColor = "#2563eb";
106
+ if (conversations[i].indexOf("<img ") == 0) {
107
+ new_div.style.width = "80%";
108
+ new_div.style.padding = "0.2rem";
109
+ }
110
+ }
111
+ new_div.innerHTML = conversations[i];
112
+ chatbot.appendChild(new_div);
113
+ }
114
+ }
115
+ }
116
+ var gradioEl = document.querySelector('body > gradio-app').shadowRoot;
117
+ if (!gradioEl) {
118
+ gradioEl = document.querySelector('body > gradio-app');
119
+ }
120
+
121
+ if (typeof window['gradioEl'] === 'undefined') {
122
+ window['gradioEl'] = gradioEl;
123
+
124
+ const page1 = window['gradioEl'].querySelectorAll('#page_1')[0];
125
+ const page2 = window['gradioEl'].querySelectorAll('#page_2')[0];
126
+
127
+ page1.style.display = "none";
128
+ page2.style.display = "block";
129
+ window['div_count'] = 0;
130
+ window['chat_bot'] = window['gradioEl'].querySelectorAll('#chat_bot')[0];
131
+ window['chat_bot1'] = window['gradioEl'].querySelectorAll('#chat_bot1')[0];
132
+ chat_row = window['gradioEl'].querySelectorAll('#chat_row')[0];
133
+ prompt_row = window['gradioEl'].querySelectorAll('#prompt_row')[0];
134
+ window['chat_bot1'].children[1].textContent = '';
135
+
136
+ clientHeight = getClientHeight();
137
+ if (isMobile()) {
138
+ output_htmls = window['gradioEl'].querySelectorAll('.output-html');
139
+ for (var i = 0; i < output_htmls.length; i++) {
140
+ output_htmls[i].style.display = "none";
141
+ }
142
+ new_height = (clientHeight - 250) + 'px';
143
+ } else {
144
+ new_height = (clientHeight - 350) + 'px';
145
+ }
146
+ chat_row.style.height = new_height;
147
+ window['chat_bot'].style.height = new_height;
148
+ window['chat_bot'].children[2].style.height = new_height;
149
+ window['chat_bot1'].style.height = new_height;
150
+ window['chat_bot1'].children[2].style.height = new_height;
151
+ prompt_row.children[0].style.flex = 'auto';
152
+ prompt_row.children[0].style.width = '100%';
153
+ window['gradioEl'].querySelectorAll('#chat_radio')[0].style.flex = 'auto';
154
+ window['gradioEl'].querySelectorAll('#chat_radio')[0].style.width = '100%';
155
+ prompt_row.children[0].setAttribute('style','flex-direction: inherit; flex: 1 1 auto; width: 100%;border-color: green;border-width: 1px !important;')
156
+ window['chat_bot1'].children[1].setAttribute('style', 'border-bottom-right-radius:0;top:unset;bottom:0;padding-left:0.1rem');
157
+ window['gradioEl'].querySelectorAll('#btns_row')[0].children[0].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
158
+ window['gradioEl'].querySelectorAll('#btns_row')[0].children[1].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
159
+
160
+ load_conversation(window['chat_bot1'].children[2].children[0]);
161
+ window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
162
+
163
+ window['gradioEl'].querySelectorAll('#clear-btn')[0].onclick = function(e){
164
+ if (confirm('Clear all outputs?')==true) {
165
+ window['chat_bot1'].children[2].children[0].innerHTML = '';
166
+ save_conversation(window['chat_bot1'].children[2].children[0]);
167
+ }
168
+ }
169
+
170
+ window['prevPrompt'] = '';
171
+ window['doCheckPrompt'] = 0;
172
+ window['prevImgSrc'] = '';
173
+ window['checkChange'] = function checkChange() {
174
+ try {
175
+ if (window['gradioEl'].querySelectorAll('.gr-radio')[0].checked) {
176
+ if (window['chat_bot'].children[2].children[0].children.length > window['div_count']) {
177
+ new_len = window['chat_bot'].children[2].children[0].children.length - window['div_count'];
178
+ for (var i = 0; i < new_len; i++) {
179
+ new_div = window['chat_bot'].children[2].children[0].children[window['div_count'] + i].cloneNode(true);
180
+ window['chat_bot1'].children[2].children[0].appendChild(new_div);
181
+ }
182
+ window['div_count'] = chat_bot.children[2].children[0].children.length;
183
+ window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
184
+ save_conversation(window['chat_bot1'].children[2].children[0]);
185
+ }
186
+ if (window['chat_bot'].children[0].children.length > 1) {
187
+ window['chat_bot1'].children[1].textContent = window['chat_bot'].children[0].children[1].textContent;
188
+ } else {
189
+ window['chat_bot1'].children[1].textContent = '';
190
+ }
191
+ } else {
192
+ texts = window['gradioEl'].querySelectorAll('textarea');
193
+ text0 = texts[0];
194
+ text1 = texts[1];
195
+ img_index = 0;
196
+ text_value = text1.value;
197
+ if (window['doCheckPrompt'] === 0 && window['prevPrompt'] !== text_value) {
198
+ console.log('_____new prompt___[' + text_value + ']_');
199
+ window['doCheckPrompt'] = 1;
200
+ window['prevPrompt'] = text_value;
201
+
202
+ tabitems = window['gradioEl'].querySelectorAll('.tabitem');
203
+ for (var i = 0; i < tabitems.length; i++) {
204
+ inputText = tabitems[i].children[0].children[1].children[0].querySelectorAll('.gr-text-input')[0];
205
+ setNativeValue(inputText, text_value);
206
+ inputText.dispatchEvent(new Event('input', { bubbles: true }));
207
+ }
208
+ setTimeout(function() {
209
+ btns = window['gradioEl'].querySelectorAll('button');
210
+ for (var i = 0; i < btns.length; i++) {
211
+ if (['Generate image','Run'].includes(btns[i].innerText)) {
212
+ btns[i].click();
213
+ }
214
+ }
215
+ window['doCheckPrompt'] = 0;
216
+ }, 10);
217
+ }
218
+ tabitems = window['gradioEl'].querySelectorAll('.tabitem');
219
+ imgs = tabitems[img_index].children[0].children[1].children[1].querySelectorAll("img");
220
+ if (imgs.length > 0) {
221
+ if (window['prevImgSrc'] !== imgs[0].src) {
222
+ var user_div = document.createElement("div");
223
+ user_div.className = "px-3 py-2 rounded-[22px] rounded-br-none text-white text-sm chat-message svelte-rct66g";
224
+ user_div.style.backgroundColor = "#16a34a";
225
+ user_div.innerHTML = "<p>" + text0.value + "</p>";
226
+ window['chat_bot1'].children[2].children[0].appendChild(user_div);
227
+ var bot_div = document.createElement("div");
228
+ bot_div.className = "px-3 py-2 rounded-[22px] rounded-bl-none place-self-start text-white text-sm chat-message svelte-rct66g";
229
+ bot_div.style.backgroundColor = "#2563eb";
230
+ bot_div.style.width = "80%";
231
+ bot_div.style.padding = "0.2rem";
232
+ bot_div.appendChild(imgs[0].cloneNode(true));
233
+ window['chat_bot1'].children[2].children[0].appendChild(bot_div);
234
+
235
+ window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
236
+ window['prevImgSrc'] = imgs[0].src;
237
+ save_conversation(window['chat_bot1'].children[2].children[0]);
238
+ }
239
+ }
240
+ if (tabitems[img_index].children[0].children[1].children[1].children[0].children.length > 1) {
241
+ window['chat_bot1'].children[1].textContent = tabitems[img_index].children[0].children[1].children[1].children[0].textContent;
242
+ } else {
243
+ window['chat_bot1'].children[1].textContent = '';
244
+ }
245
+ }
246
+
247
+ } catch(e) {
248
+ }
249
+ }
250
+ window['checkChange_interval'] = window.setInterval("window.checkChange()", 500);
251
+ }
252
+
253
+ return false;
254
+ }"""
255
+
256
+ space_ids = {
257
+ "spaces/stabilityai/stable-diffusion":"Stable Diffusion 2.1",
258
+ # "spaces/runwayml/stable-diffusion-v1-5":"Stable Diffusion 1.5",
259
+ # "spaces/stabilityai/stable-diffusion-1":"Stable Diffusion 1.0",
260
+ }
261
+
262
+ tab_actions = []
263
+ tab_titles = []
264
+
265
+ for space_id in space_ids.keys():
266
+ print(space_id, space_ids[space_id])
267
+ try:
268
+ tab = gr.Interface.load(space_id)
269
+ tab_actions.append(tab)
270
+ tab_titles.append(space_ids[space_id])
271
+ except Exception as e:
272
+ logger.info(f"load_fail__{space_id}_{e}")
273
+
274
+ def chat(api, input0, input1, chat_radio, chat_history):
275
+ out_chat = []
276
+ if chat_history != '':
277
+ out_chat = json.loads(chat_history)
278
+ logger.info(f"out_chat_: {len(out_chat)} / {chat_radio}")
279
+ if chat_radio == "Talk to chatGPT":
280
+ response = get_response_from_chatgpt(api, input0)
281
+ # response = get_response_from_microsoft(input0)
282
+ # response = get_response_from_skywork(input0)
283
+ out_chat.append((input0, response))
284
+ chat_history = json.dumps(out_chat)
285
+ return api, out_chat, input1, chat_history
286
+ else:
287
+ prompt_en = getTextTrans(input0, source='zh', target='en') + f',{random.randint(0,sys.maxsize)}'
288
+ return api, out_chat, prompt_en, chat_history
289
+
290
+ with gr.Blocks(title='Talk to chatGPT') as demo:
291
+ gr.HTML("<p>You can duplicating this space and use your own session token: <a style='display:inline-block' href='https://huggingface.co/spaces/yizhangliu/chatGPT?duplicate=true'><img src='https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14' alt='Duplicate Space'></a></p>")
292
+ gr.HTML("<p> Instruction on how to get session token can be seen in video <a style='display:inline-block' href='https://www.youtube.com/watch?v=TdNSj_qgdFk'><font style='color:blue;weight:bold;'>here</font></a>. Add your session token by going to settings and add under secrets. </p>")
293
+ with gr.Group(elem_id="page_1", visible=True) as page_1:
294
+ with gr.Box():
295
+ with gr.Row():
296
+ start_button = gr.Button("Let's talk to chatGPT!", elem_id="start-btn", visible=True)
297
+ start_button.click(fn=None, inputs=[], outputs=[], _js=start_work)
298
+
299
+ with gr.Group(elem_id="page_2", visible=False) as page_2:
300
+ with gr.Row(elem_id="chat_row"):
301
+ chatbot = gr.Chatbot(elem_id="chat_bot", visible=False).style(color_map=("green", "blue"))
302
+ chatbot1 = gr.Chatbot(elem_id="chat_bot1").style(color_map=("green", "blue"))
303
+ with gr.Row(elem_id="prompt_row"):
304
+ prompt_input0 = gr.Textbox(lines=2, label="prompt",show_label=False)
305
+ prompt_input1 = gr.Textbox(lines=4, label="prompt", visible=False)
306
+ chat_history = gr.Textbox(lines=4, label="prompt", visible=False)
307
+ chat_radio = gr.Radio(["Talk to chatGPT", "Text to Image"], elem_id="chat_radio",value="Talk to chatGPT", show_label=False)
308
+ with gr.Row(elem_id="btns_row"):
309
+ with gr.Column(id="submit_col"):
310
+ submit_btn = gr.Button(value = "submit",elem_id="submit-btn").style(
311
+ margin=True,
312
+ rounded=(True, True, True, True),
313
+ width=100
314
+ )
315
+ with gr.Column(id="clear_col"):
316
+ clear_btn = gr.Button(value = "clear outputs", elem_id="clear-btn").style(
317
+ margin=True,
318
+ rounded=(True, True, True, True),
319
+ width=100
320
+ )
321
+ api = gr.State(value=get_api())
322
+ submit_btn.click(fn=chat,
323
+ inputs=[api, prompt_input0, prompt_input1, chat_radio, chat_history],
324
+ outputs=[api, chatbot, prompt_input1, chat_history],
325
+ )
326
+ with gr.Row(elem_id='tab_img', visible=False).style(height=5):
327
+ tab_img = gr.TabbedInterface(tab_actions, tab_titles)
328
+
329
+ demo.launch(debug = True)
330
+
baidu_translate/module.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import random
3
+ from hashlib import md5
4
+ from typing import Optional
5
+
6
+ import requests
7
+
8
+ import paddlehub as hub
9
+ from paddlehub.module.module import moduleinfo
10
+ from paddlehub.module.module import runnable
11
+ from paddlehub.module.module import serving
12
+
13
+
14
+ def make_md5(s, encoding='utf-8'):
15
+ return md5(s.encode(encoding)).hexdigest()
16
+
17
+
18
+ @moduleinfo(name="baidu_translate",
19
+ version="1.0.0",
20
+ type="text/machine_translation",
21
+ summary="",
22
+ author="baidu-nlp",
23
+ author_email="[email protected]")
24
+ class BaiduTranslate:
25
+
26
+ def __init__(self, appid=None, appkey=None):
27
+ """
28
+ :param appid: appid for requesting Baidu translation service.
29
+ :param appkey: appkey for requesting Baidu translation service.
30
+ """
31
+ # Set your own appid/appkey.
32
+ if appid == None:
33
+ self.appid = '20201015000580007'
34
+ else:
35
+ self.appid = appid
36
+ if appkey is None:
37
+ self.appkey = 'IFJB6jBORFuMmVGDRud1'
38
+ else:
39
+ self.appkey = appkey
40
+ self.url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
41
+
42
+ def translate(self, query: str, from_lang: Optional[str] = "en", to_lang: Optional[int] = "zh"):
43
+ """
44
+ Create image by text prompts using ErnieVilG model.
45
+
46
+ :param query: Text to be translated.
47
+ :param from_lang: Source language.
48
+ :param to_lang: Dst language.
49
+
50
+ Return translated string.
51
+ """
52
+ # Generate salt and sign
53
+ salt = random.randint(32768, 65536)
54
+ sign = make_md5(self.appid + query + str(salt) + self.appkey)
55
+
56
+ # Build request
57
+ headers = {'Content-Type': 'application/x-www-form-urlencoded'}
58
+ payload = {'appid': self.appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
59
+
60
+ # Send request
61
+ try:
62
+ r = requests.post(self.url, params=payload, headers=headers)
63
+ result = r.json()
64
+ except Exception as e:
65
+ error_msg = str(e)
66
+ raise RuntimeError(error_msg)
67
+ if 'error_code' in result:
68
+ raise RuntimeError(result['error_msg'])
69
+ return result['trans_result'][0]['dst']
70
+
71
+ @runnable
72
+ def run_cmd(self, argvs):
73
+ """
74
+ Run as a command.
75
+ """
76
+ self.parser = argparse.ArgumentParser(description="Run the {} module.".format(self.name),
77
+ prog='hub run {}'.format(self.name),
78
+ usage='%(prog)s',
79
+ add_help=True)
80
+ self.arg_input_group = self.parser.add_argument_group(title="Input options", description="Input data. Required")
81
+ self.add_module_input_arg()
82
+ args = self.parser.parse_args(argvs)
83
+ if args.appid is not None and args.appkey is not None:
84
+ self.appid = args.appid
85
+ self.appkey = args.appkey
86
+ result = self.translate(args.query, args.from_lang, args.to_lang)
87
+ return result
88
+
89
+ @serving
90
+ def serving_method(self, query, from_lang, to_lang):
91
+ """
92
+ Run as a service.
93
+ """
94
+ return self.translate(query, from_lang, to_lang)
95
+
96
+ def add_module_input_arg(self):
97
+ """
98
+ Add the command input options.
99
+ """
100
+ self.arg_input_group.add_argument('--query', type=str)
101
+ self.arg_input_group.add_argument('--from_lang', type=str, default='en', help="源语言")
102
+ self.arg_input_group.add_argument('--to_lang', type=str, default='zh', help="目标语言")
103
+ self.arg_input_group.add_argument('--appid', type=str, default=None, help="注册得到的个人appid")
104
+ self.arg_input_group.add_argument('--appkey', type=str, default=None, help="注册得到的个人appkey")
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pyChatGPT
2
+ loguru
3
+ paddlepaddle==2.3.2
4
+ paddlehub