File size: 134,128 Bytes
b5698d6 |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 |
## built-in libraries
import typing
import base64
## third-party libraries
import gradio as gr
from kairyou import Indexer
from kairyou import Kairyou
## custom modules
from modules.common.toolkit import Toolkit
from modules.common.logger import Logger
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 models.kaiseki import Kaiseki
from models.kijiku import Kijiku
from translation_services.deepl_service import DeepLService
from translation_services.openai_service import OpenAIService
from translation_services.gemini_service import GeminiService
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
save_as_js = """
(text) => {
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'downloaded_text.txt';
a.click();
URL.revokeObjectURL(url);
}
"""
## used for whether the debug log tab for kaiseki/kijiku should be actively refreshing based of Logger.current_batch
is_translation_ongoing = False
##-------------------start-of-build_gui()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def build_gui(self) -> None:
"""
Builds the GUI.
"""
with gr.Blocks(title="Kudasai") 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"
if(Logger.current_batch == ""):
return "No log content found."
return Logger.current_batch
##-------------------start-of-get_saved_kaiseki_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def get_saved_kaiseki_api_key() -> str:
"""
Gets the saved kaiseki api key from the config folder, if it exists.
Returns:
api_key (str) : The api key.
"""
try:
## Api key is encoded in base 64 so we need to decode it before returning
return base64.b64decode(FileEnsurer.standard_read_file(FileEnsurer.deepl_api_key_path).encode('utf-8')).decode('utf-8')
except:
return ""
##-------------------start-of-get_saved_openai_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def get_saved_openai_api_key() -> str:
"""
Gets the saved openai api key from the config folder, if it exists.
Returns:
api_key (str) : The api key.
"""
try:
## Api key is encoded in base 64 so we need to decode it before returning
return base64.b64decode(FileEnsurer.standard_read_file(FileEnsurer.openai_api_key_path).encode('utf-8')).decode('utf-8')
except:
return ""
##-------------------start-of-get_saved_gemini_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def get_saved_gemini_api_key() -> str:
"""
Gets the saved gemini api key from the config folder, if it exists.
Returns:
api_key (str) : The api key.
"""
try:
## Api key is encoded in base 64 so we need to decode it before returning
return base64.b64decode(FileEnsurer.standard_read_file(FileEnsurer.gemini_api_key_path).encode('utf-8')).decode('utf-8')
except:
return ""
##-------------------start-of-create_new_key_value_tuple_pairs()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def create_new_key_value_tuple_pairs(kijiku_settings:typing.List[str]) -> typing.List[typing.Tuple[str, str]]:
"""
Applies the new kijiku settings to the uploaded kijiku rules file.
Parameters:
kijiku_settings (typing.List[typing.Union[gr.Textbox,gr.Slider,gr.Dropdown]]) : The kijiku setting values
Returns:
key_value_tuple_pairs (typing.List[typing.Tuple[str, str]]) : The new key value tuple pairs.
"""
key_value_tuple_pairs = []
kijiku_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: "openai_model",
8: "openai_system_message",
9: "openai_temperature",
10: "openai_top_p",
11: "openai_n",
12: "openai_stream",
13: "openai_stop",
14: "openai_logit_bias",
15: "openai_max_tokens",
16: "openai_presence_penalty",
17: "openai_frequency_penalty",
18: "gemini_model",
19: "gemini_prompt",
20: "gemini_temperature",
21: "gemini_top_p",
22: "gemini_top_k",
23: "gemini_candidate_count",
24: "gemini_stream",
25: "gemini_stop_sequences",
26: "gemini_max_output_tokens"
}
for index, setting in enumerate(kijiku_settings):
key = kijiku_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 3 | indexing
with gr.Tab("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.knowledge_base_file = gr.File(label='Knowledge Base Single File', file_count='single', file_types=['.txt'], type='filepath')
self.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 = gr.Button('Send to Kairyou (Preprocessing)')
## 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("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_kaiseki = gr.Button('Send to Kaiseki (DeepL)')
self.send_to_kijiku = gr.Button('Send to Kijiku (LLMs)')
## output fields
with gr.Column():
self.preprocess_output_field = gr.Textbox(label='Preprocessed text', lines=44, max_lines=44, 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=44, max_lines=44, 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=44, max_lines=44, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_preprocessing_tab = gr.Button('Save As')
## tab 4 | Translation Model 1 | Kaiseki
with gr.Tab("Translation With DeepL | Kaiseki") as self.kaiseki_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_kaiseki = gr.File(label='TXT file with Japanese Text', file_count='single', file_types=['.txt'], type='filepath', interactive=True)
self.input_text_kaiseki = 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)
with gr.Row():
self.kaiseki_api_key_input = gr.Textbox(label='API Key', value=get_saved_kaiseki_api_key, lines=1, show_label=True, interactive=True, type='password')
with gr.Row():
self.translate_button_kaiseki = gr.Button('Translate', variant="primary")
self.clear_button_kaiseki = gr.Button('Clear', variant='stop')
## output fields
with gr.Column():
self.output_field_kaiseki = gr.Textbox(label='Translated Text', lines=31,max_lines=31, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_kaiseki = gr.Button('Save As')
with gr.Column():
self.kaiseki_je_check_text_field = gr.Textbox(label='JE Check Text', lines=31,max_lines=31, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_je_check_text_kaiseki = gr.Button('Save As')
with gr.Column():
self.debug_log_output_field_kaiseki_tab = gr.Textbox(label='Debug Log', lines=31,max_lines=31, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_kaiseki_tab = gr.Button('Save As')
## tab 5 | Translation Model 2 | Kijiku
with gr.Tab("Translation With LLMs | Kijiku") as self.kijiku_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_kijiku = gr.File(label='TXT file with Japanese Text', file_count='single', file_types=['.txt'], type='filepath', interactive=True)
self.input_text_kijiku = 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_kijiku_rules_file = gr.File(value = FileEnsurer.config_kijiku_rules_path, label='Kijiku Rules File', file_count='single', file_types=['.json'], type='filepath')
with gr.Row():
self.llm_option = gr.Dropdown(label='LLM Option', choices=["OpenAI", "Gemini"], value="OpenAI", show_label=True, interactive=True)
self.kijiku_api_key_input = gr.Textbox(label='API Key', value=get_saved_openai_api_key, lines=1, max_lines=2, show_label=True, interactive=True, type='password')
with gr.Row():
self.translate_button_kijiku = gr.Button('Translate', variant="primary")
self.calculate_costs_button_kijiku = gr.Button('Calculate Costs', variant='secondary')
with gr.Row():
self.clear_button_kijiku = gr.Button('Clear', variant='stop')
## output fields
with gr.Column():
self.kijiku_translated_text_output_field = gr.Textbox(label='Translated Text', lines=38,max_lines=38, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_kijiku = gr.Button('Save As')
with gr.Column():
self.kijiku_je_check_text_field = gr.Textbox(label='JE Check Text', lines=38,max_lines=38, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_je_check_text_kijiku = gr.Button('Save As')
with gr.Column():
self.debug_log_output_field_kijiku_tab = gr.Textbox(label='Debug Log', lines=38, max_lines=38, interactive=False, show_copy_button=True)
with gr.Row():
self.save_to_file_debug_log_kijiku_tab = gr.Button('Save As')
## tab 6 | Kijiku Settings
with gr.Tab("Kijiku Settings") as self.kijiku_settings_tab:
with gr.Row():
with gr.Column():
gr.Markdown("Kijiku Settings")
self.prompt_assembly_mode_input_field = gr.Dropdown(label='Prompt Assembly Mode',
value=int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","prompt_assembly_mode")),
choices=[1,2],
info="1 or 2. 1 means the system message will actually be treated as a system message. 2 means it'll be treated as a user message. 1 is recommend for gpt-4 otherwise either works. For Gemini, this setting is ignored.",
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_kijiku_setting_key_values("base kijiku settings","number_of_lines_per_batch")),
info="The number of lines to be built into a prompt at once. Theoretically, more lines would be more cost effective, but other complications may occur with higher lines. So far been tested up to 48.",
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="number_of_lines_per_batch")
self.sentence_fragmenter_mode_input_field = gr.Dropdown(label='Sentence Fragmenter Mode',
value=int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","sentence_fragmenter_mode")),
choices=[1,2],
info="1 or 2 (1 - via regex and other nonsense) 2 - None (Takes formatting and text directly from API return)) the API can sometimes return a result on a single line, so this determines the way Kijiku fragments the sentences if at all. Use 2 for newer models.",
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_kijiku_setting_key_values("base kijiku settings","je_check_mode")),
choices=[1,2],
info="1 or 2, 1 will print out the jap then the english below separated by ---, 2 will attempt to pair the english and jap sentences, placing the jap above the eng. If it cannot, it will default to 1. Use 2 for newer models.",
show_label=True,
interactive=True,
elem_id="je_check_mode")
self.number_of_malformed_batch_retries_field = gr.Textbox(label="Number Of Malformed Batch Retries",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","number_of_malformed_batch_retries"),
info="(Malformed batch is when je-fixing fails) How many times Kijiku will attempt to mend a malformed batch (mending is resending the request), only for gpt4. Be careful with increasing as cost increases at (cost * length * n) at worst case. This setting is ignored if je_check_mode is set to 1.",
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="number_of_malformed_batch_retries")
self.batch_retry_timeout_input_field = gr.Textbox(label="Batch Retry Timeout",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","batch_retry_timeout"),
info="How long Kijiku will try to translate a batch in seconds, if a requests exceeds this duration, Kijiku will leave it untranslated.",
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="batch_retry_timeout")
self.number_of_concurrent_batches_input_field = gr.Textbox(label="Number Of Concurrent Batches",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","number_of_concurrent_batches"),
info="How many translations batches Kijiku will send to the translation API at a time. For OpenAI, be conservative as rate-limiting is aggressive, I'd suggest 3-5. For Gemini, do not exceed 60.",
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="number_of_concurrent_batches")
with gr.Column():
gr.Markdown("OpenAI API Settings")
gr.Markdown("openai_stream, openai_logit_bias, openai_stop and openai_n are included for completion's sake, current versions of Kudasai will hardcode their values when validating the Kijiku_rule.json to their default values. As different values for these settings do not have a use case in Kudasai's current implementation.")
gr.Markdown("See https://platform.openai.com/docs/api-reference/chat/create for further details")
self.openai_model_input_field = gr.Dropdown(label="OpenAI Model",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_model"),
choices=[model for model in FileEnsurer.ALLOWED_OPENAI_MODELS],
info="ID of the model to use. Kijiku only works with 'chat' models.",
show_label=True,
interactive=True,
elem_id="openai_model")
self.openai_system_message_input_field = gr.Textbox(label="OpenAI System Message",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_system_message"),
info="Instructions to the model. Basically tells the model how to translate.",
lines=1,
max_lines=1,
show_label=True,
interactive=True,
elem_id="openai_system_message")
self.openai_temperature_input_field = gr.Slider(label="OpenAI Temperature",
value=float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_temperature")),
minimum=0.0,
maximum=2.0,
info="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. Lower values are typically better for translation.",
show_label=True,
interactive=True,
elem_id="openai_temperature")
self.openai_top_p_input_field = gr.Slider(label="OpenAI Top P",
value=float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_top_p")),
minimum=0.0,
maximum=1.0,
info="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. I generally recommend altering this or temperature but not both.",
show_label=True,
interactive=True,
elem_id="openai_top_p")
self.openai_n_input_field = gr.Textbox(label="OpenAI N",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_n"),
info="How many chat completion choices to generate for each input message. Do not change this.",
show_label=True,
interactive=False,
elem_id="openai_n")
self.openai_stream_input_field = gr.Textbox(label="OpenAI Stream",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_stream"),
info="If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. See the OpenAI python library on GitHub for example code. Do not change this.",
show_label=True,
interactive=False,
elem_id="openai_stream")
self.openai_stop_input_field = gr.Textbox(label="OpenAI Stop",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_stop"),
info="Up to 4 sequences where the API will stop generating further tokens. Do not change this.",
show_label=True,
interactive=False,
elem_id="openai_stop")
self.openai_logit_bias_input_field = gr.Textbox(label="OpenAI Logit Bias",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_logit_bias"),
info="Modifies the likelihood of specified tokens appearing in the completion. Do not change this.",
show_label=True,
interactive=False,
elem_id="openai_logit_bias")
self.openai_max_tokens_input_field = gr.Textbox(label="OpenAI Max Tokens",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_max_tokens"),
info="The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model's context length. I wouldn't recommend changing this. Is none by default. If you change to an integer, make sure it doesn't exceed that model's context length or your request will fail and repeat till timeout.",
show_label=True,
interactive=True,
elem_id="openai_max_tokens")
self.openai_presence_penalty_input_field = gr.Slider(label="OpenAI Presence Penalty",
value=float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_presence_penalty")),
info="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. While negative values encourage repetition. Should leave this at 0.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_kijiku_setting_key_values("openai settings","openai_frequency_penalty")),
info="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. Negative values encourage repetition. Should leave this at 0.0.",
show_label=True,
interactive=True,
elem_id="openai_frequency_penalty")
with gr.Column():
gr.Markdown("Gemini API Settings")
gr.Markdown("https://ai.google.dev/docs/concepts#model-parameters for further details")
gr.Markdown("gemini_stream, gemini_stop_sequences and gemini_candidate_count are included for completion's sake, current versions of Kudasai will hardcode their values when validating the Kijiku_rule.json to their default values. As different values for these settings do not have a use case in Kudasai's current implementation.")
self.gemini_model_input_field = gr.Dropdown(label="Gemini Model",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_model"),
choices=[model for model in FileEnsurer.ALLOWED_GEMINI_MODELS],
info="The model to use. Currently only supports gemini-pro and gemini-pro-vision, the 1.0 model and it's aliases.",
show_label=True,
interactive=True,
elem_id="gemini_model")
self.gemini_prompt_input_field = gr.Textbox(label="Gemini Prompt",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_prompt"),
info="Instructions to the model. Basically tells the model how to translate.",
show_label=True,
interactive=True,
elem_id="gemini_prompt")
self.gemini_temperature_input_field = gr.Slider(label="Gemini Temperature",
value=float(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_temperature")),
minimum=0.0,
maximum=2.0,
info="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. Lower values are typically better for translation.",
show_label=True,
interactive=True,
elem_id="gemini_temperature")
self.gemini_top_p_input_field = gr.Textbox(label="Gemini Top P",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_top_p"),
info="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. I generally recommend altering this or temperature but not both.",
show_label=True,
interactive=True,
elem_id="gemini_top_p")
self.gemini_top_k_input_field = gr.Textbox(label="Gemini Top K",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_top_k"),
info="Determines the number of most probable tokens to consider for each selection step. A higher value increases diversity, a lower value makes the output more deterministic.",
show_label=True,
interactive=True,
elem_id="gemini_top_k")
self.gemini_candidate_count_input_field = gr.Textbox(label="Gemini Candidate Count",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_candidate_count"),
info="The number of candidates to generate for each input message. Do not change this.",
show_label=True,
interactive=False,
elem_id="gemini_candidate_count")
self.gemini_stream_input_field = gr.Textbox(label="Gemini Stream",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_stream"),
info="If set, partial message deltas will be sent, like in Gemini chat. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. See the OpenAI python library on GitHub for example code. Do not change this.",
show_label=True,
interactive=False,
elem_id="gemini_stream")
self.gemini_stop_sequences_input_field = gr.Textbox(label="Gemini Stop Sequences",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_stop_sequences"),
info="Up to 4 sequences where the API will stop generating further tokens. Do not change this.",
show_label=True,
interactive=False,
elem_id="gemini_stop_sequences")
self.gemini_max_output_tokens_input_field = gr.Textbox(label="Gemini Max Output Tokens",
value=GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_max_output_tokens"),
info="The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model's context length. I wouldn't recommend changing this. Is none by default. If you change to an integer, make sure it doesn't exceed that model's context length or your request will fail and repeat till timeout.",
show_label=True,
interactive=True,
elem_id="gemini_max_output_tokens")
with gr.Row():
self.reset_to_default_kijiku_settings_button = gr.Button('Reset to Default', variant='secondary')
self.discard_changes_button = gr.Button('Discard Changes', variant='stop')
with gr.Row():
self.apply_changes_button = gr.Button('Apply Changes', variant='primary')
## tab 7 | Logging
with gr.Tab("Logging") as self.logging_tab:
with gr.Row():
self.debug_log_output_field_log_tab = gr.Textbox(label='Debug Log', lines=10, interactive=False)
with gr.Row():
self.save_to_file_debug_log_logging_tab = gr.Button('Save As')
with gr.Row():
self.error_log = gr.Textbox(label='Error Log', lines=10, interactive=False)
with gr.Row():
self.save_to_file_error_log = gr.Button('Save As')
with gr.Row():
self.clear_log_button = gr.Button('Clear Logs', variant='stop')
##-------------------start-of-Listener-Functions---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def webgui_update_check() -> None:
"""
Checks for if a Kudasai update is available.
"""
Kudasai.connection, update_prompt = Toolkit.check_update()
if(update_prompt != ""):
gr.Info("Update available, see https://github.com/Bikatr7/Kudasai/releases/latest/ for more information.")
##-------------------start-of-indexing_run_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def indexing_run_button_click(input_txt_file:gr.File, input_json_file_preprocessing:gr.File, knowledge_base_file:str, knowledge_base_directory:typing.List[str]) -> typing.Tuple[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 is selected, an error is raised.
Knowledge base file or directory must be selected, but not both.
Also displays the indexing results, and the debug log.
Parameters:
input_txt_file (gr.File) : The input txt file.
input_json_file_preprocessing (gr.File) : The input json file.
knowledge_base_file (gr.File) : The knowledge base file.
knowledge_base_directory (gr.File) : The knowledge base directory.
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.
"""
if(input_txt_file is not None):
if(input_json_file_preprocessing is not None):
## must be one, but not both
if(knowledge_base_file is not None or knowledge_base_directory is not None) and not (knowledge_base_file is not None and 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
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)
if(knowledge_base_file is not None):
knowledge_base_paths.append(knowledge_base_file)
else:
knowledge_base_paths = [file for file in knowledge_base_directory]
for file in knowledge_base_paths:
knowledge_base_string += gui_get_text_from_file(file)
gr.Info("Indexing takes 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(Logger.log_file_path)
indexed_text = Kudasai.mark_indexed_names(text_to_index, unique_names)
return indexed_text, indexing_log, log_text, log_text
else:
raise gr.Error("No knowledge base file or directory selected")
else:
raise gr.Error("No JSON file selected")
else:
raise gr.Error("No TXT file selected")
##-------------------start-of-preprocessing_run_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def preprocessing_run_button_click(input_txt_file:gr.File, input_json_file_preprocessing:gr.File, input_text:str) -> typing.Tuple[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, and the debug log.
Parameters:
input_txt_file (gr.File) : The input txt file.
input_json_file_preprocessing (gr.File) : The input json file.
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.
"""
if(input_txt_file == None and input_text == ""):
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
replacements = gui_get_json_from_file(input_json_file_preprocessing)
preprocessed_text, preprocessing_log, error_log = Kairyou.preprocess(text_to_preprocess, replacements)
timestamp = Toolkit.get_timestamp(is_archival=True)
FileEnsurer.write_kairyou_results(preprocessed_text, preprocessing_log, error_log, timestamp)
log_text = FileEnsurer.standard_read_file(Logger.log_file_path)
return preprocessed_text, preprocessing_log, log_text, log_text
else:
raise gr.Error("No JSON file selected")
##-------------------start-of-kaiseki_translate_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def kaiseki_translate_button_click(input_txt_file:gr.File, input_text:gr.Textbox, api_key_input:gr.Textbox) -> typing.Tuple[str, str, str]:
"""
Translates the text in the input_txt_file or input_text using the DeepL API. 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, and the debug 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.
"""
if(Kudasai.connection == False):
raise gr.Error("No internet connection detected, please connect to the internet to use translation features of Kudasai.")
## in case of subsequent runs, we need to reset the static variables
Kaiseki.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
if(input_txt_file is None and input_text == ""):
raise gr.Error("No TXT file or text selected")
if(api_key_input == ""):
raise gr.Error("No API key provided")
if(input_txt_file is not None):
text_to_translate = gui_get_text_from_file(input_txt_file)
else:
text_to_translate = input_text
try:
DeepLService.set_api_key(str(api_key_input))
is_valid, e = DeepLService.test_api_key_validity()
if(is_valid == False and e is not None):
raise e
except:
raise gr.Error("Invalid API key")
Kaiseki.text_to_translate = [line for line in str(text_to_translate).splitlines()]
Kaiseki.commence_translation()
Kaiseki.write_kaiseki_results()
## je check text and translated text are lists of strings, so we need to convert them to strings
translated_text = "\n".join(Kaiseki.translated_text)
je_check_text = "\n".join(Kaiseki.je_check_text)
## Log text is cleared from the client, so we need to get it from the log file
log_text = FileEnsurer.standard_read_file(Logger.log_file_path)
## also gonna want to update the api key file with the new api key
FileEnsurer.standard_overwrite_file(FileEnsurer.deepl_api_key_path, base64.b64encode(str(api_key_input).encode('utf-8')).decode('utf-8'), omit=True)
return translated_text, je_check_text, log_text
##-------------------start-of-kijiku_translate_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
async def kijiku_translate_button_click(input_txt_file:str, input_text:str, api_key_input:str, llm_type:str) -> typing.Tuple[str, str, str]:
"""
Translates the text in the input_txt_file or input_text using the OpenAI API. 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, and the debug 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.
"""
## 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(Kudasai.connection == False):
raise gr.Error("No internet connection detected, please connect to the internet to use translation features of Kudasai.")
## in case of subsequent runs, we need to reset the static variables
Kijiku.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_kijiku_rules = GuiJsonUtil.current_kijiku_rules
## next, set the llm type
if(llm_type == "openai"):
Kijiku.LLM_TYPE = llm_type
elif(llm_type == "gemini"):
Kijiku.LLM_TYPE = "gemini"
else:
raise gr.Error("Invalid LLM type")
## next api key
try:
if(Kijiku.LLM_TYPE == "openai"):
OpenAIService.set_api_key(str(api_key_input))
is_valid, e = await OpenAIService.test_api_key_validity()
else:
GeminiService.redefine_client()
GeminiService.set_api_key(str(api_key_input))
is_valid, e = await GeminiService.test_api_key_validity()
if(is_valid == False and e is not None):
raise e
except:
raise gr.Error("Invalid API key")
if(input_txt_file is not None):
text_to_translate = gui_get_text_from_file(input_txt_file)
else:
text_to_translate = input_text
## need to convert to list of strings
Kijiku.text_to_translate = [line for line in str(text_to_translate).splitlines()]
## commence translation
await Kijiku.commence_translation(is_webgui=True)
Kijiku.write_kijiku_results()
## je check text and translated text are lists of strings, so we need to convert them to strings
translated_text = "\n".join(Kijiku.translated_text)
je_check_text = "\n".join(Kijiku.je_check_text)
## Log text is cleared from the client, so we need to get it from the log file
log_text = FileEnsurer.standard_read_file(Logger.log_file_path)
## also gonna want to update the api key file with the new api key
FileEnsurer.standard_overwrite_file(FileEnsurer.openai_api_key_path, base64.b64encode(str(api_key_input).encode('utf-8')).decode('utf-8'), omit=True)
return translated_text, je_check_text, log_text
##-------------------start-of-kijiku_calculate_costs_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def kijiku_calculate_costs_button_click(input_txt_file:str, input_text:str, llm_type:str) -> str:
"""
Calculates the cost of the text in the input_txt_file or input_text using the OpenAI API. If no txt file or text is selected, an error is raised.
Displays the cost, and the debug log.
Parameters:
input_txt_file (gr.File) : The input txt file.
input_text (gr.Textbox) : The input text.
Returns:
cost_estimation (str) : The cost estimation formatted as a string.
"""
## next, set the llm type
if(llm_type == "openai"):
Kijiku.LLM_TYPE = llm_type
elif(llm_type == "gemini"):
Kijiku.LLM_TYPE = "gemini"
else:
raise gr.Error("Invalid LLM type")
model = GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_model") if Kijiku.LLM_TYPE == "openai" else GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_model")
if(input_txt_file is None and input_text == ""):
raise gr.Error("No TXT file or text selected")
if(input_txt_file is not None):
text_to_translate = gui_get_text_from_file(input_txt_file)
else:
text_to_translate = input_text
## need to convert to list of strings
Kijiku.text_to_translate = [line for line in str(text_to_translate).splitlines()]
num_tokens, estimated_cost, model = Kijiku.estimate_cost(model)
cost_estimation = "Estimated number of tokens : " + str(num_tokens) + "\n" + "Estimated minimum cost : " + str(estimated_cost) + " USD"
gr.Info(cost_estimation)
return cost_estimation
##-------------------start-of-indexing_clear_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def indexing_clear_button_click() -> typing.Tuple[None, None, None, None, str, str, str]:
"""
Clears all fields on the indexing tab. As well as the input fields.
Returns:
input_txt_file_indexing (gr.File) : An empty file.
input_json_file_indexing (gr.File) : An empty file.
knowledge_base_file (gr.File) : An empty file.
indexing_output_field (str) : An empty string.
indexing_results_output_field (str) : An empty string.
debug_log_output_field_indexing_tab (str) : An empty string.
"""
input_txt_file_indexing = None
input_json_file_indexing = None
knowledge_base_file = None
knowledge_base_directory = None
indexing_output_field = ""
indexing_results_output_field = ""
debug_log_output_field_indexing_tab = ""
return input_txt_file_indexing, input_json_file_indexing, knowledge_base_file, knowledge_base_directory, indexing_output_field, indexing_results_output_field, debug_log_output_field_indexing_tab
##-------------------start-of-preprocessing_clear_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def preprocessing_clear_button_click() -> typing.Tuple[None, None, str, str, str, str]:
"""
Clears all fields on the preprocessing tab. As well as the input fields.
Returns:
input_txt_file (gr.File) : An empty file.
input_json_file_preprocessing (gr.File) : An empty file.
preprocess_output_field (str) : An empty string.
preprocessing_results_output_field (str) : An empty string.
debug_log_output_field_preprocess_tab (str) : An empty string.
"""
input_txt_file = None
input_json_file_preprocessing = None
input_text = ""
preprocess_output_field = ""
preprocessing_results_output_field = ""
debug_log_output_field_preprocess_tab = ""
return input_txt_file, input_json_file_preprocessing, input_text, preprocess_output_field, preprocessing_results_output_field, debug_log_output_field_preprocess_tab
##-------------------start-of-kaiseki_run_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def kaiseki_clear_button_click() -> typing.Tuple[None, str, str, str, str]:
"""
Clears all fields on the Kaiseki tab. As well as the input fields.
Returns:
input_txt_file_kaiseki (gr.File) : An empty file.
input_text_kaiseki (str) : An empty string.
output_field_kaiseki (str) : An empty string.
je_check_text_field_kaiseki (str) : An empty string.
debug_log_output_field_kaiseki_tab (str) : An empty string.
"""
## if clear button is clicked, we can assume that the translation is over, or that the user wants to cancel the translation
self.is_translation_ongoing = False
## Same as above, we can assume that the user wants to cancel the translation
FileEnsurer.do_interrupt = True
input_file_kaiseki = None
input_text_kaiseki = ""
output_field_kaiseki = ""
je_check_text_field_kaiseki = ""
debug_log_output_field_kaiseki_tab = ""
return input_file_kaiseki, input_text_kaiseki, output_field_kaiseki, je_check_text_field_kaiseki, debug_log_output_field_kaiseki_tab
##-------------------start-of-kijiku_clear_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def kijiku_clear_button_click() -> typing.Tuple[None, str, gr.File, str, str, str]:
"""
Clears all fields on the Kijiku tab. As well as the input fields.
Returns:
input_txt_file_kijiku (gr.File) : An empty file.
input_text_kijiku (str) : An empty string.
kijiku_translated_text_output_field (str) : An empty string.
je_check_text_field_kijiku (str) : An empty string.
debug_log_output_field_kijiku_tab (str) : An empty string.
"""
## if clear button is clicked, we can assume that the translation is over, or that the user wants to cancel the translation
self.is_translation_ongoing = False
## Same as above, we can assume that the user wants to cancel the translation
FileEnsurer.do_interrupt = True
input_file_kijiku = None
input_text_kijiku = ""
## Also gonna want to reset the json input field to the default json file
input_kijiku_rules_file = gr.File(value = FileEnsurer.config_kijiku_rules_path, label='Kijiku Rules File', file_count='single', file_types=['.json'], type='filepath')
kijiku_translated_text_output_field = ""
je_check_text_field_kijiku = ""
debug_log_output_field_kijiku_tab = ""
return input_file_kijiku, input_text_kijiku, input_kijiku_rules_file, kijiku_translated_text_output_field, je_check_text_field_kijiku, debug_log_output_field_kijiku_tab
##-------------------start-of-clear_log_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def clear_log_button_click() -> typing.Tuple[str, str]:
"""
Clears the logs on the log tab.
Returns:
debug_log_output_field_log_tab (str) : An empty string.
error_log (str) : An empty string.
"""
debug_log_output_field_log_tab = ""
error_log = ""
return debug_log_output_field_log_tab, error_log
##-------------------start-of-apply_new_kijiku_settings()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def apply_new_kijiku_settings(input_kijiku_rules_file:gr.File,
prompt_assembly_mode:int,
number_of_lines_per_batch:int,
sentence_fragmenter_mode:int,
je_check_mode:int,
num_malformed_batch_retries:int,
batch_retry_timeout:int,
num_concurrent_batches:int,
openai_model:str,
openai_system_message:str,
openai_temperature:float,
openai_top_p:float,
openai_n:str,
openai_stream:str,
openai_stop:str,
openai_logit_bias:str,
openai_max_tokens:str,
openai_presence_penalty:float,
openai_frequency_penalty:float,
gemini_model:str,
gemini_prompt:str,
gemini_temperature:float,
gemini_top_p:str,
gemini_top_k:str,
gemini_candidate_count:str,
gemini_stream:str,
gemini_stop_sequences:str,
gemini_max_output_tokens:str) -> None:
"""
Applies the new kijiku settings to the kijiku rules file.
"""
if(input_kijiku_rules_file is None):
raise gr.Error("No Kijiku Rules File Selected. Cannot apply settings.")
## build the new kijiku settings list so we can create a key-value pair list
settings_list = [
prompt_assembly_mode,
number_of_lines_per_batch,
sentence_fragmenter_mode,
je_check_mode,
num_malformed_batch_retries,
batch_retry_timeout,
num_concurrent_batches,
openai_model,
openai_system_message,
openai_temperature,
openai_top_p,
openai_n,
openai_stream,
openai_stop,
openai_logit_bias,
openai_max_tokens,
openai_presence_penalty,
openai_frequency_penalty,
gemini_model,
gemini_prompt,
gemini_temperature,
gemini_top_p,
gemini_top_k,
gemini_candidate_count,
gemini_stream,
gemini_stop_sequences,
gemini_max_output_tokens
]
## create the new key-value pair list
new_key_value_tuple_pairs = create_new_key_value_tuple_pairs(settings_list)
try:
## and then have the GuiJsonUtil apply the new kijiku settings
GuiJsonUtil.update_kijiku_settings_with_new_values(input_kijiku_rules_file, new_key_value_tuple_pairs)
except:
raise gr.Error("Invalid Kijiku Settings")
gr.Info("Kijiku Settings Applied")
##-------------------start-of-reset_to_default_kijiku_settings()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def reset_to_default_kijiku_settings(input_kijiku_rules_file:str):
"""
Resets the kijiku settings to the default values.
"""
if(input_kijiku_rules_file is None):
raise gr.Error("No Kijiku Rules File Selected. Cannot reset settings.")
GuiJsonUtil.current_kijiku_rules = FileEnsurer.DEFAULT_KIJIKU_RULES
prompt_assembly_mode_value = int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","prompt_assembly_mode"))
number_of_lines_per_batch_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","number_of_lines_per_batch"))
sentence_fragmenter_mode_value = int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","sentence_fragmenter_mode"))
je_check_mode_value = int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","je_check_mode"))
num_malformed_batch_retries_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","num_malformed_batch_retries"))
batch_retry_timeout_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","batch_retry_timeout"))
num_concurrent_batches_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","num_concurrent_batches"))
openai_model_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_model"))
openai_system_message_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_system_message"))
openai_temperature_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_temperature"))
openai_top_p_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_top_p"))
openai_n_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_n"))
openai_stream_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_stream"))
openai_stop_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_stop"))
openai_logit_bias_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_logit_bias"))
openai_max_tokens_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_max_tokens"))
openai_presence_penalty_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_presence_penalty"))
openai_frequency_penalty_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_frequency_penalty"))
gemini_model_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_model"))
gemini_prompt_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_prompt"))
gemini_temperature_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_temperature"))
gemini_top_p_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_top_p"))
gemini_top_k_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_top_k"))
gemini_candidate_count_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_candidate_count"))
gemini_stream_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_stream"))
gemini_stop_sequences_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_stop_sequences"))
gemini_max_output_tokens_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_max_output_tokens"))
return_batch = [
GuiJsonUtil.current_kijiku_rules,
prompt_assembly_mode_value,
number_of_lines_per_batch_value,
sentence_fragmenter_mode_value,
je_check_mode_value,
num_malformed_batch_retries_value,
batch_retry_timeout_value,
num_concurrent_batches_value,
openai_model_value,
openai_system_message_value,
openai_temperature_value,
openai_top_p_value,
openai_n_value,
openai_stream_value,
openai_stop_value,
openai_logit_bias_value,
openai_max_tokens_value,
openai_presence_penalty_value,
openai_frequency_penalty_value,
gemini_model_value,
gemini_prompt_value,
gemini_temperature_value,
gemini_top_p_value,
gemini_top_k_value,
gemini_candidate_count_value,
gemini_stream_value,
gemini_stop_sequences_value,
gemini_max_output_tokens_value
]
gr.Info("Kijiku Settings Reset to Default")
return return_batch
##-------------------start-of-refresh_kijiku_settings_fields()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def refresh_kijiku_settings_fields(input_kijiku_rules_file:str):
"""
"""
if(input_kijiku_rules_file is None):
raise gr.Error("No Kijiku Rules File Selected. Cannot refresh settings.")
## assume that the user has uploaded a valid kijiku rules file, if it's not, that's on them
try:
GuiJsonUtil.current_kijiku_rules = gui_get_json_from_file(input_kijiku_rules_file)
## update the default values on the Kijiku Settings tab manually
prompt_assembly_mode_value = int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","prompt_assembly_mode"))
number_of_lines_per_batch_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","number_of_lines_per_batch"))
sentence_fragmenter_mode_value = int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","sentence_fragmenter_mode"))
je_check_mode_value = int(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","je_check_mode"))
num_malformed_batch_retries_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","num_malformed_batch_retries"))
batch_retry_timeout_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","batch_retry_timeout"))
num_concurrent_batches_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("base kijiku settings","num_concurrent_batches"))
openai_model_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_model"))
openai_system_message_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_system_message"))
openai_temperature_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_temperature"))
openai_top_p_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_top_p"))
openai_n_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_n"))
openai_stream_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_stream"))
openai_stop_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_stop"))
openai_logit_bias_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_logit_bias"))
openai_max_tokens_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_max_tokens"))
openai_presence_penalty_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_presence_penalty"))
openai_frequency_penalty_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("openai settings","openai_frequency_penalty"))
gemini_model_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_model"))
gemini_prompt_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_prompt"))
gemini_temperature_value = float(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_temperature"))
gemini_top_p_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_top_p"))
gemini_top_k_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_top_k"))
gemini_candidate_count_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_candidate_count"))
gemini_stream_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_stream"))
gemini_stop_sequences_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_stop_sequences"))
gemini_max_output_tokens_value = str(GuiJsonUtil.fetch_kijiku_setting_key_values("gemini settings","gemini_max_output_tokens"))
return_batch = [
prompt_assembly_mode_value,
number_of_lines_per_batch_value,
sentence_fragmenter_mode_value,
je_check_mode_value,
num_malformed_batch_retries_value,
batch_retry_timeout_value,
num_concurrent_batches_value,
openai_model_value,
openai_system_message_value,
openai_temperature_value,
openai_top_p_value,
openai_n_value,
openai_stream_value,
openai_stop_value,
openai_logit_bias_value,
openai_max_tokens_value,
openai_presence_penalty_value,
openai_frequency_penalty_value,
gemini_model_value,
gemini_prompt_value,
gemini_temperature_value,
gemini_top_p_value,
gemini_top_k_value,
gemini_candidate_count_value,
gemini_stream_value,
gemini_stop_sequences_value,
gemini_max_output_tokens_value
]
except:
GuiJsonUtil.current_kijiku_rules = JsonHandler.current_kijiku_rules
raise gr.Error("Invalid Custom Kijiku Rules File")
return return_batch
##-------------------start-of-clear_kijiku_settings_input_fields()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def clear_kijiku_settings_input_fields():
"""
Resets the kijiku settings input fields to None.
"""
input_kijiku_rules_file = None
prompt_assembly_mode_value = None
number_of_lines_per_batch_value = None
sentence_fragmenter_mode_value = None
je_check_mode_value = None
num_malformed_batch_retries_value = None
batch_retry_timeout_value = None
num_concurrent_batches_value = None
openai_model_value = None
openai_system_message_value = None
openai_temperature_value = None
openai_top_p_value = None
openai_n_value = None
openai_stream_value = None
openai_stop_value = None
openai_logit_bias_value = None
openai_max_tokens_value = None
openai_presence_penalty_value = None
openai_frequency_penalty_value = None
gemini_model_value = None
gemini_prompt_value = None
gemini_temperature_value = None
gemini_top_p_value = None
gemini_top_k_value = None
gemini_candidate_count_value = None
gemini_stream_value = None
gemini_stop_sequences_value = None
gemini_max_output_tokens_value = None
return input_kijiku_rules_file, prompt_assembly_mode_value, number_of_lines_per_batch_value, sentence_fragmenter_mode_value, je_check_mode_value, num_malformed_batch_retries_value, batch_retry_timeout_value, num_concurrent_batches_value, openai_model_value, openai_system_message_value, openai_temperature_value, openai_top_p_value, openai_n_value, openai_stream_value, openai_stop_value, openai_logit_bias_value, openai_max_tokens_value, openai_presence_penalty_value, openai_frequency_penalty_value, gemini_model_value, gemini_prompt_value, gemini_temperature_value, gemini_top_p_value, gemini_top_k_value, gemini_candidate_count_value, gemini_stream_value, gemini_stop_sequences_value, gemini_max_output_tokens_value
##-------------------start-of-fetch_log_content()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def fetch_debug_log_content() -> typing.Tuple[str, str]:
"""
Fetches the log content from the log file.
Returns:
log_text (str) : The log text.
error_log (str) : The error log.
"""
log_text = FileEnsurer.standard_read_file(Logger.log_file_path)
error_log = FileEnsurer.standard_read_file(FileEnsurer.error_log_path)
return log_text, error_log
##-------------------start-of-send_to_kairyou()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def send_to_kairyou(input_text:str) -> str:
"""
Sends the indexed text to Kairyou.
Parameters:
input_text (str) : The input text.
Returns:
input_text (str) : The input text.
"""
if(input_text == ""):
gr.Warning("No indexed text to send to Kairyou")
return ""
else:
gr.Info("Indexed text copied to Kairyou")
return input_text
##-------------------start-of-send_to_kaiseki()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def send_to_kaiseki(input_text:str) -> str:
""""
Sends the preprocessed text to Kaiseki.
Parameters:
input_text (str) : The input text.
Returns:
input_text (str) : The input text.
"""
if(input_text == ""):
gr.Warning("No preprocessed text to send to Kaiseki")
return ""
else:
gr.Info("Preprocessed text copied to Kaiseki")
return input_text
##-------------------start-of-send_to_kijiku()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def send_to_kijiku(input_text:str) -> str:
"""
Sends the preprocessed text to Kijiku.
Parameters:
input_text (str) : The input text.
Returns:
input_text (str) : The input text.
"""
if(input_text == ""):
gr.Warning("No preprocessed text to send to Kijiku")
return ""
else:
gr.Info("Preprocessed text copied to Kijiku")
return input_text
##-------------------start-of-Listener-Declaration---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
##-------------------start-of-load()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.gui.load(webgui_update_check)
##-------------------start-of-indexing_run_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.indexing_run_button.click(indexing_run_button_click,
inputs=[
self.input_txt_file_indexing, ## input txt file to index
self.input_json_file_indexing, ## input json file
self.knowledge_base_file, ## knowledge base file
self.knowledge_base_directory], ## knowledge base directory
outputs=[
self.indexing_output_field, ## indexed text
self.indexing_results_output_field, ## indexing results
self.debug_log_output_field_indexing_tab, ## debug log on indexing tab
self.debug_log_output_field_log_tab]) ## debug log on log tab
##-------------------start-of-preprocessing_run_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.preprocessing_run_button.click(fn=preprocessing_run_button_click,
inputs=[
self.input_txt_file_preprocessing, ## input txt file to preprocess
self.input_json_file_preprocessing, ## replacements json file
self.input_text_kairyou], ## input text to preprocess
outputs=[
self.preprocess_output_field, ## preprocessed text
self.preprocessing_results_output_field, ## kairyou results
self.debug_log_output_field_preprocess_tab, ## debug log on preprocess tab
self.debug_log_output_field_log_tab]) ## debug log on log tab
##-------------------start-of-kaiseki_translate_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## for the actual translation, and the je check text
kaiseki_translation_process = self.translate_button_kaiseki.click(kaiseki_translate_button_click,
inputs=[
self.input_txt_file_kaiseki, ## input txt file to translate
self.input_text_kaiseki, ## input text to translate
self.kaiseki_api_key_input], ## api key input
outputs=[
self.output_field_kaiseki, ## translated text
self.kaiseki_je_check_text_field, ## je check text field on kaiseki tab
self.debug_log_output_field_log_tab]) ## debug log on log tab
## for the kaiseki debug log
self.translate_button_kaiseki.click(fn=fetch_log_content,
inputs=[],
outputs=[self.debug_log_output_field_kaiseki_tab], ## debug log on kaiseki tab
every=.1) ## update every 100ms
##-------------------start-of-kijiku_translate_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## for the actual translation, and the je check text
kijiku_translation_process = self.translate_button_kijiku.click(kijiku_translate_button_click,
inputs=[
self.input_txt_file_kijiku, ## input txt file to translate
self.input_text_kijiku, ## input text to translate
self.kijiku_api_key_input, ## api key input
self.llm_option], ## llm option input
outputs=[
self.kijiku_translated_text_output_field, ## translated text
self.kijiku_je_check_text_field, ## je check text field on kijiku tab
self.debug_log_output_field_log_tab])
## for the kijiku debug log
self.translate_button_kijiku.click(fn=fetch_log_content,
inputs=[],
outputs=[self.debug_log_output_field_kijiku_tab], ## debug log on kijiku tab
every=.1) ## update every 100ms
##-------------------start-of-kijiku_calculate_costs_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.calculate_costs_button_kijiku.click(kijiku_calculate_costs_button_click,
inputs=[
self.input_txt_file_kijiku, ## input txt file to calculate costs
self.input_text_kijiku,
self.llm_option], ## llm option input
outputs=[self.kijiku_translated_text_output_field]) ## functions as an output field for the cost output field
##-------------------start-of-indexing_clear_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.indexing_clear_button.click(indexing_clear_button_click,
inputs=[],
outputs=[
self.input_txt_file_indexing, ## input txt file
self.input_json_file_indexing, ## input json file
self.knowledge_base_file, ## knowledge base file
self.knowledge_base_directory, ## knowledge base directory
self.indexing_output_field, ## indexing output field
self.indexing_results_output_field, ## indexing results output field
self.debug_log_output_field_indexing_tab]) ## debug log on indexing tab
##-------------------start-of-preprocessing_clear_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.preprocessing_clear_button.click(preprocessing_clear_button_click,
inputs=[],
outputs=[
self.input_txt_file_preprocessing, ## input txt file
self.input_json_file_preprocessing, ## input json file
self.input_text_kairyou, ## input text
self.preprocess_output_field, ## preprocessed text output field
self.preprocessing_results_output_field, ## preprocessing results output field
self.debug_log_output_field_preprocess_tab])## debug log on preprocess tab
##-------------------start-of-clear_button_kaiseki_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.clear_button_kaiseki.click(kaiseki_clear_button_click,
inputs=[],
outputs=[
self.input_txt_file_kaiseki, ## input txt file
self.input_text_kaiseki, ## input text
self.output_field_kaiseki, ## translation output field
self.kaiseki_je_check_text_field, ## je check text field on kaiseki tab
self.debug_log_output_field_kaiseki_tab], ## debug log on kaiseki tab
cancels=kaiseki_translation_process) ## cancels the translation process
##-------------------start-of-clear_button_kijiku_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.clear_button_kijiku.click(kijiku_clear_button_click,
inputs=[],
outputs=[
self.input_txt_file_kijiku, ## input txt file
self.input_text_kijiku, ## input text
self.input_kijiku_rules_file, ## kijiku rules file
self.kijiku_translated_text_output_field, ## translation output field
self.kijiku_je_check_text_field, ## je check text field on kijiku tab
self.debug_log_output_field_kijiku_tab], ## debug log on kijiku tab
cancels=kijiku_translation_process)
##-------------------start-of-clear_log_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.clear_log_button.click(clear_log_button_click,
inputs=[],
outputs=[
self.debug_log_output_field_log_tab,
self.error_log])
##-------------------start-of-apply_new_kijiku_settings()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.apply_changes_button.click(apply_new_kijiku_settings,
inputs=[
self.input_kijiku_rules_file, ## kijiku rules file
self.prompt_assembly_mode_input_field, ## prompt assembly mode input field
self.number_of_lines_per_batch_input_field, ## num lines input field
self.sentence_fragmenter_mode_input_field, ## sentence fragmenter mode input field
self.je_check_mode_input_field, ## je check mode input field
self.number_of_malformed_batch_retries_field, ## num malformed batch retries input field
self.batch_retry_timeout_input_field, ## batch retry timeout input field
self.number_of_concurrent_batches_input_field, ## num concurrent batches input field
self.openai_model_input_field, ## openai model input field
self.openai_system_message_input_field, ## openai system message input field
self.openai_temperature_input_field, ## openai temperature input field
self.openai_top_p_input_field, ## openai top p input field
self.openai_n_input_field, ## openai n input field
self.openai_stream_input_field, ## openai stream input field
self.openai_stop_input_field, ## openai stop input field
self.openai_logit_bias_input_field, ## openai logit bias input field
self.openai_max_tokens_input_field, ## openai max tokens input field
self.openai_presence_penalty_input_field, ## openai presence penalty input field
self.openai_frequency_penalty_input_field, ## openai frequency penalty input field
self.gemini_model_input_field, ## gemini model input field
self.gemini_prompt_input_field, ## gemini prompt input field
self.gemini_temperature_input_field, ## gemini temperature input field
self.gemini_top_p_input_field, ## gemini top p input field
self.gemini_top_k_input_field, ## gemini top k input field
self.gemini_candidate_count_input_field, ## gemini candidate count input field
self.gemini_stream_input_field, ## gemini stream input field
self.gemini_stop_sequences_input_field, ## gemini stop sequences input field
self.gemini_max_output_tokens_input_field], ## gemini max output tokens input field
outputs=[])
##-------------------start-of-reset_to_default_kijiku_settings_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.reset_to_default_kijiku_settings_button.click(reset_to_default_kijiku_settings,
inputs=[self.input_kijiku_rules_file],
outputs=[self.input_kijiku_rules_file, ## kijiku rules file
self.prompt_assembly_mode_input_field, ## prompt assembly mode input field
self.number_of_lines_per_batch_input_field, ## num lines input field
self.sentence_fragmenter_mode_input_field, ## sentence fragmenter mode input field
self.je_check_mode_input_field, ## je check mode input field
self.number_of_malformed_batch_retries_field, ## num malformed batch retries input field
self.batch_retry_timeout_input_field, ## batch retry timeout input field
self.number_of_concurrent_batches_input_field, ## num concurrent batches input field
self.openai_model_input_field, ## openai model input field
self.openai_system_message_input_field, ## openai system message input field
self.openai_temperature_input_field, ## openai temperature input field
self.openai_top_p_input_field, ## openai top p input field
self.openai_n_input_field, ## openai n input field
self.openai_stream_input_field, ## openai stream input field
self.openai_stop_input_field, ## openai stop input field
self.openai_logit_bias_input_field, ## openai logit bias input field
self.openai_max_tokens_input_field, ## openai max tokens input field
self.openai_presence_penalty_input_field, ## openai presence penalty input field
self.openai_frequency_penalty_input_field, ## openai frequency penalty input field
self.gemini_model_input_field, ## gemini model input field
self.gemini_prompt_input_field, ## gemini prompt input field
self.gemini_temperature_input_field, ## gemini temperature input field
self.gemini_top_p_input_field, ## gemini top p input field
self.gemini_top_k_input_field, ## gemini top k input field
self.gemini_candidate_count_input_field, ## gemini candidate count input field
self.gemini_stream_input_field, ## gemini stream input field
self.gemini_stop_sequences_input_field, ## gemini stop sequences input field
self.gemini_max_output_tokens_input_field])
##-------------------start-of-discard_changes_button_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.discard_changes_button.click(refresh_kijiku_settings_fields,
inputs=[self.input_kijiku_rules_file],
outputs=[
self.prompt_assembly_mode_input_field, ## prompt assembly mode input field
self.number_of_lines_per_batch_input_field, ## num lines input field
self.sentence_fragmenter_mode_input_field, ## sentence fragmenter mode input field
self.je_check_mode_input_field, ## je check mode input field
self.number_of_malformed_batch_retries_field, ## num malformed batch retries input field
self.batch_retry_timeout_input_field, ## batch retry timeout input field
self.number_of_concurrent_batches_input_field, ## num concurrent batches input field
self.openai_model_input_field, ## openai model input field
self.openai_system_message_input_field, ## openai system message input field
self.openai_temperature_input_field, ## openai temperature input field
self.openai_top_p_input_field, ## openai top p input field
self.openai_n_input_field, ## openai n input field
self.openai_stream_input_field, ## openai stream input field
self.openai_stop_input_field, ## openai stop input field
self.openai_logit_bias_input_field, ## openai logit bias input field
self.openai_max_tokens_input_field, ## openai max tokens input field
self.openai_presence_penalty_input_field, ## openai presence penalty input field
self.openai_frequency_penalty_input_field, ## openai frequency penalty input field
self.gemini_model_input_field, ## gemini model input field
self.gemini_prompt_input_field, ## gemini prompt input field
self.gemini_temperature_input_field, ## gemini temperature input field
self.gemini_top_p_input_field, ## gemini top p input field
self.gemini_top_k_input_field, ## gemini top k input field
self.gemini_candidate_count_input_field, ## gemini candidate count input field
self.gemini_stream_input_field, ## gemini stream input field
self.gemini_stop_sequences_input_field, ## gemini stop sequences input field
self.gemini_max_output_tokens_input_field]) ## gemini max output tokens input field
##-------------------start-of-input_kijiku_rules_file_upload()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.input_kijiku_rules_file.upload(refresh_kijiku_settings_fields,
inputs=[self.input_kijiku_rules_file],
outputs=[
self.prompt_assembly_mode_input_field, ## prompt assembly mode input field
self.number_of_lines_per_batch_input_field, ## num lines input field
self.sentence_fragmenter_mode_input_field, ## sentence fragmenter mode input field
self.je_check_mode_input_field, ## je check mode input field
self.number_of_malformed_batch_retries_field, ## num malformed batch retries input field
self.batch_retry_timeout_input_field, ## batch retry timeout input field
self.number_of_concurrent_batches_input_field, ## num concurrent batches input field
self.openai_model_input_field, ## openai model input field
self.openai_system_message_input_field, ## openai system message input field
self.openai_temperature_input_field, ## openai temperature input field
self.openai_top_p_input_field, ## openai top p input field
self.openai_n_input_field, ## openai n input field
self.openai_stream_input_field, ## openai stream input field
self.openai_stop_input_field, ## openai stop input field
self.openai_logit_bias_input_field, ## openai logit bias input field
self.openai_max_tokens_input_field, ## openai max tokens input field
self.openai_presence_penalty_input_field, ## openai presence penalty input field
self.openai_frequency_penalty_input_field, ## openai frequency penalty input field
self.gemini_model_input_field, ## gemini model input field
self.gemini_prompt_input_field, ## gemini prompt input field
self.gemini_temperature_input_field, ## gemini temperature input field
self.gemini_top_p_input_field, ## gemini top p input field
self.gemini_top_k_input_field, ## gemini top k input field
self.gemini_candidate_count_input_field, ## gemini candidate count input field
self.gemini_stream_input_field, ## gemini stream input field
self.gemini_stop_sequences_input_field, ## gemini stop sequences input field
self.gemini_max_output_tokens_input_field])
self.input_kijiku_rules_file.clear(clear_kijiku_settings_input_fields,
inputs=[],
outputs=[
self.input_kijiku_rules_file, ## kijiku rules file
self.prompt_assembly_mode_input_field, ## prompt assembly mode input field
self.number_of_lines_per_batch_input_field, ## num lines input field
self.sentence_fragmenter_mode_input_field, ## sentence fragmenter mode input field
self.je_check_mode_input_field, ## je check mode input field
self.number_of_malformed_batch_retries_field, ## num malformed batch retries input field
self.batch_retry_timeout_input_field, ## batch retry timeout input field
self.number_of_concurrent_batches_input_field, ## num concurrent batches input field
self.openai_model_input_field, ## openai model input field
self.openai_system_message_input_field, ## openai system message input field
self.openai_temperature_input_field, ## openai temperature input field
self.openai_top_p_input_field, ## openai top p input field
self.openai_n_input_field, ## openai n input field
self.openai_stream_input_field, ## openai stream input field
self.openai_stop_input_field, ## openai stop input field
self.openai_logit_bias_input_field, ## openai logit bias input field
self.openai_max_tokens_input_field, ## openai max tokens input field
self.openai_presence_penalty_input_field, ## openai presence penalty input field
self.openai_frequency_penalty_input_field, ## openai frequency penalty input field
self.gemini_model_input_field, ## gemini model input field
self.gemini_prompt_input_field, ## gemini prompt input field
self.gemini_temperature_input_field, ## gemini temperature input field
self.gemini_top_p_input_field, ## gemini top p input field
self.gemini_top_k_input_field, ## gemini top k input field
self.gemini_candidate_count_input_field, ## gemini candidate count input field
self.gemini_stream_input_field, ## gemini stream input field
self.gemini_stop_sequences_input_field, ## gemini stop sequences input field
self.gemini_max_output_tokens_input_field])
##-------------------start-of-logging_tab.select()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.logging_tab.select(fetch_debug_log_content,
inputs=[],
outputs=[self.debug_log_output_field_log_tab, self.error_log])
##-------------------start-of-save_to_file_indexed_text_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_indexed_text.click(lambda text: text, ## save text as is
inputs=[self.indexing_output_field], ## input text to save
outputs=[], ## no outputs
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "indexed_text.txt")
)
##-------------------start-of-save_to_file_indexing_results_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_indexing_results.click(lambda text: text, ## save text as is
inputs=[self.indexing_results_output_field], ## input text to save
outputs=[], ## no outputs
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "indexing_results.txt")
)
##-------------------start-of-save_to_file_indexing_debug_log_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_debug_log_indexing_tab.click(lambda text: text, ## save text as is
inputs=[self.debug_log_output_field_indexing_tab], ## input text to save
outputs=[], ## no outputs
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "indexing_debug_log.txt")
)
##-------------------start-of-save_to_file_preprocessing_results_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_preprocessed_text.click(lambda text: text, ## save text as is
inputs=[self.preprocess_output_field],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "preprocessed_text.txt")
)
##-------------------start-of-save_to_file_preprocessing_results_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_preprocessing_results.click(lambda text: text, ## save text as is
inputs=[self.preprocessing_results_output_field],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "preprocessing_results.txt")
)
##-------------------start-of-save_to_file_debug_log_processing_tab_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_debug_log_preprocessing_tab.click(lambda text: text, ## save text as is
inputs=[self.debug_log_output_field_preprocess_tab],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "processing_debug_log.txt")
)
##-------------------start-of-save_to_file_kaiseki_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_kaiseki.click(lambda text: text, ## save text as is
inputs=[self.output_field_kaiseki],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "translated_text.txt")
)
##-------------------start-of-save_to_file_je_check_text_kaiseki_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_je_check_text_kaiseki.click(lambda text: text, ## save text as is
inputs=[self.kaiseki_je_check_text_field],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "je_check_text.txt")
)
##-------------------start-of-save_to_file_debug_log_kaiseki_tab_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_debug_log_kaiseki_tab.click(lambda text: text, ## save text as is
inputs=[self.debug_log_output_field_kaiseki_tab],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "debug_log.txt")
)
##-------------------start-of-save_to_file_kijiku_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_kijiku.click(lambda text: text, ## save text as is
inputs=[self.kijiku_translated_text_output_field],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "translated_text.txt")
)
##-------------------start-of-save_to_file_je_check_text_kijiku_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_je_check_text_kijiku.click(lambda text: text, ## save text as is
inputs=[self.kijiku_je_check_text_field],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "je_check_text.txt")
)
##-------------------start-of-save_to_file_debug_log_kijiku_tab_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_debug_log_kijiku_tab.click(lambda text: text, ## save text as is
inputs=[self.debug_log_output_field_kijiku_tab],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "debug_log.txt")
)
##-------------------start-of-save_to_file_debug_log_logging_tab_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_debug_log_logging_tab.click(lambda text: text, ## save text as is
inputs=[self.debug_log_output_field_log_tab],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "debug_log_all.txt")
)
##-------------------start-of-save_to_file_error_log_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.save_to_file_error_log.click(lambda text: text, ## save text as is
inputs=[self.error_log],
outputs=[],
## javascript code that allows us to save textbox contents to a file
js=(self.save_as_js).replace("downloaded_text.txt", "error_log.txt")
)
##-------------------start-of-send_to_x_click()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
self.send_to_kairyou.click(fn=send_to_kairyou,
inputs=[self.indexing_output_field],
outputs=[self.input_text_kairyou])
self.send_to_kaiseki.click(fn=send_to_kaiseki,
inputs=[self.preprocess_output_field],
outputs=[self.input_text_kaiseki])
self.send_to_kijiku.click(fn=send_to_kijiku,
inputs=[self.preprocess_output_field],
outputs=[self.input_text_kijiku])
##-------------------start-of-launch()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
def launch(self):
"""
Launches the GUI.
"""
Kudasai.boot()
GuiJsonUtil.current_kijiku_rules = JsonHandler.current_kijiku_rules
self.build_gui()
self.gui.queue().launch(inbrowser=True, show_error=True, show_api=False, favicon_path=FileEnsurer.favicon_path)
##-------------------start-of-main()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
if(__name__ == '__main__'):
try:
kudasai_gui = KudasaiGUI()
kudasai_gui.launch()
Logger.push_batch()
except Exception as e:
FileEnsurer.handle_critical_exception(e)
|