basantyahya commited on
Commit
906213a
·
verified ·
1 Parent(s): 0a5e547

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -212
app.py CHANGED
@@ -2,254 +2,124 @@ import os
2
  import openai
3
  import gradio as gr
4
 
5
- openai.api_key = os.environ['OPENAI_KEY']
 
6
 
 
7
  supportLanguages = [
8
  ["auto", "auto"],
9
- ["粤语", "yue"],
10
- ["古文", "wyw"],
11
- ["af","Afrikaans"],
12
- ["ak","Akan"],
13
- ["sq","Albanian"],
14
- ["am","Amharic"],
15
- ["ar","Arabic"],
16
- ["hy","Armenian"],
17
- ["az","Azerbaijani"],
18
- ["eu","Basque"],
19
- ["be","Belarusian"],
20
- ["bem","Bemba"],
21
- ["bn","Bengali"],
22
- ["bh","Bihari"],
23
- ["xx-bork","Bork, bork, bork!"],
24
- ["bs","Bosnian"],
25
- ["br","Breton"],
26
- ["bg","Bulgarian"],
27
- ["km","Cambodian"],
28
- ["ca","Catalan"],
29
- ["chr","Cherokee"],
30
- ["ny","Chichewa"],
31
- ["zh-CN","Chinese (Simplified)"],
32
- ["zh-TW","Chinese (Traditional)"],
33
- ["co","Corsican"],
34
- ["hr","Croatian"],
35
- ["cs","Czech"],
36
- ["da","Danish"],
37
- ["nl","Dutch"],
38
- ["xx-elmer","Elmer Fudd"],
39
- ["en","English"],
40
- ["eo","Esperanto"],
41
- ["et","Estonian"],
42
- ["ee","Ewe"],
43
- ["fo","Faroese"],
44
- ["tl","Filipino"],
45
- ["fi","Finnish"],
46
- ["fr","French"],
47
- ["fy","Frisian"],
48
- ["gaa","Ga"],
49
- ["gl","Galician"],
50
- ["ka","Georgian"],
51
- ["de","German"],
52
- ["el","Greek"],
53
- ["gn","Guarani"],
54
- ["gu","Gujarati"],
55
- ["xx-hacker","Hacker"],
56
- ["ht","Haitian Creole"],
57
- ["ha","Hausa"],
58
- ["haw","Hawaiian"],
59
- ["iw","Hebrew"],
60
- ["hi","Hindi"],
61
- ["hu","Hungarian"],
62
- ["is","Icelandic"],
63
- ["ig","Igbo"],
64
- ["id","Indonesian"],
65
- ["ia","Interlingua"],
66
- ["ga","Irish"],
67
- ["it","Italian"],
68
- ["ja","Japanese"],
69
- ["jw","Javanese"],
70
- ["kn","Kannada"],
71
- ["kk","Kazakh"],
72
- ["rw","Kinyarwanda"],
73
- ["rn","Kirundi"],
74
- ["xx-klingon","Klingon"],
75
- ["kg","Kongo"],
76
- ["ko","Korean"],
77
- ["kri","Krio (Sierra Leone)"],
78
- ["ku","Kurdish"],
79
- ["ckb","Kurdish (Soranî)"],
80
- ["ky","Kyrgyz"],
81
- ["lo","Laothian"],
82
- ["la","Latin"],
83
- ["lv","Latvian"],
84
- ["ln","Lingala"],
85
- ["lt","Lithuanian"],
86
- ["loz","Lozi"],
87
- ["lg","Luganda"],
88
- ["ach","Luo"],
89
- ["mk","Macedonian"],
90
- ["mg","Malagasy"],
91
- ["ms","Malay"],
92
- ["ml","Malayalam"],
93
- ["mt","Maltese"],
94
- ["mi","Maori"],
95
- ["mr","Marathi"],
96
- ["mfe","Mauritian Creole"],
97
- ["mo","Moldavian"],
98
- ["mn","Mongolian"],
99
- ["sr-ME","Montenegrin"],
100
- ["ne","Nepali"],
101
- ["pcm","Nigerian Pidgin"],
102
- ["nso","Northern Sotho"],
103
- ["no","Norwegian"],
104
- ["nn","Norwegian (Nynorsk)"],
105
- ["oc","Occitan"],
106
- ["or","Oriya"],
107
- ["om","Oromo"],
108
- ["ps","Pashto"],
109
- ["fa","Persian"],
110
- ["xx-pirate","Pirate"],
111
- ["pl","Polish"],
112
- ["pt-BR","Portuguese (Brazil)"],
113
- ["pt-PT","Portuguese (Portugal)"],
114
- ["pa","Punjabi"],
115
- ["qu","Quechua"],
116
- ["ro","Romanian"],
117
- ["rm","Romansh"],
118
- ["nyn","Runyakitara"],
119
- ["ru","Russian"],
120
- ["gd","Scots Gaelic"],
121
- ["sr","Serbian"],
122
- ["sh","Serbo-Croatian"],
123
- ["st","Sesotho"],
124
- ["tn","Setswana"],
125
- ["crs","Seychellois Creole"],
126
- ["sn","Shona"],
127
- ["sd","Sindhi"],
128
- ["si","Sinhalese"],
129
- ["sk","Slovak"],
130
- ["sl","Slovenian"],
131
- ["so","Somali"],
132
- ["es","Spanish"],
133
- ["es-419","Spanish (Latin American)"],
134
- ["su","Sundanese"],
135
- ["sw","Swahili"],
136
- ["sv","Swedish"],
137
- ["tg","Tajik"],
138
- ["ta","Tamil"],
139
- ["tt","Tatar"],
140
- ["te","Telugu"],
141
- ["th","Thai"],
142
- ["ti","Tigrinya"],
143
- ["to","Tonga"],
144
- ["lua","Tshiluba"],
145
- ["tum","Tumbuka"],
146
- ["tr","Turkish"],
147
- ["tk","Turkmen"],
148
- ["tw","Twi"],
149
- ["ug","Uighur"],
150
- ["uk","Ukrainian"],
151
- ["ur","Urdu"],
152
- ["uz","Uzbek"],
153
- ["vi","Vietnamese"],
154
- ["cy","Welsh"],
155
- ["wo","Wolof"],
156
- ["xh","Xhosa"],
157
- ["yi","Yiddish"],
158
- ["yo","Yoruba"],
159
- ["zu","Zulu"],
160
  ]
161
- prompt_template = "You are a translation engine that can only translate text and cannot interpret it. Keep the indent of the original text, only modify when you need."
162
 
 
 
 
 
 
 
163
  def submit_message(detectFrom, detectTo, user_token, prompt):
164
- if user_token != "":
165
  openai.api_key = user_token
166
 
167
  if not prompt:
168
- return gr.update(value="")
169
-
170
- for lc, lang in supportLanguages:
171
- if detectFrom == lang:
172
- detectFrom = lc
173
- if detectTo == lang:
174
- detectTo = lc
 
175
 
176
  systemInstruct = prompt_template
177
  translateInstruct = f"translate from {detectFrom} to {detectTo}"
 
178
  if detectFrom == "auto":
179
  translateInstruct = f"translate to {detectTo}"
180
- if detectFrom in ["古文", "zh-CN", "zh-TW"]:
181
- if detectTo == "zh-TW":
182
- translateInstruct = "翻译成繁体白话文"
183
- if detectTo == "zh-CN":
184
- translateInstruct = "翻译成简体白话文"
185
- if detectTo == "粤语":
186
- translateInstruct = "翻译成粤语白话文"
187
 
188
  if detectFrom == detectTo:
189
- systemInstruct = "You are a text embellisher, you can only embellish the text, don't interpret it."
190
- if detectTo in ["zh-CN", "zh-TW"]:
191
- translateInstruct = "润色此句"
192
- else:
193
- translateInstruct = "polish this sentence"
194
 
195
- prompt_msg = [
196
  {"role": "system", "content": systemInstruct},
197
  {"role": "user", "content": translateInstruct},
198
  {"role": "user", "content": prompt},
199
  ]
200
 
201
  try:
202
- openai_response = openai.ChatCompletion.create(
203
  model="gpt-3.5-turbo",
204
- messages=prompt_msg,
205
  temperature=0,
206
  max_tokens=1000,
207
- top_p=1,
208
- stream=True,
209
- frequency_penalty=1,
210
- presence_penalty=1,
211
  )
212
-
213
- combined = ""
214
- for resp in openai_response:
215
- delta = resp["choices"][0]["delta"]
216
- if "content" in delta:
217
- combined += delta["content"]
218
- yield combined
219
 
220
  except Exception as e:
221
  return f"Error: {e}"
222
 
 
223
  css = """
224
- #col-container {max-width: 80%; margin-left: auto; margin-right: auto;}
225
- #chatbox {min-height: 400px;}
226
- #header {text-align: center;}
227
- #label {font-size: 0.8em; padding: 0.5em; margin: 0;}
228
- .message { font-size: 1.2em; }
229
- """
230
-
231
- with gr.Blocks(css=css) as demo:
232
-
233
- state = gr.State([])
234
 
 
 
235
  with gr.Column(elem_id="col-container"):
236
- gr.Markdown("""## OpenAI Translator
237
- Using the official API (gpt-3.5-turbo model).""", elem_id="header")
238
 
239
  with gr.Row():
240
- with gr.Column():
241
- translateFrom = gr.Dropdown(label="Translate From", elem_id="translate-from", multiselect=False, value="auto", choices=[l[1] for l in supportLanguages]).style(container=False)
242
- input_message = gr.Textbox(max_lines=100, show_label=False, lines=10, placeholder="Enter text and press enter", visible=True).style(container=False)
243
- with gr.Column():
244
- translateTo = gr.Dropdown(label="Translate To", elem_id="translate-to", multiselect=False, value="Chinese (Simplified)", choices=[l[1] for l in supportLanguages[1:]]).style(container=False)
245
- output = gr.Textbox(max_lines=100, show_label=False, lines=10, label="Output", visible=True).style(container=False)
246
-
247
- btn_submit = gr.Button("Translate")
 
 
 
 
 
 
 
 
 
 
 
248
 
249
- with gr.Row():
250
- user_token = gr.Textbox(value='', placeholder="OpenAI API Key", type="password", label="Enter your OpenAI API Key. Leave blank to use default key.")
 
 
 
 
 
 
 
 
251
 
252
- btn_submit.click(submit_message, [translateFrom, translateTo, user_token, input_message], [output])
 
 
 
 
 
 
253
 
254
- demo.queue(concurrency_count=10)
255
- demo.launch(height='800px')
 
 
2
  import openai
3
  import gradio as gr
4
 
5
+ # -------- OpenAI Key --------
6
+ openai.api_key = os.environ.get("OPENAI_KEY", "")
7
 
8
+ # -------- Supported Languages --------
9
  supportLanguages = [
10
  ["auto", "auto"],
11
+ ["ar", "Arabic"],
12
+ ["en", "English"],
13
+ ["fr", "French"],
14
+ ["de", "German"],
15
+ ["es", "Spanish"],
16
+ ["it", "Italian"],
17
+ ["pt", "Portuguese"],
18
+ ["zh-CN", "Chinese (Simplified)"],
19
+ ["zh-TW", "Chinese (Traditional)"],
20
+ ["ja", "Japanese"],
21
+ ["ko", "Korean"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  ]
 
23
 
24
+ prompt_template = (
25
+ "You are a translation engine that can only translate text "
26
+ "and cannot interpret it. Keep the indent of the original text."
27
+ )
28
+
29
+ # -------- Translation Function --------
30
  def submit_message(detectFrom, detectTo, user_token, prompt):
31
+ if user_token:
32
  openai.api_key = user_token
33
 
34
  if not prompt:
35
+ return ""
36
+
37
+ # map language name -> code
38
+ for code, name in supportLanguages:
39
+ if detectFrom == name:
40
+ detectFrom = code
41
+ if detectTo == name:
42
+ detectTo = code
43
 
44
  systemInstruct = prompt_template
45
  translateInstruct = f"translate from {detectFrom} to {detectTo}"
46
+
47
  if detectFrom == "auto":
48
  translateInstruct = f"translate to {detectTo}"
 
 
 
 
 
 
 
49
 
50
  if detectFrom == detectTo:
51
+ systemInstruct = "You are a text embellisher."
52
+ translateInstruct = "polish this sentence"
 
 
 
53
 
54
+ messages = [
55
  {"role": "system", "content": systemInstruct},
56
  {"role": "user", "content": translateInstruct},
57
  {"role": "user", "content": prompt},
58
  ]
59
 
60
  try:
61
+ response = openai.ChatCompletion.create(
62
  model="gpt-3.5-turbo",
63
+ messages=messages,
64
  temperature=0,
65
  max_tokens=1000,
 
 
 
 
66
  )
67
+ return response["choices"][0]["message"]["content"]
 
 
 
 
 
 
68
 
69
  except Exception as e:
70
  return f"Error: {e}"
71
 
72
+ # -------- CSS --------
73
  css = """
74
+ #col-container { max-width: 80%; margin: auto; }
75
+ #header { text-align: center; }
76
+ """
 
 
 
 
 
 
 
77
 
78
+ # -------- Gradio UI --------
79
+ with gr.Blocks() as demo:
80
  with gr.Column(elem_id="col-container"):
81
+ gr.Markdown("## 🌍 OpenAI Translator", elem_id="header")
 
82
 
83
  with gr.Row():
84
+ translateFrom = gr.Dropdown(
85
+ label="Translate From",
86
+ value="auto",
87
+ choices=[l[1] for l in supportLanguages],
88
+ scale=1,
89
+ )
90
+
91
+ translateTo = gr.Dropdown(
92
+ label="Translate To",
93
+ value="English",
94
+ choices=[l[1] for l in supportLanguages if l[0] != "auto"],
95
+ scale=1,
96
+ )
97
+
98
+ input_message = gr.Textbox(
99
+ lines=8,
100
+ placeholder="Enter text here...",
101
+ label="Input",
102
+ )
103
 
104
+ output = gr.Textbox(
105
+ lines=8,
106
+ label="Translation",
107
+ )
108
+
109
+ user_token = gr.Textbox(
110
+ placeholder="Optional: OpenAI API Key",
111
+ type="password",
112
+ label="API Key",
113
+ )
114
 
115
+ btn_submit = gr.Button("Translate")
116
+
117
+ btn_submit.click(
118
+ submit_message,
119
+ inputs=[translateFrom, translateTo, user_token, input_message],
120
+ outputs=output,
121
+ )
122
 
123
+ # -------- Launch --------
124
+ demo.queue(concurrency_count=5)
125
+ demo.launch(css=css, height="800px")