-
Notifications
You must be signed in to change notification settings - Fork 4
/
webgui.py
2218 lines (1664 loc) · 142 KB
/
webgui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## built-in libraries
import typing
import base64
import asyncio
import time
import os
import json
## third-party libraries
import gradio as gr
from kairyou import Indexer
from kairyou import Kairyou
from kairyou import InvalidReplacementJsonKeys
from kairyou.util import _validate_replacement_json
from easytl import EasyTL, ALLOWED_GEMINI_MODELS, ALLOWED_OPENAI_MODELS
## custom modules
from modules.common.toolkit import Toolkit
from modules.common.file_ensurer import FileEnsurer
from modules.gui.gui_file_util import gui_get_text_from_file, gui_get_json_from_file
from modules.gui.gui_json_util import GuiJsonUtil
from handlers.json_handler import JsonHandler
from modules.common.translator import Translator
from kudasai import Kudasai
##-------------------start-of-KudasaiGUI---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
class KudasaiGUI:
"""
KudasaiGUI is a class that contains the GUI for Kudasai.
"""
## scary javascript code that allows us to save textbox contents to a file
with open(FileEnsurer.js_save_to_file_path, 'r', encoding='utf-8') as f:
js_save_to_file = f.read()
with open(FileEnsurer.js_save_to_zip_path, 'r', encoding='utf-8') as f:
js_save_to_zip = f.read()
## used for whether the debug log tab for Translator should be actively refreshing based of Logger.current_batch
is_translation_ongoing = False
with open(FileEnsurer.translation_settings_description_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
description_dict = {
"prompt_assembly_mode": lines[4-1].strip(),
"number_of_lines_per_batch": lines[6-1].strip(),
"sentence_fragmenter_mode": lines[8-1].strip(),
"je_check_mode": lines[10-1].strip(),
"number_of_malformed_batch_retries": lines[12-1].strip(),
"batch_retry_timeout": lines[14-1].strip(),
"number_of_concurrent_batches": lines[16-1].strip(),
"gender_context_insertion": lines[18-1].strip(),
"is_cote": lines[20-1].strip(),
"openai_help_link": lines[23-1].strip(),
"openai_model": lines[25-1].strip(),
"openai_system_message": lines[27-1].strip(),
"openai_temperature": lines[29-1].strip(),
"openai_top_p": lines[31-1].strip(),
"openai_n": lines[33-1].strip(),
"openai_stream": lines[35-1].strip(),
"openai_stop": lines[37-1].strip(),
"openai_logit_bias": lines[39-1].strip(),
"openai_max_tokens": lines[41-1].strip(),
"openai_presence_penalty": lines[43-1].strip(),
"openai_frequency_penalty": lines[45-1].strip(),
"openai_disclaimer": lines[47-1].strip(),
"gemini_help_link": lines[50-1].strip(),
"gemini_model": lines[52-1].strip(),
"gemini_prompt": lines[54-1].strip(),
"gemini_temperature": lines[56-1].strip(),
"gemini_top_p": lines[58-1].strip(),
"gemini_top_k": lines[60-1].strip(),
"gemini_candidate_count": lines[62-1].strip(),
"gemini_stream": lines[64-1].strip(),
"gemini_stop_sequences": lines[66-1].strip(),
"gemini_max_output_tokens": lines[68-1].strip(),
"gemini_disclaimer": lines[70-1].strip(),
"deepl_help_link": lines[73-1].strip(),
"deepl_context": lines[75-1].strip(),
"deepl_split_sentences": lines[77-1].strip(),
"deepl_preserve_formatting": lines[79-1].strip(),
"deepl_formality": lines[81-1].strip(),
}
last_text_change = 0
debounce_delay = 2 ## 2 seconds
##-------------------start-of-build_gui()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def build_gui(self) -> None:
"""
Builds the GUI.
"""
with gr.Blocks(title="Kudasai", delete_cache=(300, 300), analytics_enabled=False) as self.gui:
##-------------------start-of-Utility-Functions---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
##-------------------start-of-fetch_log_content()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def fetch_log_content() -> str:
"""
Fetches the log content from the current log batch.
Returns:
log_text (str) : The log text.
"""
if(self.is_translation_ongoing == False):
return "No translation ongoing"
with open(FileEnsurer.debug_log_path, 'r', encoding='utf-8') as f:
log_text = f.read()
return log_text
##-------------------start-of-get_saved_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@staticmethod
def get_saved_api_key(service_name:typing.Literal["openai","gemini","deepl","google translate"]) -> str:
"""
Gets the saved api key from the config folder, if it exists.
Parameters:
service_name (str): The name of the service (e.g., "deepl", "openai", "gemini").
Returns:
api_key (str) : The api key.
"""
if(FileEnsurer.is_hugging_space()):
return ""
service_to_path = {
"openai": FileEnsurer.openai_api_key_path,
"gemini": FileEnsurer.gemini_api_key_path,
"deepl": FileEnsurer.deepl_api_key_path,
"google_translate": FileEnsurer.google_translate_service_key_json_path
}
api_key_path = service_to_path.get(service_name, "")
try:
if(service_name == "google translate"):
return api_key_path
## Api key is encoded in base 64 so we need to decode it before returning
return base64.b64decode(FileEnsurer.standard_read_file(api_key_path).encode('utf-8')).decode('utf-8')
except:
return ""
##-------------------start-of-set_translator_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
async def set_translator_api_key(api_key) -> None:
"""
Sets the translator api key.
Parameters:
api_key (str) : The api key.
"""
## ik this looks really bad
## but the set_credentials for google translate expects a filepath, and normal way isn't working
## so we write the client secrets to a temp file, send that, then clear the file
## even if it fails, purge_storage is set to kill that path too so we should be good.
if(Translator.TRANSLATION_METHOD == "google translate"):
FileEnsurer.standard_overwrite_file(FileEnsurer.temp_file_path, str(api_key), omit=True)
await asyncio.sleep(1)
api_key = FileEnsurer.temp_file_path
try:
EasyTL.set_credentials(Translator.TRANSLATION_METHOD, str(api_key))
is_valid, e = EasyTL.test_credentials(Translator.TRANSLATION_METHOD)
if(is_valid == False and e is not None):
raise e
except:
raise gr.Error("Invalid API key")
finally:
try:
os.remove(FileEnsurer.temp_file_path)
except:
pass
##-------------------start-of-update_translator_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def update_translator_api_key(api_key) -> None:
"""
Updates the translator api key.
Parameters:
api_key (str) : The api key.
"""
if(FileEnsurer.is_hugging_space()):
return
method_to_path = {
"openai": FileEnsurer.openai_api_key_path,
"gemini": FileEnsurer.gemini_api_key_path,
"deepl": FileEnsurer.deepl_api_key_path,
"google translate": FileEnsurer.google_translate_service_key_json_path
}
path_to_api_key = method_to_path.get(Translator.TRANSLATION_METHOD, None)
assert path_to_api_key is not None, "Invalid translation method"
if(Translator.TRANSLATION_METHOD != "google translate"):
api_key = base64.b64encode(str(api_key).encode('utf-8')).decode('utf-8')
FileEnsurer.standard_overwrite_file(path_to_api_key, str(api_key), omit=True)
##-------------------start-of-create_new_key_value_tuple_pairs()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def create_new_key_value_tuple_pairs(translation_settings:typing.List[str]) -> typing.List[typing.Tuple[str, str]]:
"""
Applies the new translation to the uploaded translation_settings.json file.
Parameters:
translation_settings (typing.List[typing.Union[gr.Textbox,gr.Slider,gr.Dropdown]]) : The translation settings.
Returns:
key_value_tuple_pairs (typing.List[typing.Tuple[str, str]]) : The new key value tuple pairs.
"""
key_value_tuple_pairs = []
translation_settings_key_names = {
0: "prompt_assembly_mode",
1: "number_of_lines_per_batch",
2: "sentence_fragmenter_mode",
3: "je_check_mode",
4: "number_of_malformed_batch_retries",
5: "batch_retry_timeout",
6: "number_of_concurrent_batches",
7: "gender_context_insertion",
8: "is_cote",
9: "openai_model",
10: "openai_system_message",
11: "openai_temperature",
12: "openai_top_p",
13: "openai_n",
14: "openai_stream",
15: "openai_stop",
16: "openai_logit_bias",
17: "openai_max_tokens",
18: "openai_presence_penalty",
19: "openai_frequency_penalty",
20: "gemini_model",
21: "gemini_prompt",
22: "gemini_temperature",
23: "gemini_top_p",
24: "gemini_top_k",
25: "gemini_candidate_count",
26: "gemini_stream",
27: "gemini_stop_sequences",
28: "gemini_max_output_tokens",
29: "deepl_context",
30: "deepl_split_sentences",
31: "deepl_preserve_formatting",
32: "deepl_formality",
}
for index, setting in enumerate(translation_settings):
key = translation_settings_key_names.get(index)
key_value_tuple_pairs.append((key, setting))
return key_value_tuple_pairs
##-------------------start-of-GUI-Structure---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## tab 1 | Main
with gr.Tab("Kudasai") as self.kudasai_tab:
## tab 2 | indexing
with gr.Tab("Name Indexing | Kairyou") as self.indexing_tab:
with gr.Row():
## input fields, text input for indexing, and replacement json file input.
with gr.Column():
self.input_txt_file_indexing = gr.File(label='TXT file with Japanese Text', file_count='single', file_types=['.txt'], type='filepath')
self.input_json_file_indexing = gr.File(label='Replacements JSON file', file_count='single', file_types=['.json'], type='filepath')
self.input_knowledge_base_file = gr.File(label='Knowledge Base Single File', file_count='single', file_types=['.txt'], type='filepath')
self.input_knowledge_base_directory = gr.File(label='Knowledge Base Directory', file_count='directory', type='filepath')
## run and clear buttons
with gr.Row():
self.indexing_run_button = gr.Button('Run', variant='primary')
self.indexing_clear_button = gr.Button('Clear', variant='stop')
with gr.Row():
self.send_to_kairyou_button = gr.Button('Send to Preprocessing (Kairyou)')
## output fields
with gr.Column():
self.indexing_output_field = gr.Textbox(label='Indexed text', lines=56, max_lines=56, show_label=True, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_indexed_text = gr.Button('Save As')
with gr.Column():
self.indexing_results_output_field = gr.Textbox(label='Indexing Results', lines=56, max_lines=56, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_indexing_results = gr.Button('Save As')
with gr.Column():
self.debug_log_output_field_indexing_tab = gr.Textbox(label='Debug Log', lines=56, max_lines=56, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_indexing_tab = gr.Button('Save As')
## tab 3 | preprocessing
with gr.Tab("Text Preprocessing | Kairyou") as self.preprocessing_tab:
with gr.Row():
## input fields, text input for preprocessing, and replacement json file input.
with gr.Column():
self.input_txt_file_preprocessing = gr.File(label='TXT file with Japanese Text', file_count='single', file_types=['.txt'], type='filepath')
self.input_json_file_preprocessing = gr.File(label='Replacements JSON file', file_count='single', file_types=['.json'], type='filepath')
self.input_text_kairyou = gr.Textbox(label='Japanese Text', placeholder='Use this or the text file input, if you provide both, Kudasai will use the file input.', lines=10, show_label=True, interactive=True)
## run and clear buttons
with gr.Row():
self.preprocessing_run_button = gr.Button('Run', variant='primary')
self.preprocessing_clear_button = gr.Button('Clear', variant='stop')
with gr.Row():
self.send_to_translator_button = gr.Button('Send to Translator')
## output fields
with gr.Column():
self.preprocessing_output_field = gr.Textbox(label='Preprocessed text', lines=42, max_lines=42, show_label=True, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_preprocessed_text = gr.Button('Save As')
with gr.Column():
self.preprocessing_results_output_field = gr.Textbox(label='Preprocessing Results', lines=42, max_lines=42, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_preprocessing_results = gr.Button('Save As')
with gr.Column():
self.debug_log_output_field_preprocess_tab = gr.Textbox(label='Debug Log', lines=42, max_lines=42, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_preprocessing_tab = gr.Button('Save As')
## tab 4 | Translation
with gr.Tab("Text Translation | Translator") as self.translator_tab:
with gr.Row():
## input file or text input, gui allows for both but will prioritize file input
with gr.Column():
self.input_txt_file_translator = gr.File(label='TXT file with Japanese Text', file_count='single', file_types=['.txt'], type='filepath', interactive=True)
self.input_text_translator = gr.Textbox(label='Japanese Text', placeholder='Use this or the text file input, if you provide both, Kudasai will use the file input.', lines=10, show_label=True, interactive=True, type='text')
self.input_translation_rules_file = gr.File(value = FileEnsurer.config_translation_settings_path, label='Translation Settings File', file_count='single', file_types=['.json'], type='filepath', interactive=True)
self.input_genders_file = gr.File(value=FileEnsurer.config_translation_genders_path, label='Genders.json File', file_count='single', file_types=['.json'], type='filepath', interactive=True)
with gr.Row():
self.llm_option_dropdown = gr.Dropdown(label='Translation Method', choices=["OpenAI", "Gemini", "DeepL", "Google Translate"], value="DeepL", show_label=True, interactive=True)
with gr.Row():
self.translator_api_key_input = gr.Textbox(label='API Key', value=get_saved_api_key("deepl"), lines=1, max_lines=1, show_label=True, interactive=True, type='password')
with gr.Row():
self.translator_translate_button = gr.Button('Translate', variant="primary")
self.translator_calculate_cost_button = gr.Button('Calculate Cost', variant='secondary')
with gr.Row():
self.translator_clear_button = gr.Button('Clear', variant='stop')
## output fields
with gr.Column():
self.translator_translated_text_output_field = gr.Textbox(label='Translated Text', lines=43,max_lines=43, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_translator_translated_text = gr.Button('Save As')
with gr.Column():
self.translator_je_check_text_output_field = gr.Textbox(label='JE Check Text', lines=43,max_lines=43, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_translator_je_check_text = gr.Button('Save As')
with gr.Column():
self.translator_debug_log_output_field = gr.Textbox(label='Debug Log', lines=43, max_lines=43, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_translator_tab = gr.Button('Save As')
## tab 5 | Settings
with gr.Tab("Translation Settings") as self.translation_settings_tab:
with gr.Row():
with gr.Column():
gr.Markdown("Base Translation Settings")
gr.Markdown("These settings are used for OpenAI, Gemini, DeepL, and Google Translate")
gr.Markdown("Please ensure to thoroughly read and understand these settings before making any modifications. Each setting has a specific impact on the translation methods. Some settings may affect one or two translation methods, but not the others. Incorrect adjustments could lead to unexpected results or errors in the translation process.")
self.prompt_assembly_mode_input_field = gr.Dropdown(label='Prompt Assembly Mode',
value=int(GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","prompt_assembly_mode")),
choices=[1,2],
info=KudasaiGUI.description_dict.get("prompt_assembly_mode", "An error occurred while fetching the description for this setting."),
show_label=True,
interactive=True,
elem_id="prompt_assembly_mode")
self.number_of_lines_per_batch_input_field = gr.Textbox(label='Number of Lines Per Batch',
value=(GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","number_of_lines_per_batch")),
info=KudasaiGUI.description_dict.get("number_of_lines_per_batch"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="number_of_lines_per_batch",
show_copy_button=True)
self.sentence_fragmenter_mode_input_field = gr.Dropdown(label='Sentence Fragmenter Mode',
value=int(GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","sentence_fragmenter_mode")),
choices=[1,2],
info=KudasaiGUI.description_dict.get("sentence_fragmenter_mode"),
show_label=True,
interactive=True,
elem_id="sentence_fragmenter_mode")
self.je_check_mode_input_field = gr.Dropdown(label='JE Check Mode',
value=int(GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","je_check_mode")),
choices=[1,2],
info=KudasaiGUI.description_dict.get("je_check_mode"),
show_label=True,
interactive=True,
elem_id="je_check_mode")
self.number_of_malformed_batch_retries_input_field = gr.Textbox(label="Number Of Malformed Batch Retries",
value=GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","number_of_malformed_batch_retries"),
info=KudasaiGUI.description_dict.get("number_of_malformed_batch_retries"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="number_of_malformed_batch_retries",
show_copy_button=True)
self.batch_retry_timeout_input_field = gr.Textbox(label="Batch Retry Timeout",
value=GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","batch_retry_timeout"),
info=KudasaiGUI.description_dict.get("batch_retry_timeout"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="batch_retry_timeout",
show_copy_button=True)
self.number_of_concurrent_batches_input_field = gr.Textbox(label="Number Of Concurrent Batches",
value=GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","number_of_concurrent_batches"),
info=KudasaiGUI.description_dict.get("number_of_concurrent_batches"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="number_of_concurrent_batches",
show_copy_button=True)
self.gender_context_insertion_input_field = gr.Checkbox(label="Gender Context Insertion",
value=bool(GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","gender_context_insertion")),
info=KudasaiGUI.description_dict.get("gender_context_insertion"),
show_label=True,
interactive=True,
elem_id="number_of_concurrent_batches")
self.is_cote_input_field = gr.Checkbox(label="Is Cote",
value=bool(GuiJsonUtil.fetch_translation_settings_key_values("base translation settings","is_cote")),
info=KudasaiGUI.description_dict.get("is_cote"),
show_label=True,
interactive=True,
elem_id="is_cote")
with gr.Column():
## all these need to be changed later as well
gr.Markdown("OpenAI API Settings")
gr.Markdown(str(KudasaiGUI.description_dict.get("openai_help_link")))
gr.Markdown(str(KudasaiGUI.description_dict.get("openai_disclaimer")))
self.openai_model_input_field = gr.Dropdown(label="OpenAI Model",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_model")),
choices=[model for model in ALLOWED_OPENAI_MODELS],
info=KudasaiGUI.description_dict.get("openai_model"),
show_label=True,
interactive=True,
elem_id="openai_model")
self.openai_system_message_input_field = gr.Textbox(label="OpenAI System Message",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_system_message")),
info=KudasaiGUI.description_dict.get("openai_system_message"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="openai_system_message",
show_copy_button=True)
self.openai_temperature_input_field = gr.Slider(label="OpenAI Temperature",
value=float(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_temperature")),
minimum=0.0,
maximum=2.0,
info=KudasaiGUI.description_dict.get("openai_temperature"),
interactive=True,
elem_id="openai_temperature")
self.openai_top_p_input_field = gr.Slider(label="OpenAI Top P",
value=float(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_top_p")),
minimum=0.0,
maximum=1.0,
info=KudasaiGUI.description_dict.get("openai_top_p"),
show_label=True,
interactive=True,
elem_id="openai_top_p")
self.openai_n_input_field = gr.Textbox(label="OpenAI N",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_n")),
info=KudasaiGUI.description_dict.get("openai_n"),
show_label=True,
interactive=False,
elem_id="openai_n",
show_copy_button=True)
self.openai_stream_input_field = gr.Textbox(label="OpenAI Stream",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_stream")),
info=KudasaiGUI.description_dict.get("openai_stream"),
show_label=True,
interactive=False,
elem_id="openai_stream",
show_copy_button=True)
self.openai_stop_input_field = gr.Textbox(label="OpenAI Stop",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_stop")),
info=KudasaiGUI.description_dict.get("openai_stop"),
show_label=True,
interactive=False,
elem_id="openai_stop",
show_copy_button=True)
self.openai_logit_bias_input_field = gr.Textbox(label="OpenAI Logit Bias",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_logit_bias")),
info=KudasaiGUI.description_dict.get("openai_logit_bias"),
show_label=True,
interactive=False,
elem_id="openai_logit_bias",
show_copy_button=True)
self.openai_max_tokens_input_field = gr.Textbox(label="OpenAI Max Tokens",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_max_tokens")),
info=KudasaiGUI.description_dict.get("openai_max_tokens"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="openai_max_tokens",
show_copy_button=True)
self.openai_presence_penalty_input_field = gr.Slider(label="OpenAI Presence Penalty",
value=float(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_presence_penalty")),
info=KudasaiGUI.description_dict.get("openai_presence_penalty"),
minimum=-2.0,
maximum=2.0,
show_label=True,
interactive=True,
elem_id="openai_presence_penalty")
self.openai_frequency_penalty_input_field = gr.Slider(label="OpenAI Frequency Penalty",
value=float(GuiJsonUtil.fetch_translation_settings_key_values("openai settings","openai_frequency_penalty")),
info=KudasaiGUI.description_dict.get("openai_frequency_penalty"),
minimum=-2.0,
maximum=2.0,
show_label=True,
interactive=True,
elem_id="openai_frequency_penalty")
with gr.Row():
with gr.Column():
gr.Markdown("Gemini API Settings")
gr.Markdown(str(KudasaiGUI.description_dict.get("gemini_help_link")))
gr.Markdown(str(KudasaiGUI.description_dict.get("gemini_disclaimer")))
self.gemini_model_input_field = gr.Dropdown(label="Gemini Model",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_model")),
choices=[model for model in ALLOWED_GEMINI_MODELS],
info=KudasaiGUI.description_dict.get("gemini_model"),
show_label=True,
interactive=True,
elem_id="gemini_model")
self.gemini_prompt_input_field = gr.Textbox(label="Gemini Prompt",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_prompt")),
info=KudasaiGUI.description_dict.get("gemini_prompt"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="gemini_prompt",
show_copy_button=True)
self.gemini_temperature_input_field = gr.Slider(label="Gemini Temperature",
value=float(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_temperature")),
minimum=0.0,
maximum=2.0,
info=KudasaiGUI.description_dict.get("gemini_temperature"),
show_label=True,
interactive=True,
elem_id="gemini_temperature")
self.gemini_top_p_input_field = gr.Textbox(label="Gemini Top P",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_top_p")),
info=KudasaiGUI.description_dict.get("gemini_top_p"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="gemini_top_p",
show_copy_button=True)
self.gemini_top_k_input_field = gr.Textbox(label="Gemini Top K",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_top_k")),
info=KudasaiGUI.description_dict.get("gemini_top_k"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="gemini_top_k",
show_copy_button=True)
self.gemini_candidate_count_input_field = gr.Textbox(label="Gemini Candidate Count",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_candidate_count")),
info=KudasaiGUI.description_dict.get("gemini_candidate_count"),
lines=1,
max_lines=1,
show_label=True,
interactive=False,
elem_id="gemini_candidate_count",
show_copy_button=True)
self.gemini_stream_input_field = gr.Textbox(label="Gemini Stream",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_stream")),
info=KudasaiGUI.description_dict.get("gemini_stream"),
lines=1,
max_lines=1,
show_label=True,
interactive=False,
elem_id="gemini_stream",
show_copy_button=True)
self.gemini_stop_sequences_input_field = gr.Textbox(label="Gemini Stop Sequences",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_stop_sequences")),
info=KudasaiGUI.description_dict.get("gemini_stop_sequences"),
lines=1,
max_lines=1,
show_label=True,
interactive=False,
elem_id="gemini_stop_sequences",
show_copy_button=True)
self.gemini_max_output_tokens_input_field = gr.Textbox(label="Gemini Max Output Tokens",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("gemini settings","gemini_max_output_tokens")),
info=KudasaiGUI.description_dict.get("gemini_max_output_tokens"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="gemini_max_output_tokens",
show_copy_button=True)
with gr.Column():
gr.Markdown("DeepL API Settings")
gr.Markdown(str(KudasaiGUI.description_dict.get("deepl_help_link")))
gr.Markdown("DeepL API settings are not as extensive as OpenAI and Gemini, a lot of the settings are simply not included for Kudasai as they do not have a decent use case to warrant their inclusion. Settings may be added in the future if a use case is found or is suggested.")
self.deepl_context_input_field = gr.Textbox(label="DeepL Context",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("deepl settings","deepl_context")),
info=KudasaiGUI.description_dict.get("deepl_context"),
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="deepl_context",
show_copy_button=True)
self.deepl_split_sentences_input_field = gr.Dropdown(label="DeepL Split Sentences",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("deepl settings","deepl_split_sentences")),
choices=['OFF', 'ALL', 'NO_NEWLINES'],
info=KudasaiGUI.description_dict.get("deepl_split_sentences"),
show_label=True,
interactive=True,
elem_id="deepl_split_sentences")
self.deepl_preserve_formatting_input_field = gr.Checkbox(label="DeepL Preserve Formatting",
value=bool(GuiJsonUtil.fetch_translation_settings_key_values("deepl settings","deepl_preserve_formatting")),
info=KudasaiGUI.description_dict.get("deepl_preserve_formatting"),
show_label=True,
interactive=True,
elem_id="deepl_preserve_formatting")
self.deepl_formality_input_field = gr.Dropdown(label="DeepL Formality",
value=str(GuiJsonUtil.fetch_translation_settings_key_values("deepl settings","deepl_formality")),
choices=['default', 'more', 'less', 'prefer_more', 'prefer_less'],
info=KudasaiGUI.description_dict.get("deepl_formality"),
show_label=True,
interactive=True,
elem_id="deepl_formality")
with gr.Row():
self.translation_settings_reset_to_default_button = gr.Button('Reset to Default', variant='secondary')
self.translation_settings_discard_changes_button = gr.Button('Discard Changes', variant='stop')
with gr.Row():
self.translation_settings_apply_changes_button = gr.Button('Apply Changes', variant='primary')
## tab 6 | Logging
with gr.Tab("Logging") as self.logging_tab:
with gr.Row():
self.logging_tab_debug_log_output_field = gr.Textbox(label='Debug Log', lines=10, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_logging_tab = gr.Button('Save As')
with gr.Row():
self.logging_tab_error_log_output_field = gr.Textbox(label='Error Log', lines=10, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_error_log_logging_tab = gr.Button('Save As')
with gr.Row():
self.logging_clear_logs_button = gr.Button('Clear Logs', variant='stop')
with gr.Tab("Output"):
with gr.Row():
self.download_all_outputs_button = gr.Button('Download All Outputs', elem_id="download-all-outputs-button")
##-------------------start-of-Listener-Functions---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def webgui_update_check() -> None:
"""
Checks for if a Kudasai update is available.
"""
Kudasai.connection, update_prompt = Toolkit.check_update(do_pause=False)
if(update_prompt != ""):
gr.Info("Update available, see https://github.com/Bikatr7/Kudasai/releases/latest/ for more information.")
if(Kudasai.connection == False):
gr.Warning("No internet connection, Auto-MTL features disabled (Indexing and Preprocessing still functional). Please reload the page when you have an internet connection.")
##-------------------start-of-index()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def index(input_txt_file:gr.File, input_json_file_preprocessing:gr.File, input_knowledge_base_file:gr.File, input_knowledge_base_directory:typing.List[str]) -> typing.Tuple[str, str, str, str, str]:
"""
Runs the indexing and displays the results in the indexing output field. If no txt file is selected, an error is raised. If no json file is selected, an error is raised. If no knowledge base file or directory is selected, an error is raised.
Knowledge base file or directory must be selected, but not both.
Also displays the indexing results, the debug log, and the error log.
Parameters:
input_txt_file (gr.File) : The input txt file.
input_json_file_preprocessing (gr.File) : The input json file.
input_knowledge_base_file (gr.File) : The knowledge base file.
input_knowledge_base_directory (typing.List[str]) : List of knowledge base file paths.
Returns:
indexed_text (str) : The indexed text.
indexing_log (str) : The indexing log.
log_text (str) : The log text for the Indexing tab.
log_text (str) : The log text for the log tab.
error_log (str) : The error log for the log tab.
"""
if(input_txt_file is not None):
if(input_json_file_preprocessing is not None):
## must be one, but not both
if(input_knowledge_base_file is not None or input_knowledge_base_directory is not None) and not (input_knowledge_base_file is not None and input_knowledge_base_directory is not None):
## looks like file will just be the file path
## but directory will be a list of file paths, I can't think of a workaround right now, so will have to update kairyou to accept a list of file paths.
## wait nvm im a genius, let's just read all the files and concatenate them into one string lmfao
## index does not produce an error log
error_log = ""
knowledge_base_paths = []
knowledge_base_string = ""
text_to_index = gui_get_text_from_file(input_txt_file)
replacements = gui_get_json_from_file(input_json_file_preprocessing)
## DON"T DO THIS, THIS IS BAD PRACTICE, I'M JUST DOING BECAUSE I'M LAZY AND I MADE THE LIBRARY
try:
_validate_replacement_json(replacements)
except InvalidReplacementJsonKeys:
raise gr.Error("Invalid JSON file, please ensure that the JSON file contains the correct keys See https://github.com/Bikatr7/Kairyou for more information.")
if(input_knowledge_base_file is not None):
knowledge_base_paths.append(input_knowledge_base_file)
else:
knowledge_base_paths = [file for file in input_knowledge_base_directory]
for file in knowledge_base_paths:
knowledge_base_string += gui_get_text_from_file(file)
gr.Info("Indexing may take a while, please be patient.")
unique_names, indexing_log = Indexer.index(text_to_index, knowledge_base_string, replacements)
## Indexer does not directly log anything, in case of anything else touching it, we will grab the log from the log file
log_text = FileEnsurer.standard_read_file(FileEnsurer.debug_log_path)
indexed_text = Kudasai.mark_indexed_names(text_to_index, unique_names)
return indexed_text, indexing_log, log_text, log_text, error_log
else:
raise gr.Error("No knowledge base file or directory selected (or both selected, select one or the other)")
else:
raise gr.Error("No JSON file selected")
else:
raise gr.Error("No TXT file selected")
##-------------------start-of-preprocess()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def preprocess(input_txt_file:gr.File, input_json_file_preprocessing:gr.File, input_text_field_contents:str) -> typing.Tuple[str, str, str, str, str]:
"""
Runs the preprocessing and displays the results in the preprocessing output field. If no txt file is selected, an error is raised. If no json file is selected, an error is raised.
Also displays the preprocessing results, the debug log, and the error log.
Prioritizes the txt file input over the text input field.
Parameters:
input_txt_file (gr.File) : The input txt file.
input_json_file_preprocessing (gr.File) : The input json file.
input_text (str) : The input text.
Returns:
text_to_preprocess (str) : The preprocessed text.
preprocessing_log (str) : The preprocessing log.
log_text (str) : The log text for the Kairyou tab.
log_text (str) : The log text for the log tab.
error_log (str) : The error log for the log tab.
"""
if(input_txt_file == None and input_text_field_contents == ""):
raise gr.Error("No TXT file selected and no text input")
if(input_json_file_preprocessing is not None):
if(input_txt_file is not None):
text_to_preprocess = gui_get_text_from_file(input_txt_file)
else:
text_to_preprocess = input_text_field_contents
replacements = gui_get_json_from_file(input_json_file_preprocessing)
try:
preprocessed_text, preprocessing_log, error_log = Kairyou.preprocess(text_to_preprocess, replacements)
except InvalidReplacementJsonKeys:
## link needs to be updated later
raise gr.Error("Invalid JSON file, please ensure that the JSON file contains the correct keys See: https://github.com/Bikatr7/Kairyou?tab=readme-ov-file#usage")
timestamp = Toolkit.get_timestamp(is_archival=True)
FileEnsurer.write_kairyou_results(preprocessed_text, preprocessing_log, error_log, timestamp)
log_text = FileEnsurer.standard_read_file(FileEnsurer.debug_log_path)
return preprocessed_text, preprocessing_log, log_text, log_text, error_log
else:
raise gr.Error("No JSON file selected")
##-------------------start-of-translate_with_translator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
async def translate_with_translator(input_txt_file:gr.File, input_text:str, api_key:str, translation_method:str, translation_settings_file:gr.File) -> typing.Tuple[str, str, str, str]:
"""
Translates the text in the input_txt_file or input_text using either OpenAI, Gemini, or DeepL. If no txt file or text is selected, an error is raised. If no API key is provided or the API key is invalid, an error is raised.
Displays the translated text, the debug log, and the error log.
Parameters:
input_txt_file (gr.File) : The input txt file.
input_text (gr.Textbox) : The input text.
api_key_input (gr.Textbox) : The API key input.
Returns:
translated_text (str) : The translated text.
je_check_text (str) : The je check text.
log_text (str) : The log text for the Log tab.
error_text (str) : The error text for the Log tab.
"""
## check if we have stuff to translate
if(input_txt_file is None and input_text == ""):
raise gr.Error("No TXT file or text selected")
if(api_key == ""):
raise gr.Error("No API key provided")
if(translation_settings_file is None):
raise gr.Error("No Translation Settings File selected")
if(Kudasai.connection == False):
raise gr.Error("No internet connection detected, please connect to the internet and reload the page to use translation features of Kudasai.")
## in case of subsequent runs, we need to reset the static variables
Translator.reset_static_variables()
## start of translation, so we can assume that that we don't want to interrupt it
FileEnsurer.do_interrupt = False
## if translate button is clicked, we can assume that the translation is ongoing
self.is_translation_ongoing = True
## first, set the json in the json handler to the json currently set as in gui_json_util
JsonHandler.current_translation_settings = GuiJsonUtil.current_translation_settings
## next, set the llm type
translation_methods = {
"OpenAI": "openai",
"Gemini": "gemini",
"DeepL": "deepl",
"Google Translate": "google translate"
}
Translator.TRANSLATION_METHOD = translation_methods.get(translation_method, "") # type: ignore
## api key as well
await set_translator_api_key(api_key)