vilarin commited on
Commit
352ea7e
·
verified ·
1 Parent(s): ad326f0

Update app/webui/app.py

Browse files
Files changed (1) hide show
  1. app/webui/app.py +277 -277
app/webui/app.py CHANGED
@@ -1,278 +1,278 @@
1
- import sys
2
- import os
3
-
4
- # Add the project root to the Python path
5
- project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
6
- sys.path.insert(0, project_root)
7
-
8
- import re
9
- import gradio as gr
10
- from glob import glob
11
- from app.webui.process import model_load, diff_texts, translator, translator_sec
12
- from llama_index.core import SimpleDirectoryReader
13
-
14
- def huanik(
15
- endpoint: str,
16
- model: str,
17
- api_key: str,
18
- choice: str,
19
- endpoint2: str,
20
- model2: str,
21
- api_key2: str,
22
- source_lang: str,
23
- target_lang: str,
24
- source_text: str,
25
- country: str,
26
- max_tokens: int,
27
- context_window: int,
28
- num_output: int,
29
- rpm: int,
30
- ):
31
-
32
- if not source_text or source_lang == target_lang:
33
- raise gr.Error("Please check that the content or options are entered correctly.")
34
-
35
- try:
36
- model_load(endpoint, model, api_key, context_window, num_output, rpm)
37
- except Exception as e:
38
- raise gr.Error(f"An unexpected error occurred: {e}")
39
-
40
- source_text = re.sub(r'(?m)^\s*$\n?', '', source_text)
41
-
42
- if choice:
43
- init_translation, reflect_translation, final_translation = translator_sec(
44
- endpoint2=endpoint2,
45
- model2=model2,
46
- api_key2=api_key2,
47
- context_window=context_window,
48
- num_output=num_output,
49
- source_lang=source_lang,
50
- target_lang=target_lang,
51
- source_text=source_text,
52
- country=country,
53
- max_tokens=max_tokens,
54
- )
55
-
56
- else:
57
- init_translation, reflect_translation, final_translation = translator(
58
- source_lang=source_lang,
59
- target_lang=target_lang,
60
- source_text=source_text,
61
- country=country,
62
- max_tokens=max_tokens,
63
- )
64
-
65
- final_diff = gr.HighlightedText(
66
- diff_texts(init_translation, final_translation),
67
- label="Diff translation",
68
- combine_adjacent=True,
69
- show_legend=True,
70
- visible=True,
71
- color_map={"removed": "red", "added": "green"})
72
-
73
- return init_translation, reflect_translation, final_translation, final_diff
74
-
75
- def update_model(endpoint):
76
- endpoint_model_map = {
77
- "Groq": "llama3-70b-8192",
78
- "OpenAI": "gpt-4o",
79
- "Cohere": "command-r",
80
- "TogetherAI": "Qwen/Qwen2-72B-Instruct",
81
- "Ollama": "llama3",
82
- "Huggingface": "mistralai/Mistral-7B-Instruct-v0.3"
83
- }
84
- return gr.update(value=endpoint_model_map[endpoint])
85
-
86
- def read_doc(file):
87
- docs = SimpleDirectoryReader(input_files=[file]).load_data()
88
- texts = ""
89
- for doc in docs:
90
- texts += doc.text
91
- texts = re.sub(r'(?m)^\s*$\n?', '', texts)
92
- return texts
93
-
94
- def enable_sec(choice):
95
- if choice:
96
- return gr.update(visible = True), gr.update(visible = True), gr.update(visible = True)
97
- else:
98
- return gr.update(visible = False), gr.update(visible = False), gr.update(visible = False)
99
-
100
- def update_menu(visible):
101
- return not visible, gr.update(visible=not visible)
102
-
103
- def export_txt(strings):
104
- os.makedirs("outputs", exist_ok=True)
105
- base_count = len(glob(os.path.join("outputs", "*.txt")))
106
- file_path = os.path.join("outputs", f"{base_count:06d}.txt")
107
- with open(file_path, "w", encoding="utf-8") as f:
108
- f.write(strings)
109
- return gr.update(value=file_path, visible=True)
110
-
111
- def switch(source_lang,source_text,target_lang,output_final):
112
- if output_final:
113
- return gr.update(value=target_lang), gr.update(value=output_final), gr.update(value=source_lang), gr.update(value=source_text)
114
- else:
115
- return gr.update(value=target_lang), gr.update(value=source_text), gr.update(value=source_lang), gr.update(value="")
116
-
117
- TITLE = """
118
- <div style="display: inline-flex;">
119
- <div style="margin-left: 6px; font-size:32px; color: #6366f1"><b>Translation Agent</b> WebUI</div>
120
- </div>
121
- """
122
-
123
- CSS = """
124
- h1 {
125
- text-align: center;
126
- display: block;
127
- height: 10vh;
128
- align-content: center;
129
- }
130
- footer {
131
- visibility: hidden;
132
- }
133
- .menu_btn {
134
- width: 48px;
135
- height: 48px;
136
- max-width: 48px;
137
- min-width: 48px;
138
- padding: 0px;
139
- background-color: transparent;
140
- border: none;
141
- cursor: pointer;
142
- position: relative;
143
- box-shadow: none;
144
- }
145
- .menu_btn::before,
146
- .menu_btn::after {
147
- content: '';
148
- position: absolute;
149
- width: 30px;
150
- height: 3px;
151
- background-color: #4f46e5;
152
- transition: transform 0.3s ease;
153
- }
154
- .menu_btn::before {
155
- top: 12px;
156
- box-shadow: 0 8px 0 #6366f1;
157
- }
158
- .menu_btn::after {
159
- bottom: 16px;
160
- }
161
- .menu_btn.active::before {
162
- transform: translateY(8px) rotate(45deg);
163
- box-shadow: none;
164
- }
165
- .menu_btn.active::after {
166
- transform: translateY(-8px) rotate(-45deg);
167
- }
168
- .lang {
169
- max-width: 100px;
170
- min-width: 100px;
171
- }
172
- """
173
-
174
- JS = """
175
- function () {
176
- const menuBtn = document.getElementById('menu');
177
- menuBtn.classList.toggle('active');
178
- }
179
-
180
- """
181
-
182
- with gr.Blocks(theme="soft", css=CSS, fill_height=True) as demo:
183
- with gr.Row():
184
- visible = gr.State(value=True)
185
- menuBtn = gr.Button(value="", elem_classes="menu_btn", elem_id="menu", size="sm")
186
- gr.HTML(TITLE)
187
- with gr.Row():
188
- with gr.Column(scale=1) as menubar:
189
- endpoint = gr.Dropdown(
190
- label="Endpoint",
191
- choices=["Groq","OpenAI","Cohere","TogetherAI","Ollama","Huggingface"],
192
- value="OpenAI",
193
- )
194
- choice = gr.Checkbox(label="Second Endpoint", info="Add second endpoint for reflection")
195
- model = gr.Textbox(label="Model", value="gpt-4o", )
196
- api_key = gr.Textbox(label="API_KEY", type="password", )
197
- endpoint2 = gr.Dropdown(
198
- label="Endpoint 2",
199
- choices=["Groq","OpenAI","Cohere","TogetherAI","Ollama","Huggingface"],
200
- value="OpenAI",
201
- visible=False,
202
- )
203
- model2 = gr.Textbox(label="Model 2", value="gpt-4o", visible=False,)
204
- api_key2 = gr.Textbox(label="API_KEY 2", type="password", visible=False,)
205
- with gr.Row():
206
- source_lang = gr.Textbox(
207
- label="Source Lang",
208
- value="English",
209
- elem_classes = "lang",
210
- )
211
- target_lang = gr.Textbox(
212
- label="Target Lang",
213
- value="Spanish",
214
- elem_classes = "lang",
215
- )
216
- switchBtn = gr.Button(value="🔄️")
217
- country = gr.Textbox(label="Country", value="Argentina", max_lines=1)
218
- with gr.Accordion("Advanced Options", open=False):
219
- max_tokens = gr.Slider(
220
- label="Max tokens Per Chunk",
221
- minimum=512,
222
- maximum=2046,
223
- value=1000,
224
- step=8,
225
- )
226
- context_window = gr.Slider(
227
- label="Context Window",
228
- minimum=512,
229
- maximum=8192,
230
- value=4096,
231
- step=8,
232
- )
233
- num_output = gr.Slider(
234
- label="Output Num",
235
- minimum=256,
236
- maximum=8192,
237
- value=512,
238
- step=8,
239
- )
240
- rpm = gr.Slider(
241
- label="Request Per Minute",
242
- minimum=1,
243
- maximum=1000,
244
- value=60,
245
- step=1,
246
- )
247
- with gr.Column(scale=4):
248
- source_text = gr.Textbox(
249
- label="Source Text",
250
- value="How we live is so different from how we ought to live that he who studies "+\
251
- "what ought to be done rather than what is done will learn the way to his downfall "+\
252
- "rather than to his preservation.",
253
- lines=12,
254
- )
255
- with gr.Tab("Final"):
256
- output_final = gr.Textbox(label="FInal Translation", lines=12, show_copy_button=True)
257
- with gr.Tab("Initial"):
258
- output_init = gr.Textbox(label="Init Translation", lines=12, show_copy_button=True)
259
- with gr.Tab("Reflection"):
260
- output_reflect = gr.Textbox(label="Reflection", lines=12, show_copy_button=True)
261
- with gr.Tab("Diff"):
262
- output_diff = gr.HighlightedText(visible = False)
263
- with gr.Row():
264
- submit = gr.Button(value="Translate")
265
- upload = gr.UploadButton(label="Upload", file_types=["text"])
266
- export = gr.DownloadButton(visible=False)
267
- clear = gr.ClearButton([source_text, output_init, output_reflect, output_final])
268
-
269
- switchBtn.click(fn=switch, inputs=[source_lang,source_text,target_lang,output_final], outputs=[source_lang,source_text,target_lang,output_final])
270
- menuBtn.click(fn=update_menu, inputs=visible, outputs=[visible, menubar], js=JS)
271
- endpoint.change(fn=update_model, inputs=[endpoint], outputs=[model])
272
- choice.select(fn=enable_sec, inputs=[choice], outputs=[endpoint2, model2, api_key2])
273
- endpoint2.change(fn=update_model, inputs=[endpoint2], outputs=[model2])
274
- submit.click(fn=huanik, inputs=[endpoint, model, api_key, choice, endpoint2, model2, api_key2, source_lang, target_lang, source_text, country, max_tokens, context_window, num_output, rpm], outputs=[output_init, output_reflect, output_final, output_diff])
275
- upload.upload(fn=read_doc, inputs = upload, outputs = source_text)
276
- output_final.change(fn=export_txt, inputs=output_final, outputs=[export])
277
- if __name__ == "__main__":
278
  demo.queue(api_open=False).launch(show_api=False, share=False)
 
1
+ import sys
2
+ import os
3
+
4
+ # Add the project root to the Python path
5
+ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
6
+ sys.path.insert(0, project_root)
7
+
8
+ import re
9
+ import gradio as gr
10
+ from glob import glob
11
+ from app.webui.process import model_load, diff_texts, translator, translator_sec
12
+ from llama_index.core import SimpleDirectoryReader
13
+
14
+ def huanik(
15
+ endpoint: str,
16
+ model: str,
17
+ api_key: str,
18
+ choice: str,
19
+ endpoint2: str,
20
+ model2: str,
21
+ api_key2: str,
22
+ source_lang: str,
23
+ target_lang: str,
24
+ source_text: str,
25
+ country: str,
26
+ max_tokens: int,
27
+ context_window: int,
28
+ num_output: int,
29
+ rpm: int,
30
+ ):
31
+
32
+ if not source_text or source_lang == target_lang:
33
+ raise gr.Error("Please check that the content or options are entered correctly.")
34
+
35
+ try:
36
+ model_load(endpoint, model, api_key, context_window, num_output, rpm)
37
+ except Exception as e:
38
+ raise gr.Error(f"An unexpected error occurred: {e}")
39
+
40
+ source_text = re.sub(r'(?m)^\s*$\n?', '', source_text)
41
+
42
+ if choice:
43
+ init_translation, reflect_translation, final_translation = translator_sec(
44
+ endpoint2=endpoint2,
45
+ model2=model2,
46
+ api_key2=api_key2,
47
+ context_window=context_window,
48
+ num_output=num_output,
49
+ source_lang=source_lang,
50
+ target_lang=target_lang,
51
+ source_text=source_text,
52
+ country=country,
53
+ max_tokens=max_tokens,
54
+ )
55
+
56
+ else:
57
+ init_translation, reflect_translation, final_translation = translator(
58
+ source_lang=source_lang,
59
+ target_lang=target_lang,
60
+ source_text=source_text,
61
+ country=country,
62
+ max_tokens=max_tokens,
63
+ )
64
+
65
+ final_diff = gr.HighlightedText(
66
+ diff_texts(init_translation, final_translation),
67
+ label="Diff translation",
68
+ combine_adjacent=True,
69
+ show_legend=True,
70
+ visible=True,
71
+ color_map={"removed": "red", "added": "green"})
72
+
73
+ return init_translation, reflect_translation, final_translation, final_diff
74
+
75
+ def update_model(endpoint):
76
+ endpoint_model_map = {
77
+ "Groq": "llama3-70b-8192",
78
+ "OpenAI": "gpt-4o",
79
+ "Cohere": "command-r",
80
+ "TogetherAI": "Qwen/Qwen2-72B-Instruct",
81
+ "Ollama": "llama3",
82
+ "Huggingface": "mistralai/Mistral-7B-Instruct-v0.3"
83
+ }
84
+ return gr.update(value=endpoint_model_map[endpoint])
85
+
86
+ def read_doc(file):
87
+ docs = SimpleDirectoryReader(input_files=[file]).load_data()
88
+ texts = ""
89
+ for doc in docs:
90
+ texts += doc.text
91
+ texts = re.sub(r'(?m)^\s*$\n?', '', texts)
92
+ return texts
93
+
94
+ def enable_sec(choice):
95
+ if choice:
96
+ return gr.update(visible = True), gr.update(visible = True), gr.update(visible = True)
97
+ else:
98
+ return gr.update(visible = False), gr.update(visible = False), gr.update(visible = False)
99
+
100
+ def update_menu(visible):
101
+ return not visible, gr.update(visible=not visible)
102
+
103
+ def export_txt(strings):
104
+ os.makedirs("outputs", exist_ok=True)
105
+ base_count = len(glob(os.path.join("outputs", "*.txt")))
106
+ file_path = os.path.join("outputs", f"{base_count:06d}.txt")
107
+ with open(file_path, "w", encoding="utf-8") as f:
108
+ f.write(strings)
109
+ return gr.update(value=file_path, visible=True)
110
+
111
+ def switch(source_lang,source_text,target_lang,output_final):
112
+ if output_final:
113
+ return gr.update(value=target_lang), gr.update(value=output_final), gr.update(value=source_lang), gr.update(value=source_text)
114
+ else:
115
+ return gr.update(value=target_lang), gr.update(value=source_text), gr.update(value=source_lang), gr.update(value="")
116
+
117
+ TITLE = """
118
+ <div style="display: inline-flex;">
119
+ <div style="margin-left: 6px; font-size:32px; color: #6366f1"><b>Translation Agent</b> WebUI</div>
120
+ </div>
121
+ """
122
+
123
+ CSS = """
124
+ h1 {
125
+ text-align: center;
126
+ display: block;
127
+ height: 10vh;
128
+ align-content: center;
129
+ }
130
+ footer {
131
+ visibility: hidden;
132
+ }
133
+ .menu_btn {
134
+ width: 48px;
135
+ height: 48px;
136
+ max-width: 48px;
137
+ min-width: 48px;
138
+ padding: 0px;
139
+ background-color: transparent;
140
+ border: none;
141
+ cursor: pointer;
142
+ position: relative;
143
+ box-shadow: none;
144
+ }
145
+ .menu_btn::before,
146
+ .menu_btn::after {
147
+ content: '';
148
+ position: absolute;
149
+ width: 30px;
150
+ height: 3px;
151
+ background-color: #4f46e5;
152
+ transition: transform 0.3s ease;
153
+ }
154
+ .menu_btn::before {
155
+ top: 12px;
156
+ box-shadow: 0 8px 0 #6366f1;
157
+ }
158
+ .menu_btn::after {
159
+ bottom: 16px;
160
+ }
161
+ .menu_btn.active::before {
162
+ transform: translateY(8px) rotate(45deg);
163
+ box-shadow: none;
164
+ }
165
+ .menu_btn.active::after {
166
+ transform: translateY(-8px) rotate(-45deg);
167
+ }
168
+ .lang {
169
+ max-width: 100px;
170
+ min-width: 100px;
171
+ }
172
+ """
173
+
174
+ JS = """
175
+ function () {
176
+ const menuBtn = document.getElementById('menu');
177
+ menuBtn.classList.toggle('active');
178
+ }
179
+
180
+ """
181
+
182
+ with gr.Blocks(theme="soft", css=CSS, fill_height=True) as demo:
183
+ with gr.Row():
184
+ visible = gr.State(value=True)
185
+ menuBtn = gr.Button(value="", elem_classes="menu_btn", elem_id="menu", size="sm")
186
+ gr.HTML(TITLE)
187
+ with gr.Row():
188
+ with gr.Column(scale=1) as menubar:
189
+ endpoint = gr.Dropdown(
190
+ label="Endpoint",
191
+ choices=["Groq","OpenAI","Cohere","TogetherAI","Ollama","Huggingface"],
192
+ value="Huggingface",
193
+ )
194
+ choice = gr.Checkbox(label="Second Endpoint", info="Add second endpoint for reflection")
195
+ model = gr.Textbox(label="Model", value="mistralai/Mistral-7B-Instruct-v0.3",)
196
+ api_key = gr.Textbox(label="API_KEY", type="password", )
197
+ endpoint2 = gr.Dropdown(
198
+ label="Endpoint 2",
199
+ choices=["Groq","OpenAI","Cohere","TogetherAI","Ollama","Huggingface"],
200
+ value="Groq",
201
+ visible=False,
202
+ )
203
+ model2 = gr.Textbox(label="Model 2", value="llama3-70b-8192", visible=False,)
204
+ api_key2 = gr.Textbox(label="API_KEY 2", type="password", visible=False,)
205
+ with gr.Row():
206
+ source_lang = gr.Textbox(
207
+ label="Source Lang",
208
+ value="English",
209
+ elem_classes = "lang",
210
+ )
211
+ target_lang = gr.Textbox(
212
+ label="Target Lang",
213
+ value="Spanish",
214
+ elem_classes = "lang",
215
+ )
216
+ switchBtn = gr.Button(value="🔄️")
217
+ country = gr.Textbox(label="Country", value="Argentina", max_lines=1)
218
+ with gr.Accordion("Advanced Options", open=False):
219
+ max_tokens = gr.Slider(
220
+ label="Max tokens Per Chunk",
221
+ minimum=512,
222
+ maximum=2046,
223
+ value=1000,
224
+ step=8,
225
+ )
226
+ context_window = gr.Slider(
227
+ label="Context Window",
228
+ minimum=512,
229
+ maximum=8192,
230
+ value=4096,
231
+ step=8,
232
+ )
233
+ num_output = gr.Slider(
234
+ label="Output Num",
235
+ minimum=256,
236
+ maximum=8192,
237
+ value=512,
238
+ step=8,
239
+ )
240
+ rpm = gr.Slider(
241
+ label="Request Per Minute",
242
+ minimum=1,
243
+ maximum=1000,
244
+ value=60,
245
+ step=1,
246
+ )
247
+ with gr.Column(scale=4):
248
+ source_text = gr.Textbox(
249
+ label="Source Text",
250
+ value="How we live is so different from how we ought to live that he who studies "+\
251
+ "what ought to be done rather than what is done will learn the way to his downfall "+\
252
+ "rather than to his preservation.",
253
+ lines=12,
254
+ )
255
+ with gr.Tab("Final"):
256
+ output_final = gr.Textbox(label="FInal Translation", lines=12, show_copy_button=True)
257
+ with gr.Tab("Initial"):
258
+ output_init = gr.Textbox(label="Init Translation", lines=12, show_copy_button=True)
259
+ with gr.Tab("Reflection"):
260
+ output_reflect = gr.Textbox(label="Reflection", lines=12, show_copy_button=True)
261
+ with gr.Tab("Diff"):
262
+ output_diff = gr.HighlightedText(visible = False)
263
+ with gr.Row():
264
+ submit = gr.Button(value="Translate")
265
+ upload = gr.UploadButton(label="Upload", file_types=["text"])
266
+ export = gr.DownloadButton(visible=False)
267
+ clear = gr.ClearButton([source_text, output_init, output_reflect, output_final])
268
+
269
+ switchBtn.click(fn=switch, inputs=[source_lang,source_text,target_lang,output_final], outputs=[source_lang,source_text,target_lang,output_final])
270
+ menuBtn.click(fn=update_menu, inputs=visible, outputs=[visible, menubar], js=JS)
271
+ endpoint.change(fn=update_model, inputs=[endpoint], outputs=[model])
272
+ choice.select(fn=enable_sec, inputs=[choice], outputs=[endpoint2, model2, api_key2])
273
+ endpoint2.change(fn=update_model, inputs=[endpoint2], outputs=[model2])
274
+ submit.click(fn=huanik, inputs=[endpoint, model, api_key, choice, endpoint2, model2, api_key2, source_lang, target_lang, source_text, country, max_tokens, context_window, num_output, rpm], outputs=[output_init, output_reflect, output_final, output_diff])
275
+ upload.upload(fn=read_doc, inputs = upload, outputs = source_text)
276
+ output_final.change(fn=export_txt, inputs=output_final, outputs=[export])
277
+ if __name__ == "__main__":
278
  demo.queue(api_open=False).launch(show_api=False, share=False)