pushing everything fr
Browse files- .gitignore +106 -0
- LICENSE.md +674 -0
- README.md +294 -13
- app.py +0 -0
- custom_classes/messages.py +54 -0
- demo/cote_replacements.json +207 -0
- demo/demo_sample_text.txt +4 -0
- handlers/json_handler.py +524 -0
- jsons/86_replacements.json +39 -0
- jsons/blank_replacements.json +39 -0
- jsons/cote_replacements.json +206 -0
- jsons/misfit_replacements.json +139 -0
- jsons/rezero_replacements.json +545 -0
- jsons/teis_replacements.json +218 -0
- jsons/tensura_replacements.json +114 -0
- kudasai.py +409 -0
- lib/gui/Kudasai_Logo.png +0 -0
- models/kaiseki.py +572 -0
- models/kijiku.py +1154 -0
- modules/common/decorators.py +36 -0
- modules/common/exceptions.py +59 -0
- modules/common/file_ensurer.py +460 -0
- modules/common/logger.py +132 -0
- modules/common/toolkit.py +255 -0
- modules/gui/gui_file_util.py +42 -0
- modules/gui/gui_json_util.py +89 -0
- requirements.txt +7 -0
- translation_services/deepl_service.py +85 -0
- translation_services/gemini_service.py +215 -0
- translation_services/openai_service.py +180 -0
- util/openai_model_info/openai_chat_model_info.csv +17 -0
- util/openai_model_info/openai_chat_model_info.pdf +0 -0
- util/openai_model_info/openai_chat_model_info.xlsx +0 -0
- util/openai_model_info/webpage/openai_chat_model_info.html +2 -0
- util/openai_model_info/webpage/resources/sheet.css +0 -0
- util/token_counter.py +111 -0
.gitignore
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
## C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
## Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib64/
|
18 |
+
parts/
|
19 |
+
sdist/
|
20 |
+
var/
|
21 |
+
wheels/
|
22 |
+
share/python-wheels/
|
23 |
+
*.egg-info/
|
24 |
+
.installed.cfg
|
25 |
+
*.egg
|
26 |
+
|
27 |
+
## PyInstaller
|
28 |
+
## Usually these files are written by a python script from a template
|
29 |
+
## before PyInstaller builds the exe, so as to inject date/other infos into it.
|
30 |
+
*.manifest
|
31 |
+
*.spec
|
32 |
+
|
33 |
+
## Installer logs
|
34 |
+
pip-log.txt
|
35 |
+
pip-delete-this-directory.txt
|
36 |
+
|
37 |
+
## Unit test / coverage reports
|
38 |
+
htmlcov/
|
39 |
+
.tox/
|
40 |
+
.nox/
|
41 |
+
.coverage
|
42 |
+
.coverage.*
|
43 |
+
.cache
|
44 |
+
nosetests.xml
|
45 |
+
coverage.xml
|
46 |
+
*.cover
|
47 |
+
*.py,cover
|
48 |
+
.hypothesis/
|
49 |
+
.pytest_cache/
|
50 |
+
|
51 |
+
## Jupyter Notebook
|
52 |
+
.ipynb_checkpoints
|
53 |
+
|
54 |
+
## IPython
|
55 |
+
profile_default/
|
56 |
+
ipython_config.py
|
57 |
+
|
58 |
+
## Environment directories
|
59 |
+
.env
|
60 |
+
.venv
|
61 |
+
env/
|
62 |
+
venv/
|
63 |
+
ENV/
|
64 |
+
env.bak/
|
65 |
+
venv.bak/
|
66 |
+
|
67 |
+
## Spyder project settings
|
68 |
+
.spyderproject
|
69 |
+
.spyproject
|
70 |
+
|
71 |
+
## Rope project settings
|
72 |
+
.ropeproject
|
73 |
+
|
74 |
+
## mkdocs documentation
|
75 |
+
/site
|
76 |
+
|
77 |
+
## mypy
|
78 |
+
.mypy_cache/
|
79 |
+
.dmypy.json
|
80 |
+
dmypy.json
|
81 |
+
|
82 |
+
## Pyre type checker
|
83 |
+
.pyre/
|
84 |
+
|
85 |
+
## VS Code settings
|
86 |
+
.vscode/
|
87 |
+
|
88 |
+
## PyCharm settings
|
89 |
+
.idea/
|
90 |
+
|
91 |
+
## Directories used by popular Python packages and tools
|
92 |
+
__pypackages__/
|
93 |
+
|
94 |
+
## Rules for KiJiKu
|
95 |
+
kijiku_rules.json
|
96 |
+
|
97 |
+
## Output files
|
98 |
+
output/
|
99 |
+
output.zip
|
100 |
+
|
101 |
+
## Visual Studio shit
|
102 |
+
.vs/slnx.sqlite-journal
|
103 |
+
.vs/slnx.sqlite
|
104 |
+
.vs/ProjectSettings.json
|
105 |
+
.vs/VSWorkspaceState.json
|
106 |
+
.vs/Kudasai/v17/.wsuo
|
LICENSE.md
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
@@ -1,13 +1,294 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
2 |
+
**Table of Contents**
|
3 |
+
|
4 |
+
- [Notes](#notes)
|
5 |
+
- [Dependencies](#dependencies)
|
6 |
+
- [Quick Start](#quick-start)
|
7 |
+
- [Naming Conventions](#naming-conventions)
|
8 |
+
- [Kairyou](#kairyou)
|
9 |
+
- [Kaiseki](#kaiseki)
|
10 |
+
- [Kijiku](#kijiku)
|
11 |
+
- [Kijiku Settings](#kijiku-settings)
|
12 |
+
- [Web GUI](#webgui)
|
13 |
+
- [License](#license)
|
14 |
+
- [Contact](#contact)
|
15 |
+
|
16 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
17 |
+
**Notes**<a name="notes"></a>
|
18 |
+
|
19 |
+
Windows 10 and Linux Mint are the only tested operating systems, feel free to test on other operating systems and report back to me. I will do my best to fix any issues that arise.
|
20 |
+
|
21 |
+
Python version: 3.8+
|
22 |
+
|
23 |
+
Used to make (Japanese - English) translation easier by preprocessing the Japanese text (optional auto translation using deepL/openai API).
|
24 |
+
|
25 |
+
Preprocessor is sourced from an external package, which I also designed, called [Kairyou](https://github.com/Bikatr7/Kairyou).
|
26 |
+
|
27 |
+
Kudasai has a public trello board, you can find it [here](https://trello.com/b/Wsuwr24S/kudasai) to see what I'm working on.
|
28 |
+
|
29 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
30 |
+
**Dependencies**<a name="dependencies"></a>
|
31 |
+
|
32 |
+
deepl==1.16.1
|
33 |
+
|
34 |
+
openai==1.13.3
|
35 |
+
|
36 |
+
backoff==2.2.1
|
37 |
+
|
38 |
+
tiktoken==0.6.0
|
39 |
+
|
40 |
+
gradio==4.19.2
|
41 |
+
|
42 |
+
kairyou==1.4.0
|
43 |
+
|
44 |
+
google-generativeai==0.4.0
|
45 |
+
|
46 |
+
or see requirements.txt
|
47 |
+
|
48 |
+
Also requires spacy's ja_core_news_lg model, which can be installed via the following command:
|
49 |
+
|
50 |
+
```bash
|
51 |
+
python -m spacy download ja_core_news_lg
|
52 |
+
```
|
53 |
+
|
54 |
+
or on Linux
|
55 |
+
|
56 |
+
```bash
|
57 |
+
python3 -m spacy download ja_core_news_lg
|
58 |
+
```
|
59 |
+
|
60 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
61 |
+
**Quick Start**<a name="quick-start"></a>
|
62 |
+
|
63 |
+
Windows is assumed for the rest of this README, but the process should be similar for Linux.
|
64 |
+
|
65 |
+
Due to TOML's limitations, you need to install spacy's JP Model, which can not be included automatically due to it being a direct dependency link. Make sure you do this after installing the requirements.txt file.
|
66 |
+
|
67 |
+
```bash
|
68 |
+
python -m spacy download ja_core_news_lg
|
69 |
+
```
|
70 |
+
|
71 |
+
Simply run Kudasai.py, enter a txt file path to the text you wish to translate, and then insert a replacement json file path if you wish to use one. If you do not wish to use a replacement json file, you can simply input a blank space and Kudasai will skip preprocessing and go straight to translation.
|
72 |
+
|
73 |
+
Kudasai will offer to index the text, which is useful for finding new names to add to the replacement json file. This is optional and can be skipped.
|
74 |
+
|
75 |
+
Can also run webgui.py for a web gui which is simpler and non-linear.
|
76 |
+
|
77 |
+
After preprocessing is completed (if triggered), you will be prompted to run the translation modules.
|
78 |
+
|
79 |
+
I recommend using Kijiku as it is vastly superior.
|
80 |
+
|
81 |
+
See the [Kijiku Settings](#kijiku-settings) section for more information on Kijiku's settings, but default should run fine. Inside the demo folder is a copy of the settings I use to translate COTE should you wish to use them. There is also a demo txt file in the demo folder that you can use to test Kudasai.
|
82 |
+
|
83 |
+
Follow the prompts from there and you should be good to go, results will be stored in the output folder in the same directory as kudasai.py.
|
84 |
+
|
85 |
+
If you have any questions, comments, or concerns, please feel free to open an issue.
|
86 |
+
|
87 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
88 |
+
**Naming Conventions**<a name="naming-conventions"></a>
|
89 |
+
|
90 |
+
kudasai.py - Main script - ください - Please
|
91 |
+
|
92 |
+
Kairyou - Preprocessing Package - 改良 - Reform
|
93 |
+
|
94 |
+
kaiseki.py - DeepL translation module - 解析 - Parsing
|
95 |
+
|
96 |
+
kijiku.py - OpenAI translation module - 基軸 - Foundation
|
97 |
+
|
98 |
+
Kudasai gets it's original name idea from it's inspiration, Atreyagaurav's Onegai. Which also means please. You can find that [here](https://github.com/Atreyagaurav/onegai)
|
99 |
+
|
100 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
101 |
+
|
102 |
+
**Kairyou**<a name="kairyou"></a>
|
103 |
+
|
104 |
+
Kairyou is the preprocessing package, it is used to preprocess Japanese text to make it easier to translate. It is the first step taken when running Kudasai.
|
105 |
+
|
106 |
+
To run Kairyou and by extension Kudasai, you may use the CLI or the Console.
|
107 |
+
|
108 |
+
You can run the console by simply clicking on kudasai.py, this will open the console and you can follow the prompts from there.
|
109 |
+
|
110 |
+
If you wish to use the CLI, you can do so by opening a command prompt and entering the following:
|
111 |
+
|
112 |
+
```python Path to Kudasai.py Path to the text you are preprocessing Path to the replacement json file```
|
113 |
+
|
114 |
+
i.e.
|
115 |
+
|
116 |
+
Path to Kudasai.py
|
117 |
+
|
118 |
+
Path to the text you are preprocessing
|
119 |
+
|
120 |
+
Path to the replacement json file
|
121 |
+
|
122 |
+
You can omit the replacement json file if you do not wish to use one. This will skip preprocessing and go straight to translation.
|
123 |
+
|
124 |
+
See an example of a command line entry below
|
125 |
+
|
126 |
+
![Example CMD](https://i.imgur.com/eQmVaYY.png)
|
127 |
+
|
128 |
+
Many replacement json files are included in the jsons folder, you can also make your own if you wish provided it follows the same format. See an example below
|
129 |
+
Kudasai/Kairyou works with both Kudasai and Fukuin Json's, the below is a Kudasai type json.
|
130 |
+
|
131 |
+
![Example JSON](https://i.imgur.com/u3FnUia.jpg)
|
132 |
+
|
133 |
+
Upon Kudasai being run, it will create a folder called "output" which will contain 5 files. It is located in the same directory as kudasai.py.
|
134 |
+
|
135 |
+
Old runs are stored in the archive folder in output as well.
|
136 |
+
|
137 |
+
These files are:
|
138 |
+
|
139 |
+
"debug_log.txt" : A log of crucial information that occurred during Kudasai's run, useful for debugging or reporting issues as well as seeing what was done.
|
140 |
+
|
141 |
+
"error_log.txt" : A log of errors that occurred during Kudasai's run if any, useful for debugging or reporting issues.
|
142 |
+
|
143 |
+
"je_check_text.txt" : A log of the Japanese and English sentences that were paired together, useful for checking the accuracy of the translation and further editing of a machine translation.
|
144 |
+
|
145 |
+
"preprocessed_text.txt" : The preprocessed text, the text output by Kairyou (preprocessor).
|
146 |
+
|
147 |
+
"preprocessing_results.txt" : A log of the results of the preprocessing, shows what was replaced and how many times.
|
148 |
+
|
149 |
+
"translated_text.txt" : The translated text, the text output by Kaiseki or Kijiku.
|
150 |
+
|
151 |
+
Kairyou will ask if you'd like to index the text, this is useful for finding new names to add to the replacement json file. If you select 1 for yes, you need to provide a knowledge base, this can either be txt, a path to a txt file, or a path to a folder containing txt files. Kairyou will then index the all three sources and Kudasai will flag all new names with >>><<< in the preprocessed text.
|
152 |
+
|
153 |
+
After preprocessing is completed, you will be prompted to run a translation module. If you choose to do so, you will be prompted to choose between Kaiseki and Kijiku. See the sections below for more information on each translation module.
|
154 |
+
|
155 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
156 |
+
|
157 |
+
**Kaiseki**<a name="kaiseki"></a>
|
158 |
+
|
159 |
+
Kaiseki is the DeepL translation module, it is used to translate Japanese to English. It is *flawed* and not very accurate compared to Kijiku although it is still useful for some things.
|
160 |
+
|
161 |
+
Kaiseki is effectively deprecated and is only maintained. Do not expect any updates to it anytime soon other than bug fixes or compatibility updates.
|
162 |
+
|
163 |
+
Please note an API key is required for Kaiseki to work, you can get one here: https://www.deepl.com/pro#developer.
|
164 |
+
|
165 |
+
It is free under 500k characters per month.
|
166 |
+
|
167 |
+
If you accept the prompt and choose '1' to run Kaiseki, you will be prompted to enter your api key. Provided all goes well, Kaiseki will run and translate the preprocessed text and no other input is required.
|
168 |
+
|
169 |
+
Your translated text will be stored in the output folder in the same directory as kudasai.py.
|
170 |
+
|
171 |
+
Kaiseki will store your obfuscated api key locally under KudasaiSecrets under %APPDATA% or ~/.config/ depending on your OS.
|
172 |
+
|
173 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
174 |
+
|
175 |
+
**Kijiku**<a name="kijiku"></a>
|
176 |
+
|
177 |
+
Kijiku is the OpenAI translation module, it is used to translate Japanese to English. It is very accurate and is the recommended translation module.
|
178 |
+
|
179 |
+
You also need an api key for Kijiku to work, you can get one here: https://platform.openai.com/
|
180 |
+
|
181 |
+
Currently, you can get a free API trial credit that lasts for a month and is worth around 15 dollars.
|
182 |
+
|
183 |
+
Kijiku is vastly more complicated and has a lot of steps, so let's go over them.
|
184 |
+
|
185 |
+
Provided you accept the prompt and choose '2' to run Kijiku, you will be prompted to enter your API key. Provided all goes well, Kijiku will attempt to load it's settings from KudasaiConfig, if it cannot find them, it will create them. Kijiku will store your obfuscated api key locally under KudasaiSecrets under %APPDATA% or ~/.config/ depending on your OS.
|
186 |
+
|
187 |
+
You will be prompted if you'd like to change these settings, if you choose to do so, you'll be asked for which setting you'd like to change, and what to change it too, until you choose to exit. Multiple things can be done in this menu, so follow the prompts. If you want to change anything about the settings, you do it here.
|
188 |
+
|
189 |
+
You can also choose to upload your own settings file in the settings change menu, this is useful if you want to use someone else's settings file. You would do so by placing the json file in the same directory as kudasai.py and then selecting 'c' in the settings change menu. This will load the file in and use it as your settings instead.
|
190 |
+
|
191 |
+
You can change your api key right after this step if you wish.
|
192 |
+
|
193 |
+
After that you will be shown an estimated cost of translation, this is based on the number of tokens in the preprocessed text as determined by tiktoken. Kijiku will then prompt for confirmation, run, and translate the preprocessed text and no other input is required.
|
194 |
+
|
195 |
+
Your translated text will be stored in the output folder in the same directory as kudasai.py.
|
196 |
+
|
197 |
+
Also note that Kijiku's settings are somewhat complex, please see the section below for more information on them if you wish to change them.
|
198 |
+
|
199 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
200 |
+
|
201 |
+
**Kijiku Settings**<a name="kijiku-settings"></a>
|
202 |
+
|
203 |
+
(Fairly technical, can be abstracted away by using default settings or someone else's settings file.)
|
204 |
+
|
205 |
+
See https://platform.openai.com/docs/api-reference/chat/create for further details
|
206 |
+
|
207 |
+
----------------------------------------------------------------------------------
|
208 |
+
model : ID of the model to use. As of right now, Kijiku only works with 'chat' models.
|
209 |
+
|
210 |
+
system_message : Instructions to the model. Basically tells the model what to do.
|
211 |
+
|
212 |
+
temp : 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.
|
213 |
+
|
214 |
+
top_p : 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.
|
215 |
+
|
216 |
+
n : How many chat completion choices to generate for each input message. Do not change this.
|
217 |
+
|
218 |
+
stream : 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.
|
219 |
+
|
220 |
+
stop : Up to 4 sequences where the API will stop generating further tokens. Do not change this.
|
221 |
+
|
222 |
+
logit_bias : Modifies the likelihood of specified tokens appearing in the completion. Do not change this.
|
223 |
+
|
224 |
+
max_tokens : 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.
|
225 |
+
|
226 |
+
presence_penalty : 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.
|
227 |
+
|
228 |
+
frequency_penalty : 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.
|
229 |
+
|
230 |
+
message_mode : 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.
|
231 |
+
|
232 |
+
num_lines : 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.
|
233 |
+
|
234 |
+
sentence_fragmenter_mode : 1 or 2 or 3 (1 - via regex and other nonsense, 2 - NLP via spacy (depreciated, will default to 3 if you select 2), 3 - 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 3 for gpt-4.
|
235 |
+
|
236 |
+
je_check_mode : 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 gpt-4.
|
237 |
+
|
238 |
+
num_malformed_batch_retries : How many times Kijiku will attempt to mend a malformed batch, only for gpt4. Be careful with increasing as cost increases at (cost * length * n) at worst case.
|
239 |
+
|
240 |
+
batch_retry_timeout : How long Kijiku will try to translate a batch in seconds, if a requests exceeds this duration, Kijiku will leave it untranslated.
|
241 |
+
|
242 |
+
num_concurrent_batches : How many translations batches Kijiku will send to OpenAI at a time.
|
243 |
+
----------------------------------------------------------------------------------
|
244 |
+
stream, logit_bias, stop and n are included for legacy purposes, current versions of Kudasai will hardcode their values when validating the Kijiku_rule.json to their default values.
|
245 |
+
|
246 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
247 |
+
|
248 |
+
**Web GUI**<a name="webgui"></a>
|
249 |
+
|
250 |
+
Kudasai also offers a Web GUI. It has all the main functionality of the program but in an easier and non-linear way.
|
251 |
+
|
252 |
+
To run the Web GUI, simply run webgui.py in the same directory as kudasai.py
|
253 |
+
|
254 |
+
Below are some images of the Web GUI.
|
255 |
+
|
256 |
+
Indexing | Kairyou:
|
257 |
+
![Indexing Screen | Kairyou](https://i.imgur.com/7HCdLt6.png)
|
258 |
+
|
259 |
+
Preprocessing | Kairyou:
|
260 |
+
![Preprocessing Screen | Kairyou](https://i.imgur.com/1qcPpeP.jpg)
|
261 |
+
|
262 |
+
Translation | Kaiseki:
|
263 |
+
![Translation Screen | Kaiseki](https://i.imgur.com/U9GBaLw.jpg)
|
264 |
+
|
265 |
+
Translation | Kijiku:
|
266 |
+
![Translation Screen | Kijiku](https://i.imgur.com/nySRp9y.jpg)
|
267 |
+
|
268 |
+
Kijiku Settings:
|
269 |
+
![Kijiku Settings](https://i.imgur.com/42IZYIz.jpg)
|
270 |
+
|
271 |
+
Logging:
|
272 |
+
![Logging](https://i.imgur.com/c9LmkPR.jpg)
|
273 |
+
|
274 |
+
API Keys above are dead, so no worries on that end.
|
275 |
+
|
276 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
277 |
+
**License**<a name="license"></a>
|
278 |
+
|
279 |
+
This project (Kudasai) is licensed under the GNU General Public License (GPL). You can find the full text of the license in the [LICENSE](License.md) file.
|
280 |
+
|
281 |
+
The GPL is a copyleft license that promotes the principles of open-source software. It ensures that any derivative works based on this project must also be distributed under the same GPL license. This license grants you the freedom to use, modify, and distribute the software.
|
282 |
+
|
283 |
+
Please note that this information is a brief summary of the GPL. For a detailed understanding of your rights and obligations under this license, please refer to the full license text.
|
284 |
+
|
285 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
286 |
+
**Contact**<a name="contact"></a>
|
287 |
+
|
288 |
+
If you have any questions, comments, or concerns, please feel free to contact me at [Tetralon07@gmail.com](mailto:Tetralon07@gmail.com).
|
289 |
+
|
290 |
+
For any bugs or suggestions please use the issues tab [here](https://github.com/Bikatr7/Kudasai/issues).
|
291 |
+
|
292 |
+
Once again, I actively encourage and welcome any feedback on this project.
|
293 |
+
|
294 |
+
---------------------------------------------------------------------------------------------------------------------------------------------------
|
app.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
custom_classes/messages.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
##-------------------start-of-Message--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
2 |
+
|
3 |
+
class Message:
|
4 |
+
|
5 |
+
"""
|
6 |
+
|
7 |
+
Message is a class that is used to send translation batches to the OpenAI API.
|
8 |
+
|
9 |
+
"""
|
10 |
+
|
11 |
+
def __init__(self, content: str):
|
12 |
+
self._content = content
|
13 |
+
|
14 |
+
@property
|
15 |
+
def role(self):
|
16 |
+
raise NotImplementedError
|
17 |
+
|
18 |
+
@property
|
19 |
+
def content(self):
|
20 |
+
return self._content
|
21 |
+
|
22 |
+
def to_dict(self):
|
23 |
+
return {
|
24 |
+
'role': self.role,
|
25 |
+
'content': self.content
|
26 |
+
}
|
27 |
+
|
28 |
+
##-------------------start-of-SystemTranslationMessage--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
29 |
+
|
30 |
+
class SystemTranslationMessage(Message):
|
31 |
+
|
32 |
+
"""
|
33 |
+
|
34 |
+
SystemTranslationMessage is a class that is used to send the system message to the OpenAI API.
|
35 |
+
|
36 |
+
"""
|
37 |
+
|
38 |
+
@property
|
39 |
+
def role(self):
|
40 |
+
return 'system'
|
41 |
+
|
42 |
+
##-------------------start-of-ModelTranslationMessage--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
43 |
+
|
44 |
+
class ModelTranslationMessage(Message):
|
45 |
+
|
46 |
+
"""
|
47 |
+
|
48 |
+
ModelTranslationMessage is a class that is used to send the model/user message to the OpenAI API.
|
49 |
+
|
50 |
+
"""
|
51 |
+
|
52 |
+
@property
|
53 |
+
def role(self):
|
54 |
+
return 'user'
|
demo/cote_replacements.json
ADDED
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
{
|
3 |
+
"honorifics": {
|
4 |
+
"ちゃん": "chan",
|
5 |
+
"殿": "dono",
|
6 |
+
"どの": "dono",
|
7 |
+
"くん": "kun",
|
8 |
+
"君": "kun",
|
9 |
+
"後輩": "kōhai",
|
10 |
+
"こうはい": "kōhai",
|
11 |
+
"様": "sama",
|
12 |
+
"さま": "sama",
|
13 |
+
"さん": "san",
|
14 |
+
"先輩": "senpai",
|
15 |
+
"せんぱい": "senpai",
|
16 |
+
"先生": "sensei",
|
17 |
+
"せんせい": "sensei",
|
18 |
+
"氏": "shi",
|
19 |
+
"し": "shi",
|
20 |
+
"上": "ue",
|
21 |
+
"うえ": "ue"
|
22 |
+
|
23 |
+
},
|
24 |
+
|
25 |
+
"single_words": {
|
26 |
+
"β": "Beta",
|
27 |
+
"後輩":"kōhai",
|
28 |
+
"先輩":"senpai"
|
29 |
+
|
30 |
+
},
|
31 |
+
|
32 |
+
"unicode": {
|
33 |
+
"\u2026":"...",
|
34 |
+
"\u3000": " "
|
35 |
+
},
|
36 |
+
|
37 |
+
"phrases": {
|
38 |
+
"高度育成高等学校": "Advanced Nurturing High School",
|
39 |
+
"高育" : "ANHS",
|
40 |
+
"ケヤキモール" : "Keyaki Mall",
|
41 |
+
"プロテクトポイント": "Protection Point",
|
42 |
+
"東京都高度育成高等学校":"Tokyo Metropolitan Advanced Nurturing High School"
|
43 |
+
},
|
44 |
+
|
45 |
+
"kutouten": {
|
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 |
+
"name_like": {
|
72 |
+
|
73 |
+
},
|
74 |
+
|
75 |
+
"single_names": {
|
76 |
+
"Akiyama": ["秋山"],
|
77 |
+
"Anzai": ["安在"],
|
78 |
+
"Ijūin": ["伊集院"],
|
79 |
+
"Ishida": ["石田"],
|
80 |
+
"Isoyama": ["磯山"],
|
81 |
+
"Keisei": ["啓誠"],
|
82 |
+
"Kijima": ["鬼島"],
|
83 |
+
"Kisarazu": ["木更津"],
|
84 |
+
"Kinugasa" :["衣笠"],
|
85 |
+
"Mii": ["みー"],
|
86 |
+
"Mika": ["美香"],
|
87 |
+
"Namekawa": ["滑川"],
|
88 |
+
"Ohba": ["大場"],
|
89 |
+
"Satonaka": ["里中"],
|
90 |
+
"Shiro": ["志朗"],
|
91 |
+
"Sonezaki": ["曽根崎"],
|
92 |
+
"Sōya": ["宗谷"],
|
93 |
+
"Sugio": ["杉尾"],
|
94 |
+
"Tomose":["トモセ"],
|
95 |
+
"Yano": ["矢野"],
|
96 |
+
"king": ["Wan-sama"]
|
97 |
+
},
|
98 |
+
|
99 |
+
|
100 |
+
"full_names": {
|
101 |
+
"Amasawa Ichika": ["天沢","一夏"],
|
102 |
+
"Amikura Mako": ["網倉","麻子"],
|
103 |
+
"Andō Sayo" : ["安藤","紗代"],
|
104 |
+
"Asahina Nazuna": ["朝比奈","なずな"],
|
105 |
+
"Asama Hisashi": ["浅間","久"],
|
106 |
+
"Ayanokōji Atsuomi": ["綾小路","篤臣"],
|
107 |
+
"Ayanokōji Kiyotaka": ["綾小路","清隆"],
|
108 |
+
"Azuma Sana": ["東","咲菜"],
|
109 |
+
"Chabashira Sae": ["茶柱","佐枝"],
|
110 |
+
"Enoshima Midoriko":["榎嶋","翠子"],
|
111 |
+
"Fukuchi Hinano": ["福地陽","菜乃"],
|
112 |
+
"Hamaguchi Tetsuya": ["浜口","哲也"],
|
113 |
+
"Hagiwara Chihaya": ["萩原","千颯"],
|
114 |
+
"Hasebe Haruka": ["長谷部","波瑠加"],
|
115 |
+
"Hashimoto Masayoshi": ["橋本","正義"],
|
116 |
+
"Himeno Yuki":["姫野","ユキ"],
|
117 |
+
"Hirata Yōsuke": ["平田","洋介"],
|
118 |
+
"Hondō Ryōtarō": ["本堂","遼太郎"],
|
119 |
+
"Horikita Manabu": ["堀北","学"],
|
120 |
+
"Horikita Suzune": ["堀北","鈴音"],
|
121 |
+
"Hoshinomiya Chie": ["星之宮","知恵"],
|
122 |
+
"Hōsen Kazuomi": ["宝泉","和臣"],
|
123 |
+
"Ibuki Mio": ["伊吹","澪"],
|
124 |
+
"Ichinose Honami": ["一之瀬","帆波"],
|
125 |
+
"Iguchi Yuri": ["井口","由里"],
|
126 |
+
"Ike Kanji": ["池","寛治"],
|
127 |
+
"Inogashira Kokoro": ["井の頭","心"],
|
128 |
+
"Ishigami Kyō" : ["石上" , "京"],
|
129 |
+
"Ishizaki Daichi": ["石崎","大地"],
|
130 |
+
"Isomaru Yōkō": ["磯丸","容幸"],
|
131 |
+
"Kamogawa Toshizō": ["鴨川","俊三"],
|
132 |
+
"Kamuro Masumi": ["神室","真澄"],
|
133 |
+
"Kaneda Satoru": ["金田","悟"],
|
134 |
+
"Kanzaki Ryūji": ["神崎","隆二"],
|
135 |
+
"Karuizawa Kei": ["軽井沢","恵"],
|
136 |
+
"Katsuragi Kōhei": ["葛城","康平"],
|
137 |
+
"Kikyō Kushida": ["桔梗","櫛田"],
|
138 |
+
"Kinoshita Minori" : ["木下","美野里"],
|
139 |
+
"Kiriyama Ikuto": ["桐山","生叶"],
|
140 |
+
"Kiryūin Fūka": ["鬼龍院","楓花"],
|
141 |
+
"Kitō Hayato": ["鬼頭","隼"],
|
142 |
+
"Kobashi Yume": ["小橋","夢"],
|
143 |
+
"Komiya Kyōgo": ["小宮","叶吾"],
|
144 |
+
"Kondō Reo": ["近藤","玲音"],
|
145 |
+
"Kōenji Rokusuke": ["高円寺","六助"],
|
146 |
+
"Kōji Machida": ["浩二","町田"],
|
147 |
+
"Kusuda Yukitsu": ["楠田","ゆきつ"],
|
148 |
+
"Manabe Shiho": ["真鍋","志保"],
|
149 |
+
"Mashima Tomonari": ["真嶋","智也"],
|
150 |
+
"Matsushita Chiaki": ["松下","千秋"],
|
151 |
+
"Miyake Akito": ["三宅","明人"],
|
152 |
+
"Miyamoto Sōshi":["宮本","蒼士"],
|
153 |
+
"Mori Nene": ["森","寧々"],
|
154 |
+
"Morishita Ai": ["森下","藍"],
|
155 |
+
"Morofuji Rika" : ["諸藤","リカ"],
|
156 |
+
"Nagumo Miyabi": ["南雲","雅"],
|
157 |
+
"Nanase Tsubasa": ["七瀬","翼"],
|
158 |
+
"Naoe Jinnosuke": ["直江","仁之助"],
|
159 |
+
"Nishimura Ryūko": ["西村","龍子"],
|
160 |
+
"Nishino Takeko" : ["西野","武子"],
|
161 |
+
"Norihito Watanabe": ["渡辺","紀仁"],
|
162 |
+
"Okitani Kyōsuke": ["沖谷","京介"],
|
163 |
+
"Onodera Kayano": ["小野寺","かや乃"],
|
164 |
+
"Ryūen Kakeru": ["龍園","翔"],
|
165 |
+
"Sakagami Kazuma": ["坂上","数馬"],
|
166 |
+
"Sakayanagi Arisu": ["坂柳","有栖"],
|
167 |
+
"Sakayanagi Narimori": ["坂柳","成守"],
|
168 |
+
"Sakura Airi": ["佐倉","愛里"],
|
169 |
+
"Satō Maya": ["佐藤","麻耶"],
|
170 |
+
"Sanada Kousei": ["真田","康生"],
|
171 |
+
"Sawada Yasumi": ["沢田","恭美"],
|
172 |
+
"Shiba Katsunori": ["司馬","克典"],
|
173 |
+
"Shibata Sō" : ["柴田","颯"],
|
174 |
+
"Shiina Hiyori": ["椎名","ひより"],
|
175 |
+
"Shinohara Satsuki": ["篠原","さつき"],
|
176 |
+
"Shiranami Chihiro": ["白波","千尋"],
|
177 |
+
"Sotomura Hideo": ["外村","秀雄"],
|
178 |
+
"Suchi Moeka": ["須知","萌香"],
|
179 |
+
"Sudō Ken": ["須藤","健"],
|
180 |
+
"Suzukake Tanji": ["鈴懸","鍛治"],
|
181 |
+
"Tachibana Akane": ["橘","茜"],
|
182 |
+
"Tachibana Kento": ["立花","賢人"],
|
183 |
+
"Takahashi Osamu":["高橋","修"],
|
184 |
+
"Tokitō Hiroya": ["時任","裕也"],
|
185 |
+
"Tatewaki Aoi": ["帯刀","碧"],
|
186 |
+
"Totsuka Yahiko": ["戸塚","弥彦"],
|
187 |
+
"Tōdō Rin": ["藤堂","凛"],
|
188 |
+
"Tsubaki Sakurako": ["椿","桜子"],
|
189 |
+
"Tsukishiro Tokinari": ["月城","常成"],
|
190 |
+
"Utomiya Riku": ["宇都宮","陸"],
|
191 |
+
"Wan Mei-Yui": ["王","美雨"],
|
192 |
+
"Yabu Nanami" : ["藪","菜々美"],
|
193 |
+
"Yagami Takuya": ["八神","拓也"],
|
194 |
+
"Yamada Albert": ["山田","アルベルト"],
|
195 |
+
"Yamamura Miki": ["山村","美紀"],
|
196 |
+
"Yamanaka Ikuko": ["山中","郁子"],
|
197 |
+
"Yamashita Saki" : ["鈴代","紗弓"],
|
198 |
+
"Yamashita Naohisa" :[ "山下","直久"],
|
199 |
+
"Yamauchi Haruki": ["山内","春樹"],
|
200 |
+
"Yukimura Teruhiko": ["幸村","輝彦"]
|
201 |
+
},
|
202 |
+
|
203 |
+
"enhanced_check_whitelist": {
|
204 |
+
"Hoshinomiya Chie": ["星之宮","知恵"]
|
205 |
+
}
|
206 |
+
|
207 |
+
}
|
demo/demo_sample_text.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
気が付くと、俺は勉強でもスポーツでも一番だった。
|
2 |
+
気が付くと、俺の周囲には恩恵にあやかろうとする連中がいた。
|
3 |
+
特に努力をしたわけじゃない。
|
4 |
+
同じ時間、同じことを習っても、頭一つ抜けて学習する力があった。
|
handlers/json_handler.py
ADDED
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import json
|
3 |
+
import typing
|
4 |
+
|
5 |
+
## custom modules
|
6 |
+
from modules.common.file_ensurer import FileEnsurer
|
7 |
+
from modules.common.logger import Logger
|
8 |
+
from modules.common.toolkit import Toolkit
|
9 |
+
|
10 |
+
##-------------------start-of-JsonHandler---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
11 |
+
|
12 |
+
class JsonHandler:
|
13 |
+
|
14 |
+
"""
|
15 |
+
|
16 |
+
Handles the Kijiku Rules.json file and interactions with it.
|
17 |
+
|
18 |
+
"""
|
19 |
+
|
20 |
+
current_kijiku_rules = dict()
|
21 |
+
|
22 |
+
kijiku_settings_message = """
|
23 |
+
----------------------------------------------------------------------------------
|
24 |
+
Kijiku Settings:
|
25 |
+
|
26 |
+
prompt_assembly_mode : 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.
|
27 |
+
|
28 |
+
number_of_lines_per_batch : 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.
|
29 |
+
|
30 |
+
sentence_fragmenter_mode : 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.
|
31 |
+
|
32 |
+
je_check_mode : 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.
|
33 |
+
|
34 |
+
number_of_malformed_batch_retries : (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.
|
35 |
+
|
36 |
+
batch_retry_timeout : How long Kijiku will try to translate a batch in seconds, if a requests exceeds this duration, Kijiku will leave it untranslated.
|
37 |
+
|
38 |
+
number_of_concurrent_batches : 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.
|
39 |
+
----------------------------------------------------------------------------------
|
40 |
+
Open AI Settings:
|
41 |
+
See https://platform.openai.com/docs/api-reference/chat/create for further details
|
42 |
+
----------------------------------------------------------------------------------
|
43 |
+
openai_model : ID of the model to use. Kijiku only works with 'chat' models.
|
44 |
+
|
45 |
+
openai_system_message : Instructions to the model. Basically tells the model how to translate.
|
46 |
+
|
47 |
+
openai_temperature : 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.
|
48 |
+
|
49 |
+
openai_top_p : 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.
|
50 |
+
|
51 |
+
openai_n : How many chat completion choices to generate for each input message. Do not change this.
|
52 |
+
|
53 |
+
openai_stream : 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.
|
54 |
+
|
55 |
+
openai_stop : Up to 4 sequences where the API will stop generating further tokens. Do not change this.
|
56 |
+
|
57 |
+
openai_logit_bias : Modifies the likelihood of specified tokens appearing in the completion. Do not change this.
|
58 |
+
|
59 |
+
openai_max_tokens : 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.
|
60 |
+
|
61 |
+
openai_presence_penalty : 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.
|
62 |
+
|
63 |
+
openai_frequency_penalty : 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.
|
64 |
+
----------------------------------------------------------------------------------
|
65 |
+
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.
|
66 |
+
----------------------------------------------------------------------------------
|
67 |
+
Gemini Settings:
|
68 |
+
https://ai.google.dev/docs/concepts#model-parameters for further details
|
69 |
+
----------------------------------------------------------------------------------
|
70 |
+
gemini_model : The model to use. Currently only supports gemini-pro and gemini-pro-vision, the 1.0 model and it's aliases.
|
71 |
+
|
72 |
+
gemini_prompt : Instructions to the model. Basically tells the model how to translate.
|
73 |
+
|
74 |
+
gemini_temperature : 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.
|
75 |
+
|
76 |
+
gemini_top_p : 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.
|
77 |
+
|
78 |
+
gemini_top_k : 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.
|
79 |
+
|
80 |
+
gemini_candidate_count : The number of candidates to generate for each input message. Do not change this.
|
81 |
+
|
82 |
+
gemini_stream : 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. Do not change this.
|
83 |
+
|
84 |
+
gemini_stop_sequences : Up to 4 sequences where the API will stop generating further tokens. Do not change this.
|
85 |
+
|
86 |
+
gemini_max_output_tokens : 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.
|
87 |
+
----------------------------------------------------------------------------------
|
88 |
+
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.
|
89 |
+
----------------------------------------------------------------------------------
|
90 |
+
"""
|
91 |
+
|
92 |
+
##-------------------start-of-validate_json()--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
93 |
+
|
94 |
+
@staticmethod
|
95 |
+
def validate_json() -> None:
|
96 |
+
|
97 |
+
"""
|
98 |
+
|
99 |
+
Validates the Kijiku Rules.json file.
|
100 |
+
|
101 |
+
"""
|
102 |
+
|
103 |
+
base_kijiku_keys = [
|
104 |
+
"prompt_assembly_mode",
|
105 |
+
"number_of_lines_per_batch",
|
106 |
+
"sentence_fragmenter_mode",
|
107 |
+
"je_check_mode",
|
108 |
+
"number_of_malformed_batch_retries",
|
109 |
+
"batch_retry_timeout",
|
110 |
+
"number_of_concurrent_batches"
|
111 |
+
]
|
112 |
+
|
113 |
+
openai_keys = [
|
114 |
+
"openai_model",
|
115 |
+
"openai_system_message",
|
116 |
+
"openai_temperature",
|
117 |
+
"openai_top_p",
|
118 |
+
"openai_n",
|
119 |
+
"openai_stream",
|
120 |
+
"openai_stop",
|
121 |
+
"openai_logit_bias",
|
122 |
+
"openai_max_tokens",
|
123 |
+
"openai_presence_penalty",
|
124 |
+
"openai_frequency_penalty"
|
125 |
+
]
|
126 |
+
|
127 |
+
gemini_keys = [
|
128 |
+
"gemini_model",
|
129 |
+
"gemini_prompt",
|
130 |
+
"gemini_temperature",
|
131 |
+
"gemini_top_p",
|
132 |
+
"gemini_top_k",
|
133 |
+
"gemini_candidate_count",
|
134 |
+
"gemini_stream",
|
135 |
+
"gemini_stop_sequences",
|
136 |
+
"gemini_max_output_tokens"
|
137 |
+
]
|
138 |
+
|
139 |
+
validation_rules = {
|
140 |
+
"prompt_assembly_mode": lambda x: 1 <= x <= 2,
|
141 |
+
"number_of_lines_per_batch": lambda x: x is isinstance(x, int) and x > 0,
|
142 |
+
"sentence_fragmenter_mode": lambda x: 1 <= x <= 2,
|
143 |
+
"je_check_mode": lambda x: 1 <= x <= 2,
|
144 |
+
"number_of_malformed_batch_retries": lambda x: x is isinstance(x, int) and x >= 0,
|
145 |
+
"batch_retry_timeout": lambda x: x is isinstance(x, int) and x >= 0,
|
146 |
+
"number_of_concurrent_batches": lambda x: x is isinstance(x, int) and x >= 0,
|
147 |
+
"openai_model": lambda x: x in FileEnsurer.ALLOWED_OPENAI_MODELS,
|
148 |
+
"openai_system_message": lambda x: x not in ["", "None", None],
|
149 |
+
"openai_temperature": lambda x: 0 <= x <= 2,
|
150 |
+
"openai_top_p": lambda x: 0 <= x <= 1,
|
151 |
+
"openai_max_tokens": lambda x: x is None or isinstance(x, int),
|
152 |
+
"openai_presence_penalty": lambda x: -2 <= x <= 2,
|
153 |
+
"gemini_model": lambda x: x in FileEnsurer.ALLOWED_GEMINI_MODELS,
|
154 |
+
"gemini_prompt": lambda x: x not in ["", "None", None],
|
155 |
+
"gemini_temperature": lambda x: 0 <= x <= 2,
|
156 |
+
"gemini_top_p": lambda x: x is None or 0 <= x <= 2,
|
157 |
+
"gemini_top_k": lambda x: x is None or isinstance(x, int) and x >= 0,
|
158 |
+
"gemini_max_output_tokens": lambda x: x is None or isinstance(x, int),
|
159 |
+
}
|
160 |
+
|
161 |
+
try:
|
162 |
+
## ensure categories are present
|
163 |
+
assert "base kijiku settings" in JsonHandler.current_kijiku_rules
|
164 |
+
assert "openai settings" in JsonHandler.current_kijiku_rules
|
165 |
+
assert "gemini settings" in JsonHandler.current_kijiku_rules
|
166 |
+
|
167 |
+
## assign to variables to reduce repetitive access
|
168 |
+
base_kijiku_settings = JsonHandler.current_kijiku_rules["base kijiku settings"]
|
169 |
+
openai_settings = JsonHandler.current_kijiku_rules["openai settings"]
|
170 |
+
gemini_settings = JsonHandler.current_kijiku_rules["gemini settings"]
|
171 |
+
|
172 |
+
## ensure all keys are present
|
173 |
+
## ensure all keys are present
|
174 |
+
assert all(key in base_kijiku_settings for key in base_kijiku_keys)
|
175 |
+
assert all(key in openai_settings for key in openai_keys)
|
176 |
+
assert all(key in gemini_settings for key in gemini_keys)
|
177 |
+
|
178 |
+
## validate each key using the validation rules
|
179 |
+
for key, validate in validation_rules.items():
|
180 |
+
if(key in openai_settings and not validate(openai_settings[key])):
|
181 |
+
raise ValueError(f"Invalid value for {key}")
|
182 |
+
elif(key in gemini_settings and not validate(gemini_settings[key])):
|
183 |
+
raise ValueError(f"Invalid value for {key}")
|
184 |
+
|
185 |
+
## force stop/logit_bias into None
|
186 |
+
openai_settings["openai_stop"] = None
|
187 |
+
openai_settings["openai_logit_bias"] = None
|
188 |
+
openai_settings["openai_stream"] = False
|
189 |
+
|
190 |
+
gemini_settings["gemini_stop_sequences"] = None
|
191 |
+
gemini_settings["gemini_stream"] = False
|
192 |
+
|
193 |
+
## force n and candidate_count to 1
|
194 |
+
openai_settings["openai_n"] = 1
|
195 |
+
|
196 |
+
gemini_settings["gemini_candidate_count"] = 1
|
197 |
+
|
198 |
+
except Exception as e:
|
199 |
+
Logger.log_action("Kijiku Rules.json is not valid, setting to invalid_placeholder, current:")
|
200 |
+
Logger.log_action(str(JsonHandler.current_kijiku_rules))
|
201 |
+
JsonHandler.current_kijiku_rules = FileEnsurer.INVALID_KIJIKU_RULES_PLACEHOLDER
|
202 |
+
|
203 |
+
Logger.log_action("Kijiku Rules.json is valid, current:")
|
204 |
+
Logger.log_action(str(JsonHandler.current_kijiku_rules))
|
205 |
+
|
206 |
+
##-------------------start-of-reset_kijiku_rules_to_default()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
207 |
+
|
208 |
+
@staticmethod
|
209 |
+
def reset_kijiku_rules_to_default() -> None:
|
210 |
+
|
211 |
+
"""
|
212 |
+
|
213 |
+
Resets the kijiku_rules json to default.
|
214 |
+
|
215 |
+
"""
|
216 |
+
|
217 |
+
JsonHandler.current_kijiku_rules = FileEnsurer.DEFAULT_KIJIKU_RULES
|
218 |
+
|
219 |
+
JsonHandler.dump_kijiku_rules()
|
220 |
+
|
221 |
+
JsonHandler.load_kijiku_rules()
|
222 |
+
|
223 |
+
##-------------------start-of-dump_kijiku_rules()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
224 |
+
|
225 |
+
@staticmethod
|
226 |
+
def dump_kijiku_rules() -> None:
|
227 |
+
|
228 |
+
"""
|
229 |
+
|
230 |
+
Dumps the Kijiku Rules.json file to disk.
|
231 |
+
|
232 |
+
"""
|
233 |
+
|
234 |
+
with open(FileEnsurer.config_kijiku_rules_path, 'w+', encoding='utf-8') as file:
|
235 |
+
json.dump(JsonHandler.current_kijiku_rules, file)
|
236 |
+
|
237 |
+
##-------------------start-of-load_kijiku_rules()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
238 |
+
|
239 |
+
@staticmethod
|
240 |
+
def load_kijiku_rules() -> None:
|
241 |
+
|
242 |
+
"""
|
243 |
+
|
244 |
+
Loads the Kijiku Rules.json file into memory.
|
245 |
+
|
246 |
+
"""
|
247 |
+
|
248 |
+
with open(FileEnsurer.config_kijiku_rules_path, 'r', encoding='utf-8') as file:
|
249 |
+
JsonHandler.current_kijiku_rules = json.load(file)
|
250 |
+
|
251 |
+
##-------------------start-of-print_kijiku_rules()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
252 |
+
|
253 |
+
@staticmethod
|
254 |
+
def print_kijiku_rules(output:bool=False) -> None:
|
255 |
+
|
256 |
+
"""
|
257 |
+
|
258 |
+
Prints the Kijiku Rules.json file to the log.
|
259 |
+
Logs by default, but can be set to print to console as well.
|
260 |
+
|
261 |
+
Parameters:
|
262 |
+
output (bool | optional | default=False) : Whether to print to console as well.
|
263 |
+
|
264 |
+
"""
|
265 |
+
|
266 |
+
print("-------------------")
|
267 |
+
print("Base Kijiku Settings:")
|
268 |
+
print("-------------------")
|
269 |
+
|
270 |
+
for key,value in JsonHandler.current_kijiku_rules["base kijiku settings"].items():
|
271 |
+
Logger.log_action(key + " : " + str(value), output=output, omit_timestamp=output)
|
272 |
+
|
273 |
+
print("-------------------")
|
274 |
+
print("Open AI Settings:")
|
275 |
+
print("-------------------")
|
276 |
+
|
277 |
+
for key,value in JsonHandler.current_kijiku_rules["openai settings"].items():
|
278 |
+
Logger.log_action(key + " : " + str(value), output=output, omit_timestamp=output)
|
279 |
+
|
280 |
+
print("-------------------")
|
281 |
+
print("Gemini Settings:")
|
282 |
+
print("-------------------")
|
283 |
+
|
284 |
+
for key,value in JsonHandler.current_kijiku_rules["gemini settings"].items():
|
285 |
+
Logger.log_action(key + " : " + str(value), output=output, omit_timestamp=output)
|
286 |
+
|
287 |
+
|
288 |
+
##-------------------start-of-change_kijiku_settings()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
289 |
+
|
290 |
+
@staticmethod
|
291 |
+
def change_kijiku_settings() -> None:
|
292 |
+
|
293 |
+
"""
|
294 |
+
|
295 |
+
Allows the user to change the settings of the Kijiku Rules.json file
|
296 |
+
|
297 |
+
"""
|
298 |
+
|
299 |
+
while(True):
|
300 |
+
|
301 |
+
Toolkit.clear_console()
|
302 |
+
|
303 |
+
settings_print_message = JsonHandler.kijiku_settings_message + SettingsChanger.generate_settings_change_menu()
|
304 |
+
|
305 |
+
action = input(settings_print_message).lower()
|
306 |
+
|
307 |
+
if(action == 'q'):
|
308 |
+
break
|
309 |
+
|
310 |
+
## loads a custom json directly
|
311 |
+
if(action == "c"):
|
312 |
+
SettingsChanger.load_custom_json()
|
313 |
+
|
314 |
+
elif(action == "d"):
|
315 |
+
print("Resetting to default settings.")
|
316 |
+
JsonHandler.reset_kijiku_rules_to_default()
|
317 |
+
|
318 |
+
elif(action in JsonHandler.current_kijiku_rules["base kijiku settings"]):
|
319 |
+
SettingsChanger.change_setting("base kijiku settings", action)
|
320 |
+
|
321 |
+
elif(action in JsonHandler.current_kijiku_rules["openai settings"]):
|
322 |
+
SettingsChanger.change_setting("openai settings", action)
|
323 |
+
|
324 |
+
elif(action in JsonHandler.current_kijiku_rules["gemini settings"]):
|
325 |
+
SettingsChanger.change_setting("gemini settings", action)
|
326 |
+
|
327 |
+
else:
|
328 |
+
print("Invalid setting name. Please try again.")
|
329 |
+
|
330 |
+
Toolkit.pause_console("\nPress enter to continue.")
|
331 |
+
|
332 |
+
JsonHandler.dump_kijiku_rules()
|
333 |
+
|
334 |
+
##-------------------start-of-convert_to_correct_type()-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
335 |
+
|
336 |
+
@staticmethod
|
337 |
+
def convert_to_correct_type(setting_name:str, initial_value:str) -> typing.Any:
|
338 |
+
|
339 |
+
"""
|
340 |
+
|
341 |
+
Converts the input string to the correct type based on the setting name.
|
342 |
+
|
343 |
+
Parameters:
|
344 |
+
setting_name (str) : The name of the setting to convert.
|
345 |
+
value (str) : The value to convert.
|
346 |
+
|
347 |
+
Returns:
|
348 |
+
(typing.Any) : The converted value.
|
349 |
+
|
350 |
+
"""
|
351 |
+
|
352 |
+
value = initial_value
|
353 |
+
|
354 |
+
type_expectations = {
|
355 |
+
"prompt_assembly_mode": {"type": int, "constraints": lambda x: 1 <= x <= 2},
|
356 |
+
"number_of_lines_per_batch": {"type": int, "constraints": lambda x: x > 0},
|
357 |
+
"sentence_fragmenter_mode": {"type": int, "constraints": lambda x: 1 <= x <= 2},
|
358 |
+
"je_check_mode": {"type": int, "constraints": lambda x: 1 <= x <= 2},
|
359 |
+
"number_of_malformed_batch_retries": {"type": int, "constraints": lambda x: x >= 0},
|
360 |
+
"batch_retry_timeout": {"type": int, "constraints": lambda x: x >= 0},
|
361 |
+
"number_of_concurrent_batches": {"type": int, "constraints": lambda x: x >= 0},
|
362 |
+
"openai_model": {"type": str, "constraints": lambda x: x in FileEnsurer.ALLOWED_OPENAI_MODELS},
|
363 |
+
"openai_system_message": {"type": str, "constraints": lambda x: x not in ["", "None", None]},
|
364 |
+
"openai_temperature": {"type": float, "constraints": lambda x: 0 <= x <= 2},
|
365 |
+
"openai_top_p": {"type": float, "constraints": lambda x: 0 <= x <= 2},
|
366 |
+
"openai_n": {"type": int, "constraints": lambda x: x == 1},
|
367 |
+
"openai_stream": {"type": bool, "constraints": lambda x: x is False},
|
368 |
+
"openai_stop": {"type": None, "constraints": lambda x: x is None},
|
369 |
+
"openai_logit_bias": {"type": None, "constraints": lambda x: x is None},
|
370 |
+
"openai_max_tokens": {"type": typing.Optional[int], "constraints": lambda x: x is None or isinstance(x, int)},
|
371 |
+
"openai_presence_penalty": {"type": float, "constraints": lambda x: -2 <= x <= 2},
|
372 |
+
"openai_frequency_penalty": {"type": float, "constraints": lambda x: -2 <= x <= 2},
|
373 |
+
"gemini_model": {"type": str, "constraints": lambda x: x in FileEnsurer.ALLOWED_GEMINI_MODELS},
|
374 |
+
"gemini_prompt": {"type": str, "constraints": lambda x: x not in ["", "None", None]},
|
375 |
+
"gemini_temperature": {"type": float, "constraints": lambda x: 0 <= x <= 2},
|
376 |
+
"gemini_top_p": {"type": typing.Optional[float], "constraints": lambda x: x is None or 0 <= x <= 2},
|
377 |
+
"gemini_top_k": {"type": typing.Optional[int], "constraints": lambda x: x is None or x >= 0},
|
378 |
+
"gemini_candidate_count": {"type": int, "constraints": lambda x: x == 1},
|
379 |
+
"gemini_stream": {"type": bool, "constraints": lambda x: x is False},
|
380 |
+
"gemini_stop_sequences": {"type": None, "constraints": lambda x: x is None},
|
381 |
+
"gemini_max_output_tokens": {"type": typing.Optional[int], "constraints": lambda x: x is None or isinstance(x, int)},
|
382 |
+
}
|
383 |
+
|
384 |
+
if(setting_name not in type_expectations):
|
385 |
+
raise ValueError("Invalid setting name")
|
386 |
+
|
387 |
+
setting_info = type_expectations[setting_name]
|
388 |
+
|
389 |
+
if("stream" in setting_name):
|
390 |
+
value = Toolkit.string_to_bool(initial_value)
|
391 |
+
|
392 |
+
elif(initial_value.lower() in ["none","null"]):
|
393 |
+
value = None
|
394 |
+
|
395 |
+
if(setting_info["type"] is None):
|
396 |
+
converted_value = None
|
397 |
+
elif(setting_info["type"] == typing.Optional[int]):
|
398 |
+
if value is None:
|
399 |
+
converted_value = None
|
400 |
+
else:
|
401 |
+
converted_value = int(value)
|
402 |
+
else:
|
403 |
+
converted_value = setting_info["type"](value)
|
404 |
+
|
405 |
+
if("constraints" in setting_info and not setting_info["constraints"](converted_value)):
|
406 |
+
raise ValueError(f"{setting_name} out of range")
|
407 |
+
|
408 |
+
return converted_value
|
409 |
+
|
410 |
+
##-------------------start-of-SettingsChanger---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
411 |
+
|
412 |
+
class SettingsChanger:
|
413 |
+
|
414 |
+
"""
|
415 |
+
|
416 |
+
Handles changing the settings of the Kijiku Rules.json file.
|
417 |
+
|
418 |
+
"""
|
419 |
+
|
420 |
+
##-------------------start-of-generate_settings_change_menu()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
421 |
+
|
422 |
+
@staticmethod
|
423 |
+
def generate_settings_change_menu() -> str:
|
424 |
+
|
425 |
+
"""
|
426 |
+
|
427 |
+
Generates the settings change menu.
|
428 |
+
|
429 |
+
Returns:
|
430 |
+
menu (str) : The settings change menu.
|
431 |
+
|
432 |
+
"""
|
433 |
+
|
434 |
+
menu = """
|
435 |
+
Current settings:
|
436 |
+
----------------------------------------------------------------
|
437 |
+
|
438 |
+
"""
|
439 |
+
|
440 |
+
for key,value in JsonHandler.current_kijiku_rules["base kijiku settings"].items():
|
441 |
+
menu += key + " : " + str(value) + "\n"
|
442 |
+
|
443 |
+
print("\n")
|
444 |
+
|
445 |
+
for key,value in JsonHandler.current_kijiku_rules["openai settings"].items():
|
446 |
+
menu += key + " : " + str(value) + "\n"
|
447 |
+
|
448 |
+
print("\n")
|
449 |
+
|
450 |
+
for key,value in JsonHandler.current_kijiku_rules["gemini settings"].items():
|
451 |
+
menu += key + " : " + str(value) + "\n"
|
452 |
+
|
453 |
+
menu += """
|
454 |
+
It is recommended that you maximize the console window for this. You will have to to see the settings above.
|
455 |
+
|
456 |
+
Enter the name of the setting you want to change, type d to reset to default, type c to load an external/custom json directly, or type 'q' to quit settings change :
|
457 |
+
"""
|
458 |
+
|
459 |
+
return menu
|
460 |
+
|
461 |
+
##-------------------start-of-load_custom_json()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
462 |
+
|
463 |
+
@staticmethod
|
464 |
+
def load_custom_json() -> None:
|
465 |
+
|
466 |
+
"""
|
467 |
+
|
468 |
+
Loads a custom json into the Kijiku Rules.json file.
|
469 |
+
|
470 |
+
"""
|
471 |
+
|
472 |
+
Toolkit.clear_console()
|
473 |
+
|
474 |
+
## saves old rules in case on invalid json
|
475 |
+
old_kijiku_rules = JsonHandler.current_kijiku_rules
|
476 |
+
|
477 |
+
try:
|
478 |
+
|
479 |
+
## loads the custom json file
|
480 |
+
with open(FileEnsurer.external_kijiku_rules_path, 'r', encoding='utf-8') as file:
|
481 |
+
JsonHandler.current_kijiku_rules = json.load(file)
|
482 |
+
|
483 |
+
JsonHandler.validate_json()
|
484 |
+
|
485 |
+
## validate_json() sets a dict to the invalid placeholder if it's invalid, so if it's that, it's invalid
|
486 |
+
assert JsonHandler.current_kijiku_rules != FileEnsurer.INVALID_KIJIKU_RULES_PLACEHOLDER
|
487 |
+
|
488 |
+
JsonHandler.dump_kijiku_rules()
|
489 |
+
|
490 |
+
print("Settings loaded successfully.")
|
491 |
+
|
492 |
+
except AssertionError:
|
493 |
+
print("Invalid JSON file. Please try again.")
|
494 |
+
JsonHandler.current_kijiku_rules = old_kijiku_rules
|
495 |
+
|
496 |
+
except FileNotFoundError:
|
497 |
+
print("Missing JSON file. Make sure you have a json in the same directory as kudasai.py and that the json is named \"kijiku_rules.json\". Please try again.")
|
498 |
+
JsonHandler.current_kijiku_rules = old_kijiku_rules
|
499 |
+
|
500 |
+
##-------------------start-of-change_setting()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
501 |
+
|
502 |
+
@staticmethod
|
503 |
+
def change_setting(setting_area:str, setting_name:str) -> None:
|
504 |
+
|
505 |
+
"""
|
506 |
+
|
507 |
+
Changes the setting of the Kijiku Rules.json file.
|
508 |
+
|
509 |
+
Parameters:
|
510 |
+
setting_area (str) : The area of the setting to change.
|
511 |
+
setting_name (str) : The name of the setting to change.
|
512 |
+
|
513 |
+
"""
|
514 |
+
|
515 |
+
new_value = input(f"\nEnter a new value for {setting_name}: ")
|
516 |
+
|
517 |
+
try:
|
518 |
+
converted_value = JsonHandler.convert_to_correct_type(setting_name, new_value)
|
519 |
+
|
520 |
+
JsonHandler.current_kijiku_rules[setting_area][setting_name] = converted_value
|
521 |
+
print(f"Updated {setting_name} to {converted_value}.")
|
522 |
+
|
523 |
+
except Exception as e:
|
524 |
+
print(f"Invalid input. No changes made. {e}")
|
jsons/86_replacements.json
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
|
3 |
+
"honorifics": {
|
4 |
+
|
5 |
+
},
|
6 |
+
|
7 |
+
"single_words": {
|
8 |
+
|
9 |
+
},
|
10 |
+
|
11 |
+
"unicode": {
|
12 |
+
|
13 |
+
},
|
14 |
+
|
15 |
+
"phrases": {
|
16 |
+
|
17 |
+
},
|
18 |
+
|
19 |
+
"kutouten": {
|
20 |
+
|
21 |
+
},
|
22 |
+
|
23 |
+
"name_like": {
|
24 |
+
|
25 |
+
},
|
26 |
+
|
27 |
+
"single_names": {
|
28 |
+
|
29 |
+
},
|
30 |
+
|
31 |
+
"full_names": {
|
32 |
+
|
33 |
+
},
|
34 |
+
|
35 |
+
"enhanced_check_whitelist": {
|
36 |
+
|
37 |
+
}
|
38 |
+
|
39 |
+
}
|
jsons/blank_replacements.json
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
|
3 |
+
"honorifics": {
|
4 |
+
|
5 |
+
},
|
6 |
+
|
7 |
+
"single_words": {
|
8 |
+
|
9 |
+
},
|
10 |
+
|
11 |
+
"unicode": {
|
12 |
+
|
13 |
+
},
|
14 |
+
|
15 |
+
"phrases": {
|
16 |
+
|
17 |
+
},
|
18 |
+
|
19 |
+
"kutouten": {
|
20 |
+
|
21 |
+
},
|
22 |
+
|
23 |
+
"name_like": {
|
24 |
+
|
25 |
+
},
|
26 |
+
|
27 |
+
"single_names": {
|
28 |
+
|
29 |
+
},
|
30 |
+
|
31 |
+
"full_names": {
|
32 |
+
|
33 |
+
},
|
34 |
+
|
35 |
+
"enhanced_check_whitelist": {
|
36 |
+
|
37 |
+
}
|
38 |
+
|
39 |
+
}
|
jsons/cote_replacements.json
ADDED
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
{
|
3 |
+
"honorifics": {
|
4 |
+
"ちゃん": "chan",
|
5 |
+
"殿": "dono",
|
6 |
+
"どの": "dono",
|
7 |
+
"くん": "kun",
|
8 |
+
"君": "kun",
|
9 |
+
"後輩": "kōhai",
|
10 |
+
"こうはい": "kōhai",
|
11 |
+
"様": "sama",
|
12 |
+
"さま": "sama",
|
13 |
+
"さん": "san",
|
14 |
+
"先輩": "senpai",
|
15 |
+
"せんぱい": "senpai",
|
16 |
+
"先生": "sensei",
|
17 |
+
"せんせい": "sensei",
|
18 |
+
"パイセン":"paisen",
|
19 |
+
"氏": "shi",
|
20 |
+
"上": "ue"
|
21 |
+
|
22 |
+
},
|
23 |
+
|
24 |
+
"single_words": {
|
25 |
+
"β": "Beta",
|
26 |
+
"後輩":"kōhai",
|
27 |
+
"先輩":"senpai",
|
28 |
+
"パイセン":"paisen"
|
29 |
+
},
|
30 |
+
|
31 |
+
"unicode": {
|
32 |
+
"\u2026":"...",
|
33 |
+
"\u3000": " "
|
34 |
+
},
|
35 |
+
|
36 |
+
"phrases": {
|
37 |
+
"高度育成高等学校": "Advanced Nurturing High School",
|
38 |
+
"高育" : "ANHS",
|
39 |
+
"ケヤキモール" : "Keyaki Mall",
|
40 |
+
"プロテクトポイント": "Protection Point",
|
41 |
+
"東京都高度育成高等学校":"Tokyo Metropolitan Advanced Nurturing High School"
|
42 |
+
},
|
43 |
+
|
44 |
+
"kutouten": {
|
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 |
+
"name_like": {
|
71 |
+
|
72 |
+
},
|
73 |
+
|
74 |
+
"single_names": {
|
75 |
+
"Akiyama": ["秋山"],
|
76 |
+
"Anzai": ["安在"],
|
77 |
+
"Ijūin": ["伊集院"],
|
78 |
+
"Ishida": ["石田"],
|
79 |
+
"Isoyama": ["磯山"],
|
80 |
+
"Keisei": ["啓誠"],
|
81 |
+
"Kijima": ["鬼島"],
|
82 |
+
"Kisarazu": ["木更津"],
|
83 |
+
"Kinugasa" :["衣笠"],
|
84 |
+
"Mii": ["みー"],
|
85 |
+
"Mika": ["美香"],
|
86 |
+
"Namekawa": ["滑川"],
|
87 |
+
"Ohba": ["大場"],
|
88 |
+
"Satonaka": ["里中"],
|
89 |
+
"Shiro": ["志朗"],
|
90 |
+
"Sonezaki": ["曽根崎"],
|
91 |
+
"Sōya": ["宗谷"],
|
92 |
+
"Sugio": ["杉尾"],
|
93 |
+
"Tomose":["トモセ"],
|
94 |
+
"Yano": ["矢野"],
|
95 |
+
"king": ["Wan-sama"]
|
96 |
+
},
|
97 |
+
|
98 |
+
|
99 |
+
"full_names": {
|
100 |
+
"Amasawa Ichika": ["天沢","一夏"],
|
101 |
+
"Amikura Mako": ["網倉","麻子"],
|
102 |
+
"Andō Sayo" : ["安藤","紗代"],
|
103 |
+
"Asahina Nazuna": ["朝比奈","なずな"],
|
104 |
+
"Asama Hisashi": ["浅間","久"],
|
105 |
+
"Ayanokōji Atsuomi": ["綾小路","篤臣"],
|
106 |
+
"Ayanokōji Kiyotaka": ["綾小路","清隆"],
|
107 |
+
"Azuma Sana": ["東","咲菜"],
|
108 |
+
"Chabashira Sae": ["茶柱","佐枝"],
|
109 |
+
"Enoshima Midoriko":["榎嶋","翠子"],
|
110 |
+
"Fukuchi Hinano": ["福地陽","菜乃"],
|
111 |
+
"Hamaguchi Tetsuya": ["浜口","哲也"],
|
112 |
+
"Hagiwara Chihaya": ["萩原","千颯"],
|
113 |
+
"Hasebe Haruka": ["長谷部","波瑠加"],
|
114 |
+
"Hashimoto Masayoshi": ["橋本","正義"],
|
115 |
+
"Himeno Yuki":["姫野","ユキ"],
|
116 |
+
"Hirata Yōsuke": ["平田","洋介"],
|
117 |
+
"Hondō Ryōtarō": ["本堂","遼太郎"],
|
118 |
+
"Horikita Suzune": ["堀北","鈴音"],
|
119 |
+
"Hoshinomiya Chie": ["星之宮","知恵"],
|
120 |
+
"Hōsen Kazuomi": ["宝泉","和臣"],
|
121 |
+
"Ibuki Mio": ["伊吹","澪"],
|
122 |
+
"Ichinose Honami": ["一之瀬","帆波"],
|
123 |
+
"Iguchi Yuri": ["井口","由里"],
|
124 |
+
"Ike Kanji": ["池","寛治"],
|
125 |
+
"Inogashira Kokoro": ["井の頭","心"],
|
126 |
+
"Ishigami Kyō" : ["石上" , "京"],
|
127 |
+
"Ishizaki Daichi": ["石崎","大地"],
|
128 |
+
"Isomaru Yōkō": ["磯丸","容幸"],
|
129 |
+
"Kamogawa Toshizō": ["鴨川","俊三"],
|
130 |
+
"Kamuro Masumi": ["神室","真澄"],
|
131 |
+
"Kanzaki Ryūji": ["神崎","隆二"],
|
132 |
+
"Karuizawa Kei": ["軽井沢","恵"],
|
133 |
+
"Katsuragi Kōhei": ["葛城","康平"],
|
134 |
+
"Kikyō Kushida": ["桔梗","櫛田"],
|
135 |
+
"Kinoshita Minori" : ["木下","美野里"],
|
136 |
+
"Kiriyama Ikuto": ["桐山","生叶"],
|
137 |
+
"Kiryūin Fūka": ["鬼龍院","楓花"],
|
138 |
+
"Kitō Hayato": ["鬼頭","隼"],
|
139 |
+
"Kobashi Yume": ["小橋","夢"],
|
140 |
+
"Komiya Kyōgo": ["小宮","叶吾"],
|
141 |
+
"Kondō Reo": ["近藤","玲音"],
|
142 |
+
"Kōenji Rokusuke": ["高円寺","六助"],
|
143 |
+
"Kōji Machida": ["浩二","町田"],
|
144 |
+
"Kusuda Yukitsu": ["楠田","ゆきつ"],
|
145 |
+
"Manabe Shiho": ["真鍋","志保"],
|
146 |
+
"Mashima Tomonari": ["真嶋","智也"],
|
147 |
+
"Matsushita Chiaki": ["松下","千秋"],
|
148 |
+
"Miyake Akito": ["三宅","明人"],
|
149 |
+
"Miyamoto Sōshi":["宮本","蒼士"],
|
150 |
+
"Mori Nene": ["森","寧々"],
|
151 |
+
"Morishita Ai": ["森下","藍"],
|
152 |
+
"Nagumo Miyabi": ["南雲","雅"],
|
153 |
+
"Nanase Tsubasa": ["七瀬","翼"],
|
154 |
+
"Naoe Jinnosuke": ["直江","仁之助"],
|
155 |
+
"Nishimura Ryūko": ["西村","龍子"],
|
156 |
+
"Nishino Takeko" : ["西野","武子"],
|
157 |
+
"Norihito Watanabe": ["渡辺","紀仁"],
|
158 |
+
"Okitani Kyōsuke": ["沖谷","京介"],
|
159 |
+
"Onodera Kayano": ["小野寺","かや乃"],
|
160 |
+
"Ryūen Kakeru": ["龍園","翔"],
|
161 |
+
"Sakagami Kazuma": ["坂上","数馬"],
|
162 |
+
"Sakayanagi Arisu": ["坂柳","有栖"],
|
163 |
+
"Sakayanagi Narimori": ["坂柳","成守"],
|
164 |
+
"Sakura Airi": ["佐倉","愛里"],
|
165 |
+
"Satō Maya": ["佐藤","麻耶"],
|
166 |
+
"Sanada Kousei": ["真田","康生"],
|
167 |
+
"Sawada Yasumi": ["沢田","恭美"],
|
168 |
+
"Shiba Katsunori": ["司馬","克��"],
|
169 |
+
"Shibata Sō" : ["柴田","颯"],
|
170 |
+
"Shiina Hiyori": ["椎名","ひより"],
|
171 |
+
"Shinohara Satsuki": ["篠原","さつき"],
|
172 |
+
"Shiranami Chihiro": ["白波","千尋"],
|
173 |
+
"Sotomura Hideo": ["外村","秀雄"],
|
174 |
+
"Suchi Moeka": ["須知","萌香"],
|
175 |
+
"Sudō Ken": ["須藤","健"],
|
176 |
+
"Suzukake Tanji": ["鈴懸","鍛治"],
|
177 |
+
"Tachibana Akane": ["橘","茜"],
|
178 |
+
"Tachibana Kento": ["立花","賢人"],
|
179 |
+
"Takahashi Osamu":["高橋","修"],
|
180 |
+
"Tokitō Hiroya": ["時任","裕也"],
|
181 |
+
"Tatewaki Aoi": ["帯刀","碧"],
|
182 |
+
"Totsuka Yahiko": ["戸塚","弥彦"],
|
183 |
+
"Tōdō Rin": ["藤堂","凛"],
|
184 |
+
"Tsubaki Sakurako": ["椿","桜子"],
|
185 |
+
"Tsukishiro Tokinari": ["月城","常成"],
|
186 |
+
"Utomiya Riku": ["宇都宮","陸"],
|
187 |
+
"Wan Mei-Yui": ["王","美雨"],
|
188 |
+
"Yabu Nanami" : ["藪","菜々美"],
|
189 |
+
"Yagami Takuya": ["八神","拓也"],
|
190 |
+
"Yamada Albert": ["山田","アルベルト"],
|
191 |
+
"Yamamura Miki": ["山村","美紀"],
|
192 |
+
"Yamanaka Ikuko": ["山中","郁子"],
|
193 |
+
"Yamashita Saki" : ["鈴代","紗弓"],
|
194 |
+
"Yamashita Naohisa" :[ "山下","直久"],
|
195 |
+
"Yamauchi Haruki": ["山内","春樹"],
|
196 |
+
"Yukimura Teruhiko": ["幸村","輝彦"]
|
197 |
+
},
|
198 |
+
|
199 |
+
"enhanced_check_whitelist": {
|
200 |
+
"Horikita Manabu": ["堀北","学"],
|
201 |
+
"Hoshinomiya Chie": ["星之宮","知恵"],
|
202 |
+
"Kaneda Satoru": ["金田","悟"],
|
203 |
+
"Morofuji Rika" : ["諸藤","リカ"]
|
204 |
+
}
|
205 |
+
|
206 |
+
}
|
jsons/misfit_replacements.json
ADDED
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"honorifics": {
|
3 |
+
"ちゃん": "chan",
|
4 |
+
"殿": "dono",
|
5 |
+
"くん": "kun",
|
6 |
+
"君": "kun",
|
7 |
+
"後輩": "kōhai",
|
8 |
+
"様": "sama",
|
9 |
+
"さん": "san",
|
10 |
+
"せんぱい": "senpai",
|
11 |
+
"先輩": "senpai",
|
12 |
+
"先生": "sensei",
|
13 |
+
"氏": "shi",
|
14 |
+
"上": "ue"
|
15 |
+
},
|
16 |
+
|
17 |
+
|
18 |
+
"single_words": {
|
19 |
+
},
|
20 |
+
|
21 |
+
"unicode": {
|
22 |
+
},
|
23 |
+
|
24 |
+
"phrases": {
|
25 |
+
},
|
26 |
+
|
27 |
+
|
28 |
+
"kutouten": {
|
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 |
+
"name_like": {
|
55 |
+
"お兄": "Onii",
|
56 |
+
"兄": "Nii",
|
57 |
+
"お姉": "Onee",
|
58 |
+
"姉": "Nee"
|
59 |
+
},
|
60 |
+
|
61 |
+
"single_names": {
|
62 |
+
"フクロウ":"UralOwl"
|
63 |
+
},
|
64 |
+
|
65 |
+
"full_names": {
|
66 |
+
"Ahide Alobo Agatse": ["アヒデ", "アロボ", "アガーツェ"],
|
67 |
+
"Anos Voldigoad": ["アノス", "ヴォルディゴード"],
|
68 |
+
"Anosh Portikoro":["アノシュ", "ポルティコーロ"],
|
69 |
+
"Bomiras Heros": ["ボミラス", "ヘロス"],
|
70 |
+
"Carsa Kurnoah": ["カーサ", "クルノア"],
|
71 |
+
"Celis Voldigoad": ["セリス", "ヴォルディゴード"],
|
72 |
+
"Demil Graha": ["デミル", "グラハ"],
|
73 |
+
"Diedrich Kreizen Agaha": ["ディードリッヒ", "クレイツェン", "アガハ"],
|
74 |
+
"Diego Kanon Ijaysica": ["ディエゴ", "カノン", "イジェイシカ"],
|
75 |
+
"Eges Code": ["イージェス", "コード"],
|
76 |
+
"Eldemade Dityjon": ["エールドメード", "ディティジョン"],
|
77 |
+
"Eldora Zaia": ["エルドラ", "ザイア"],
|
78 |
+
"Eleonore Bianca": ["エレオノール", "ビアンカ"],
|
79 |
+
"Elio Ludowell": ["エリオ", "ルードウェル"],
|
80 |
+
"Ellen Mihais": ["エレン", "ミハイス"],
|
81 |
+
"Emilia Ludowell": ["エミリア", "ルードウェル"],
|
82 |
+
"Eugo La Raviaz": ["エウゴ", "ラ", "ラヴィアズ"],
|
83 |
+
"Gaios Anzem": ["ガイオス", "アンゼム"],
|
84 |
+
"Gazel Apt Ageila": ["ガゼル", "アプト", "アゲイラ"],
|
85 |
+
"Gerad Azlema": ["ゲラド", "アズレマ"],
|
86 |
+
"Gilisiris Dello": ["ギリシリス", "デッロ"],
|
87 |
+
"Gorloana Dero Giordal": ["ゴルロアナ", "デロ", "ジオルダル"],
|
88 |
+
"Heine Iorg": ["ハイネ", "イオルグ"],
|
89 |
+
"Himka Houra": ["ヒムカ", "ホウラ"],
|
90 |
+
"Igareth Ijaysica": ["イガレス", "イジェイシカ"],
|
91 |
+
"Alamis Eltimo": ["アラミス", "エルティモ"],
|
92 |
+
"Ivis Necron": ["アイヴィス", "ネクロン"],
|
93 |
+
"Jessica Arnet": ["ジェシカ", "アーネート"],
|
94 |
+
"Kaihilam Jiste": ["カイヒラム", "ジステ"],
|
95 |
+
"Krut Ludowell": ["クルト", "ルードウェル"],
|
96 |
+
"Laos Jilfor": ["ラオス", "ジルフォー"],
|
97 |
+
"Lay Glanzudlii": ["レイ", "グランズドリィ"],
|
98 |
+
"Ledriano Azeschen": ["レドリアーノ", "アゼスチェン"],
|
99 |
+
"Leorig Indu": ["リオルグ", "インドゥ"],
|
100 |
+
"Linka Theournes": ["リンカ", "セオウルネス"],
|
101 |
+
"Ledane Aeon":["レドアネ", "イオン"],
|
102 |
+
"Lisius Angelo Gairadite": ["リシウス", "エンゲロ", "ガイラディーテ"],
|
103 |
+
"Madra Shenson": ["マドラ", "シェンソン"],
|
104 |
+
"Maia Zemut": ["マイア", "ゼムト"],
|
105 |
+
"Medoin Garsa": ["メドイン", "ガーサ"],
|
106 |
+
"Melheis Boran": ["メルヘイス", "ボラン"],
|
107 |
+
"Melissa Nomad": ["メリッサ", "ノマド"],
|
108 |
+
"Menou Historia": ["メノウ", "ヒストリア"],
|
109 |
+
"Misa Ilioroagu": ["ミサ", "イリオローグ"],
|
110 |
+
"Misa Reglia": ["ミサ", "レグリア"],
|
111 |
+
"Misha Necron": ["ミーシャ", "ネクロン"],
|
112 |
+
"Nate Ammilion": ["ネイト", "アンミリオン"],
|
113 |
+
"Nono Inota": ["ノノ", "イノータ"],
|
114 |
+
"Nutella De Hiana": ["ヌテラ", "ド", "ヒアナ"],
|
115 |
+
"Ramon Aiber": ["ラモン", "アイバー"],
|
116 |
+
"Revest Aynie": ["リーベスト", "エイニー"],
|
117 |
+
"Ricardo Arbishas": ["リカルド", "アービシャス"],
|
118 |
+
"Sasha Necron": ["サーシャ", "ネクロン"],
|
119 |
+
"Sheila Glanzudlii": ["シーラ", "グランズドリィ"],
|
120 |
+
"Shelia Nijem": ["シェリア", "ニジェム"],
|
121 |
+
"Shia Minsheng": ["シア", "ミンシェン"],
|
122 |
+
"Shin Reglia": ["シン", "レグリア"],
|
123 |
+
"Sylvia Arbishas": ["シルヴィア", "アービシャス"],
|
124 |
+
"Viaflare Wips Gadesiola": ["ヴィアフレア","ウィプス","ガデイシオラ"],
|
125 |
+
"Ydol Anzeo": ["イドル", "アンゼオ"],
|
126 |
+
"Zabro Gaze": ["ザブロ", "ゲーズ"],
|
127 |
+
"Zamira Angelo": ["ザミラ", "エンゲロ"],
|
128 |
+
"Zeke Ozma": ["ジーク", "オズマ"],
|
129 |
+
"Zepes Indu": ["ゼペス", "インドゥ"],
|
130 |
+
"Zerceas Angart": ["ゼルセアス", "アンガート"],
|
131 |
+
"Zeshia Bianca": ["ゼシア", "ビアンカ"],
|
132 |
+
"Zeshia Kanon Ijaysica":["ゼシア", "カノン", "イジェイシカ"],
|
133 |
+
"Zorro Angart": ["ゾロ", "アンガート"]
|
134 |
+
},
|
135 |
+
|
136 |
+
"enhanced_check_whitelist": {
|
137 |
+
|
138 |
+
}
|
139 |
+
}
|
jsons/rezero_replacements.json
ADDED
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
|
3 |
+
"honorifics": {
|
4 |
+
"先輩": "senpai",
|
5 |
+
"先生": "sensei",
|
6 |
+
"さん": "san",
|
7 |
+
"くん": "kun",
|
8 |
+
"ちゃん": "chan",
|
9 |
+
"さま": "sama",
|
10 |
+
"様": "sama",
|
11 |
+
"殿": "dono"
|
12 |
+
},
|
13 |
+
|
14 |
+
"single_words": {
|
15 |
+
"瘴気": "Miasma",
|
16 |
+
"『魔女』": "Witch",
|
17 |
+
"魔女": "Witch",
|
18 |
+
"『魔人』": "Warlock",
|
19 |
+
"魔人": "warlock",
|
20 |
+
"『暴食』": "Gluttony",
|
21 |
+
"暴食": "Gluttony",
|
22 |
+
"『憤怒』": "Wrath",
|
23 |
+
"憤怒": "Wrath",
|
24 |
+
"『色欲』": "Lust",
|
25 |
+
"色欲": "Lust",
|
26 |
+
"『傲慢』": "Pride",
|
27 |
+
"傲慢": "Pride",
|
28 |
+
"『怠惰』": "Sloth",
|
29 |
+
"怠惰": "Sloth",
|
30 |
+
"『強欲』": "Greed",
|
31 |
+
"強欲": "Greed",
|
32 |
+
"『嫉妬』": "Envy",
|
33 |
+
"嫉妬": "Envy",
|
34 |
+
"権能": "Authority",
|
35 |
+
"魔獣": "Witchbeast",
|
36 |
+
"賢人": "Sage",
|
37 |
+
"エル・": "El ",
|
38 |
+
"ウル・": "Ul ",
|
39 |
+
"アル・": "Al ",
|
40 |
+
"フーラ": "Fula",
|
41 |
+
"ドーナ": "Dona",
|
42 |
+
"ヒューマ": "Huma",
|
43 |
+
"ゴーア": "Goa",
|
44 |
+
"シャマク": "Shamak",
|
45 |
+
"ネクト": "Nect",
|
46 |
+
"ミーニャ": "Minya",
|
47 |
+
"ジワルド": "Jiwald",
|
48 |
+
"ムラク": "Murak",
|
49 |
+
"ヴィータ": "Vita",
|
50 |
+
"クラリスタ": "Clarista",
|
51 |
+
"クラウゼリア": "Clauseria",
|
52 |
+
"クランヴェル": "Kranvel",
|
53 |
+
"共感覚": "Synesthesia",
|
54 |
+
"旦那くん": "Husband-kun",
|
55 |
+
"奥さん": "Wife-san",
|
56 |
+
"姪っ子ちゃん": "Niece-chan",
|
57 |
+
"ギルティラウ": "Guiltilaw",
|
58 |
+
"エルギーナ": "Elgina",
|
59 |
+
"一角獣": "Unicorn",
|
60 |
+
"ファロー": "Falo",
|
61 |
+
"ライガー": "Liger",
|
62 |
+
"ガイラス": "Gyras",
|
63 |
+
"誓約": "oath",
|
64 |
+
"盟約": "covenant",
|
65 |
+
"契約": "contract",
|
66 |
+
"辺境伯": "Margrave",
|
67 |
+
"星詠み": "Stargazer",
|
68 |
+
"女好き": "Womanizer",
|
69 |
+
"ルグニカ": "Lugunica",
|
70 |
+
"プリステラ": "Pristella",
|
71 |
+
"ミルーラ": "Mirula",
|
72 |
+
"ヴォラキア": "Vollachia",
|
73 |
+
"バドハイム": "Buddheim",
|
74 |
+
"シュドラク": "Shudraq",
|
75 |
+
"グァラル": "Guaral",
|
76 |
+
"ガークラ": "Garkla",
|
77 |
+
"カオスフレーム": "Chaosflame",
|
78 |
+
"剣奴": "Gladiator",
|
79 |
+
"ギヌンハイブ": "Ginunhive",
|
80 |
+
"観覧者": "Observers",
|
81 |
+
"隻腕": "one-armed",
|
82 |
+
"精霊": "Spirit",
|
83 |
+
"ちょんと": "ちゃんと",
|
84 |
+
"水を向け": "水を向け MANUAL CHECK",
|
85 |
+
"頬杖をつ": "頬杖をつ MANUAL CHECK",
|
86 |
+
"影を使": "かげむしゃ",
|
87 |
+
"ぼかぁ": "僕は",
|
88 |
+
"亜人": "demi-human",
|
89 |
+
"獣人": "beastman",
|
90 |
+
"牛人": "oxman",
|
91 |
+
"シャトランジ": "Shatranj",
|
92 |
+
"天命": "commandment",
|
93 |
+
"短距離転移": "Blink",
|
94 |
+
"転移": "teleport",
|
95 |
+
"スパルカ": "Sparka",
|
96 |
+
"ルプガナ": "Lupugana",
|
97 |
+
"ボケ": "senile",
|
98 |
+
"ミーティア": "Meteor",
|
99 |
+
"ホロゥ": "Hollow",
|
100 |
+
"ゲート": "Gate",
|
101 |
+
"愛しなんし": "愛しなさい",
|
102 |
+
"商会主":"chairman",
|
103 |
+
"カララギ": "Kararagi",
|
104 |
+
"都市国家": "City-States",
|
105 |
+
"屍人": "undead",
|
106 |
+
"紫紺": "amethyst",
|
107 |
+
"神域": "Sanctum",
|
108 |
+
"核虫": "Corebug",
|
109 |
+
"魔眼": "Evil Eye",
|
110 |
+
"美食家": "Gourmet",
|
111 |
+
"飽食": "Satiation",
|
112 |
+
"『腑分け』": "Dissector",
|
113 |
+
"『石塊』": "Stone",
|
114 |
+
"『通り魔』": "Slasher"
|
115 |
+
},
|
116 |
+
|
117 |
+
"unicode": {
|
118 |
+
|
119 |
+
},
|
120 |
+
|
121 |
+
"phrases": {
|
122 |
+
"飛翼刃": "Flying Winged Blade",
|
123 |
+
"剣闘獣": "Gladiator Beast",
|
124 |
+
"陽剣": "Yang Sword",
|
125 |
+
"幼女使い": "Lolimancer",
|
126 |
+
"灼熱公": "Scorching Lady",
|
127 |
+
"亜人趣味": "Demi-Human Lover",
|
128 |
+
"剣聖": "Sword Saint",
|
129 |
+
"親竜儀": "Dragonkindling Ceremony",
|
130 |
+
"言霊": "The Soul of Language CHECK IF DIVINE PROTECTION",
|
131 |
+
"帝都": "Imperial Capital",
|
132 |
+
"選帝の儀": "Imperial Selection Ceremony",
|
133 |
+
"剣に貫かれた狼": "wolf pierced by swords",
|
134 |
+
"商会":"Trading Company",
|
135 |
+
"都市同盟":"League of Cities",
|
136 |
+
"禁書庫": "Forbidden Library",
|
137 |
+
"魔弾の射手": "Magical Sharpshooter",
|
138 |
+
"毒姫": "Poison Princess",
|
139 |
+
"地竜": "ground dragon",
|
140 |
+
"水竜": "water dragon",
|
141 |
+
"飛竜": "flying dragon",
|
142 |
+
"翼竜": "winged dragon",
|
143 |
+
"礼賛者": "(The) Admirer",
|
144 |
+
"剪定部隊": "Pruning Corps",
|
145 |
+
"美食": "MANUAL CHECK: Gourmet vs. Gourmet Delicacy/ies",
|
146 |
+
"悪食": "Bizarre Eating",
|
147 |
+
"青龍刀": "Blue Dragon Sword",
|
148 |
+
"星食": "Star Eating",
|
149 |
+
"一将": "General First-Class",
|
150 |
+
"二将": "General Second-Class",
|
151 |
+
"三将": "General Third-Class",
|
152 |
+
"宰相": "Prime Minister",
|
153 |
+
"内政官": "Internal Affairs Minister",
|
154 |
+
"聖獣": "Sacred Beast",
|
155 |
+
"調停者": "Arbitrator",
|
156 |
+
"屍都": "Undead Capital",
|
157 |
+
"茨の王": "King of Thorns",
|
158 |
+
"『茨の呪い』": "Curse of Thorns",
|
159 |
+
"血命の儀": "Lifeblood Ritual",
|
160 |
+
"魔女教": "Witch Cult",
|
161 |
+
"魔女因子": "Witch Factor",
|
162 |
+
"魔女の残り香": "Witch's Lingering Scent",
|
163 |
+
"魔女の香": "Witch's Scent",
|
164 |
+
"大罪司教": "Sin Archbishop",
|
165 |
+
"賢人会": "Council of Wise Men",
|
166 |
+
"大賢人": "Great Sage",
|
167 |
+
"死に��り": "Return by Death",
|
168 |
+
"日食": "Solar Eclipse",
|
169 |
+
"月食": "Lunar Eclipse",
|
170 |
+
"アイスブランド・アーツ、アイシクルライン": "Ice Brand Arts: Icicle Line",
|
171 |
+
"氷の兵隊": "Ice Soldiers",
|
172 |
+
"絶対零度": "Absolute Zero",
|
173 |
+
"アイスブランド・アーツ": "Ice Brand Arts",
|
174 |
+
"コル・リオニス": "Cor Leonis",
|
175 |
+
"インビジブル・プロヴィデンス": "Invisible Providence",
|
176 |
+
"見えざる手": "Unseen Hand",
|
177 |
+
"百人一太刀": "One Blow, One Hundred Felled",
|
178 |
+
"扉渡り": "Door Crossing",
|
179 |
+
"復元魔法": "Restoration Magic",
|
180 |
+
"不死王の秘蹟": "Sacrament of the Immortal King",
|
181 |
+
"村長くん": "Village Chief-kun",
|
182 |
+
"仮面の若僧": "masked young'un",
|
183 |
+
"鬼面": "oni mask",
|
184 |
+
"斑王犬": "Spotted Rex",
|
185 |
+
"黒翼鼠": "Blackwinged Mice",
|
186 |
+
"砂蚯蚓": "Sand Earthworm",
|
187 |
+
"花魁熊": "Courtesan Bear",
|
188 |
+
"勇牛": "Brave Ox",
|
189 |
+
"ファロー車": "Falo Cart",
|
190 |
+
"竜車": "dragon carriage",
|
191 |
+
"牛車": "ox cart",
|
192 |
+
"犬車": "canine cart",
|
193 |
+
"背負子": "wooden rack",
|
194 |
+
"火の魔石": "Fire Magic Stones",
|
195 |
+
"騎士の中の騎士": "Knight Amongst Knights",
|
196 |
+
"『最優』の騎士": "Finest of Knights",
|
197 |
+
"最優の騎士": "Finest of Knights",
|
198 |
+
"ゴージャス・タイガー": "Gorgeous Tiger",
|
199 |
+
"青き雷光": "(The) Blue Lightning",
|
200 |
+
"精霊喰らい": "(The) Spirit Eater",
|
201 |
+
"悪辣翁": "(The) Vicious Old Man",
|
202 |
+
"白蜘蛛": "(The) White Spider",
|
203 |
+
"獅子騎士": "(The) Lion Knight",
|
204 |
+
"呪具師": "(The) Master of Curse Tools",
|
205 |
+
"極彩色": "(The) Flamboyant",
|
206 |
+
"鋼人": "(The) Steelman",
|
207 |
+
"飛竜将": "(The) Flying Dragon General",
|
208 |
+
"九神将": "Nine Divine Generals",
|
209 |
+
"ルグニカ王国": "Kingdom of Lugunica",
|
210 |
+
"アウグリア砂丘": "Augria Sand Dunes",
|
211 |
+
"砂風": "Sand Wind",
|
212 |
+
"砂海": "Sand Sea",
|
213 |
+
"魔女の祠": "Witch's Shrine",
|
214 |
+
"リーファウス平原": "Lifaus Plains",
|
215 |
+
"リーファウス街道": "Lifaus Highway",
|
216 |
+
"神聖ヴォラキア帝国": "Sacred Vollachian Empire",
|
217 |
+
"ヴォラキア帝国": "Vollachian Empire",
|
218 |
+
"バドハイム密林": "Buddheim Jungle",
|
219 |
+
"シュドラクの民": "People of Shudraq",
|
220 |
+
"城塞都市": "Fortified City",
|
221 |
+
"城郭都市": "Fortress City",
|
222 |
+
"魔都": "Demon City",
|
223 |
+
"剣奴孤島": "Gladiator Island",
|
224 |
+
"凡愚": "foolish commoner",
|
225 |
+
"精霊術師": "Spiritual Arts Users",
|
226 |
+
"大精霊": "Great Spirit",
|
227 |
+
"準精霊": "Quasi Spirit",
|
228 |
+
"微精霊": "Micro Spirit",
|
229 |
+
"人工精霊": "Artificial Spirit",
|
230 |
+
"紅瑠璃城": "Crimson Lapis Castle",
|
231 |
+
"大災厄": "Great Calamity",
|
232 |
+
"大災": "Great Disaster",
|
233 |
+
"加護": "Divine Protection"
|
234 |
+
},
|
235 |
+
|
236 |
+
"kutouten": {
|
237 |
+
" ": " ",
|
238 |
+
"「": "\"",
|
239 |
+
"」": "\"",
|
240 |
+
"―": "-",
|
241 |
+
"『": "«",
|
242 |
+
"』": "»"
|
243 |
+
},
|
244 |
+
|
245 |
+
"name_like": {
|
246 |
+
"Onii": "お兄",
|
247 |
+
"Onee": "お姉"
|
248 |
+
},
|
249 |
+
|
250 |
+
"single_names": {
|
251 |
+
"Abel": "アベル",
|
252 |
+
"Al": "アル",
|
253 |
+
"Aldebaran": "アルデバラン",
|
254 |
+
"Alcor": "アルコル",
|
255 |
+
"Arakiya": "アラキア",
|
256 |
+
"Barusu": "バルス",
|
257 |
+
"Basu": "バッスー",
|
258 |
+
"Beako": "ベア子",
|
259 |
+
"Beatrice": "ベアトリス",
|
260 |
+
"Betty": "ベティー",
|
261 |
+
"Caerulein": "セルレイン",
|
262 |
+
"Cain": "カイン",
|
263 |
+
"Camberley": "カンバリー",
|
264 |
+
"Carmilla": "カーミラ",
|
265 |
+
"Ceci": "セッシー",
|
266 |
+
"Chamov": "チャモフ",
|
267 |
+
"Chap": "チャップ",
|
268 |
+
"Clind": "クリンド",
|
269 |
+
"Codley": "コドリー",
|
270 |
+
"Colette": "コレット",
|
271 |
+
"Daphne": "ダフネ",
|
272 |
+
"Dartz": "ダーツ",
|
273 |
+
"Didorii": "ディドリー",
|
274 |
+
"Dine": "ダイン",
|
275 |
+
"Dorkell": "ドルケル",
|
276 |
+
"Dynas": "ダイナス",
|
277 |
+
"Echidna": "エキドナ",
|
278 |
+
"Emilia": "エミリア",
|
279 |
+
"Faust": "ファウスト",
|
280 |
+
"Felt": "フェルト",
|
281 |
+
"Fene": "フェネ",
|
282 |
+
"Flugel": "フリューゲル",
|
283 |
+
"Fogg": "フォッグ",
|
284 |
+
"Fortuna": "フォルトナ",
|
285 |
+
"Frufoo": "フルフー",
|
286 |
+
"Gaston": "ガストン",
|
287 |
+
"Gian": "ジャイアン",
|
288 |
+
"Godrov": "ゴドロフ",
|
289 |
+
"Halibel": "ハリベル",
|
290 |
+
"Hector": "ヘクトール",
|
291 |
+
"Helain": "へレイン",
|
292 |
+
"Hitz": "ヒッツ",
|
293 |
+
"Holly": "ホーリィ",
|
294 |
+
"Hornet": "ホーネット",
|
295 |
+
"Ilya": "イリア",
|
296 |
+
"Izmail": "イズメイル",
|
297 |
+
"Kalifa": "カリファ",
|
298 |
+
"Katya": "カチュア",
|
299 |
+
"Korrina": "コリーナ",
|
300 |
+
"Kuna": "クーナ",
|
301 |
+
"Kurgan": "クルガン",
|
302 |
+
"Lucas": "リュカ",
|
303 |
+
"Lyra": "ライラ",
|
304 |
+
"Mariuli": "マリウリ",
|
305 |
+
"Meina": "メイーナ",
|
306 |
+
"Melakuera": "メラクェラ",
|
307 |
+
"Melinda": "メリンダ",
|
308 |
+
"Mezoreia": "メゾレイア",
|
309 |
+
"Mild": "ミルド",
|
310 |
+
"Miles": "マイルズ",
|
311 |
+
"Mimoza": "ミモザ",
|
312 |
+
"Minerva": "ミネルヴァ",
|
313 |
+
"Miser": "ミゼール",
|
314 |
+
"Mizelda": "ミゼルダ",
|
315 |
+
"Mozorite": "モゾリテ",
|
316 |
+
"Muraosa": "ムラオサ",
|
317 |
+
"Muspel": "ムスペル",
|
318 |
+
"Nadrey": "ナドレイ",
|
319 |
+
"Null": "ヌル",
|
320 |
+
"Odglass": "オドグラス",
|
321 |
+
"Omega": "オメガ",
|
322 |
+
"Orphe": "オルフェ",
|
323 |
+
"Orson": "オーソン",
|
324 |
+
"Palmyra": "パルミラ",
|
325 |
+
"Pandora": "パンドラ",
|
326 |
+
"Patrasche": "パトラッシュ",
|
327 |
+
"Petelgeuse": "ペテルギウス",
|
328 |
+
"Pooka": "プーカ",
|
329 |
+
"Puck": "パック",
|
330 |
+
"Quark": "クオーク",
|
331 |
+
"Quonson": "クオンソン",
|
332 |
+
"Raizo": "ライゾー",
|
333 |
+
"Ram": "ラム",
|
334 |
+
"Razcrew": "ラズクルー",
|
335 |
+
"Reisel": "ライゼル",
|
336 |
+
"Reize": "レーゼ",
|
337 |
+
"Rem": "レム",
|
338 |
+
"Rodriguez": "ロドリゲス",
|
339 |
+
"Roshi": "ローシ",
|
340 |
+
"Sado": "サド",
|
341 |
+
"Safis": "サーフィス",
|
342 |
+
"Satella": "サテラ",
|
343 |
+
"Schult": "シュルト",
|
344 |
+
"Sekhmet": "セクメト",
|
345 |
+
"Sergei": "セルゲイ",
|
346 |
+
"Setanta": "セタンタ",
|
347 |
+
"Shaknar": "シャクナール",
|
348 |
+
"Shasuke": "シャスケ",
|
349 |
+
"Shaula": "シャウラ",
|
350 |
+
"Shion": "シオン",
|
351 |
+
"Sirius": "シリウス",
|
352 |
+
"Sphinx": "スピンクス",
|
353 |
+
"Sylphy": "シルフィ",
|
354 |
+
"Tanza": "タンザ",
|
355 |
+
"Taritta": "タリッタ",
|
356 |
+
"Temae": "テマエ",
|
357 |
+
"Tina": "ティーナ",
|
358 |
+
"Tiriena": "ティリエナ",
|
359 |
+
"Toska": "トスカ",
|
360 |
+
"Toto": "トト",
|
361 |
+
"Typhon": "テュフォン",
|
362 |
+
"Ubilk": "ウビルク",
|
363 |
+
"Utakata": "ウタカタ",
|
364 |
+
"Valgren": "バルグレン",
|
365 |
+
"Viva": "ヴィヴァ",
|
366 |
+
"Volcanica": "ボルカニカ",
|
367 |
+
"Wolf": "ウォルフ",
|
368 |
+
"Zarestia": "ザーレスティア"
|
369 |
+
},
|
370 |
+
|
371 |
+
"full_names": {
|
372 |
+
"Natsuki Subaru": ["菜月", "昴"],
|
373 |
+
"Natsuki Kenichi": ["菜月", "賢一"],
|
374 |
+
"Natsuki Naoko": ["菜月", "菜穂子"],
|
375 |
+
"Alviero Juukulius": ["アルビエロ", "ユークリウス"],
|
376 |
+
"Anastasia Hoshin": ["アナスタシア", "ホーシン"],
|
377 |
+
"Annerose Miload": ["アンネローゼ", "ミロード"],
|
378 |
+
"Arch Elior": ["アーチ", "エリオール"],
|
379 |
+
"Array Denkuts": ["アレイ", "デンクツ"],
|
380 |
+
"Balleroy Temeglyph": ["バルロイ", "テメグリフ"],
|
381 |
+
"Barthroy Fitts": ["バルトロイ", "フィッツ"],
|
382 |
+
"Beli Hainelga": ["ベリ", "ハイネルガ"],
|
383 |
+
"Berstetz Fondalfon": ["ベルステツ", "フォンダルフォン"],
|
384 |
+
"Biehn Argyle": ["ビーン", "アーガイル"],
|
385 |
+
"Bordeaux Zellgef": ["ボルドー", "ツェルゲフ"],
|
386 |
+
"Bungam Isten": ["ブンガム", "イースタン"],
|
387 |
+
"Capella Emerada Lugunica": ["カペラ", "エメラダ", "ルグニカ"],
|
388 |
+
"Carlan Astrea": ["カルラン", "アストレア"],
|
389 |
+
"Carol Remendis": ["キャロル", "レメンディス"],
|
390 |
+
"Cassiles van Astrea": ["カッシルス", "ヴァン", "アストレア"],
|
391 |
+
"Cecilus Segmunt": ["セシルス", "セグムント"],
|
392 |
+
"Chesha Trim": ["チェシャ", "トリム"],
|
393 |
+
"Chisha Gold": ["チシャ", "ゴールド"],
|
394 |
+
"Chuden Agri": ["チュデン", "アグリ"],
|
395 |
+
"Colin Lavril": ["コリン", "ラブリル"],
|
396 |
+
"Conwood Melahau": ["コンウッド", "メラハウ"],
|
397 |
+
"Crane Donahue": ["クレイン", "ドナヒュー"],
|
398 |
+
"Crusch Karsten": ["クルシュ", "カルステン"],
|
399 |
+
"Dias Fatsbalm": ["ディアス", "ファッツバルム"],
|
400 |
+
"Doltero Amule": ["ドルテロ", "アムル"],
|
401 |
+
"Drizen Vollachia": ["ドライゼン", "ヴォラキア"],
|
402 |
+
"Dudley Miload": ["ダドリー", "ミロード"],
|
403 |
+
"Edda Rayfast": ["エッダ", "レイファスト"],
|
404 |
+
"Elsa Granhiert": ["エルザ", "グランヒルテ"],
|
405 |
+
"Emerada Lugunica": ["エメラダ", "ルグニカ"],
|
406 |
+
"Eugard Vollachia": ["ユーガルド", "ヴォラキア"],
|
407 |
+
"Ezzo Cadner": ["エッゾ", "カドナ"],
|
408 |
+
"Farsale Lugunica": ["ファルセイル", "ルグニカ"],
|
409 |
+
"Felix Argyle": ["フェリックス", "アーガイル"],
|
410 |
+
"Flam Remendis": ["フラム", "レメンディス"],
|
411 |
+
"Flop O'Connell": ["フロップ", "オコーネル"],
|
412 |
+
"Ford Lugunica": ["フォルド", "ルグニカ"],
|
413 |
+
"Fourier Lugunica": ["フーリエ", "ルグニカ"],
|
414 |
+
"Framir Suwen": ["フラミル", "スーウェン"],
|
415 |
+
"Fred Thompson": ["フレド", "トンプソン"],
|
416 |
+
"Frederica Baumann": ["フレデリカ", "バウマン"],
|
417 |
+
"Fribal van Astrea": ["フライバル", "ヴァン", "アストレア"],
|
418 |
+
"Galic Fabless": ["ガリッチ", "ファブレス"],
|
419 |
+
"Gaoran Peixit": ["ガオラン", "ペイシット"],
|
420 |
+
"Garek Thompson": ["ギャレク", "トンプソン"],
|
421 |
+
"Garfiel Tinzel": ["ガーフィール", "ティンゼル"],
|
422 |
+
"Gilian Endymion": ["ギリアン", "エンデュミオン"],
|
423 |
+
"Gionis Lugunica": ["ジオニス", "ルグニカ"],
|
424 |
+
"Goz Ralfon": ["ゴズ", "ラルフォン"],
|
425 |
+
"Grace Miload": ["グレイス", "ミロード"],
|
426 |
+
"Gramdart Holstoy": ["グラムダート", "ホルストイ"],
|
427 |
+
"Grassis Remendis": ["グラシス", "レメンディス"],
|
428 |
+
"Grimm Fauzen": ["グリム", "ファウゼン"],
|
429 |
+
"Groovy Gumlet": ["グルービー", "ガムレット"],
|
430 |
+
"Gudda Dialmo": ["グッダ", "ディアル��"],
|
431 |
+
"Gustav Morello": ["グスタフ", "モレロ"],
|
432 |
+
"Hannah Regret": ["ハンナ", "リグレット"],
|
433 |
+
"Heinkel Astrea": ["ハインケル", "アストレア"],
|
434 |
+
"Helena Karsten": ["ヘレナ", "カルステン"],
|
435 |
+
"Hetaro Pearlbaton": ["ヘータロー", "パールバトン"],
|
436 |
+
"Hiain Yatz": ["ヒアイン", "ヤッツ"],
|
437 |
+
"Holosseo Featherrun": ["ホロッセオ", "フェザーラン"],
|
438 |
+
"Idra Missanga": ["イドラ", "ミサンガ"],
|
439 |
+
"Igor Kenash": ["イゴール", "ケナシュ"],
|
440 |
+
"Ina Kallard": ["イーナ", "カラード"],
|
441 |
+
"Jamal Aurélie": ["ジャマル", "オーレリー"],
|
442 |
+
"Jorah Pendleton": ["ジョラー", "ペンダルトン"],
|
443 |
+
"Joshua Juukulius": ["ヨシュア", "ユークリウス"],
|
444 |
+
"Julius Juukulius": ["ユリウス", "ユークリウス"],
|
445 |
+
"Kadomon Risch": ["カドモン", "リッシュ"],
|
446 |
+
"Kafma Irulux": ["カフマ", "イルルクス"],
|
447 |
+
"Ketty Muttart": ["ケティ", "ムッタート"],
|
448 |
+
"Kiritaka Muse": ["キリタカ", "ミューズ"],
|
449 |
+
"Klein Juukulius": ["クライン", "ユークリウス"],
|
450 |
+
"Lamia Godwin": ["ラミア", "ゴドウィン"],
|
451 |
+
"Leip Barielle": ["ライプ", "バーリエル"],
|
452 |
+
"Leslie Gabbat": ["レスリー", "ガバット"],
|
453 |
+
"Ley Batenkaitos": ["ライ", "バテンカイトス"],
|
454 |
+
"Libre Fermi": ["リブレ", "フエルミ"],
|
455 |
+
"Liliana Masquerade": ["リリアナ", "マスカレード"],
|
456 |
+
"Logres Hyatt": ["ログレス", "ハイアット"],
|
457 |
+
"Rowan Segmunt": ["ロウアン", "セグムント"],
|
458 |
+
"Louanna Astrea": ["ルアンナ", "アストレア"],
|
459 |
+
"Louis Arneb": ["ルイ", "アルネブ"],
|
460 |
+
"Lusbel Kallard": ["ルスベル", "カラード"],
|
461 |
+
"Makarista Perkin": ["マカリスタ", "パーキン"],
|
462 |
+
"Madelyn Eschart": ["マデリン", "エッシャルト"],
|
463 |
+
"Manfred Madison": ["マンフレッド", "マディソン"],
|
464 |
+
"Marcos Gildark": ["マーコス", "ギルダーク"],
|
465 |
+
"Marone Lisbon": ["マローネ", "リズボン"],
|
466 |
+
"Mazeran Suwen": ["マゼラン", "スーウェン"],
|
467 |
+
"Meckart Karsten": ["メッカート", "カルステン"],
|
468 |
+
"Medium O'Connell": ["ミディアム", "オコーネル"],
|
469 |
+
"Meili Portroute": ["メィリィ", "ポートルート"],
|
470 |
+
"Melty Pristis": ["メルティ", "プリスティス"],
|
471 |
+
"Miklotov McMahon": ["マイクロトフ", "マクマホン"],
|
472 |
+
"Milde Arlam": ["ミルデ", "アーラム"],
|
473 |
+
"Mimi Pearlbaton": ["ミミ", "パールバトン"],
|
474 |
+
"Moguro Hagane": ["モグロ", "ハガネ"],
|
475 |
+
"Muslan Kallard": ["ムスラン", "カラード"],
|
476 |
+
"Natsuki Rigel": ["ナツキ", "リゲル"],
|
477 |
+
"Natsuki Spica": ["ナツキ", "スピカ"],
|
478 |
+
"Natsuki Subaru": ["ナツキ", "スバル"],
|
479 |
+
"Natsumi Schwartz": ["ナツミ", "シュバルツ"],
|
480 |
+
"Neiji Rockheart": ["ネイジ", "ロックハート"],
|
481 |
+
"Olbart Dunkelkenn": ["オルバルト", "ダンクルケン"],
|
482 |
+
"Ornea Featherrun": ["オルニア", "フェザーラン"],
|
483 |
+
"Oslo Suwen": ["オスロー", "スーウェン"],
|
484 |
+
"Otto Suwen": ["オットー", "スーウェン"],
|
485 |
+
"Palladio Manesque": ["パラディオ", "マネスク"],
|
486 |
+
"Petelgeuse Romanée-Conti": ["ペテルギウス", "ロマネコンティ"],
|
487 |
+
"Petra Leyte": ["ペトラ", "レイテ"],
|
488 |
+
"Pivot Arnancy": ["ピボット", "アーナンシー"],
|
489 |
+
"Plum Risch": ["プラム", "リッシュ"],
|
490 |
+
"Prisca Benedict": ["プリスカ", "ベネディクト"],
|
491 |
+
"Priscilla Barielle": ["プリシラ", "バーリエル"],
|
492 |
+
"Rachins Hoffman": ["ラチンス", "ホフマン"],
|
493 |
+
"Rafiel Thompson": ["ラフィール", "トンプソン"],
|
494 |
+
"Raksha Risch": ["ラクシャ", "リッシュ"],
|
495 |
+
"Randohal Lugunica": ["ランドハル", "ルグニカ"],
|
496 |
+
"Razak Gildark": ["ラザック", "ギルダーク"],
|
497 |
+
"Reala Thompson": ["リアラ", "トンプソンリーシア"],
|
498 |
+
"Regin Suwen": ["レギン", "スーウェン"],
|
499 |
+
"Regulus Corneas": ["レグルス", "コルニアス"],
|
500 |
+
"Reid Astrea": ["レイド", "アストレア"],
|
501 |
+
"Reinhard van Astrea": ["ラインハルト", "ヴァン", "アストレア"],
|
502 |
+
"Ricardo Welkin": ["リカード", "ウェルキン"],
|
503 |
+
"Rickert Hoffman": ["リッケルト", "ホフマン"],
|
504 |
+
"Riften Mogoji": ["リフテン", "マゴージ"],
|
505 |
+
"Roswaal J Mathers": ["ロズワール", "J", "メイザース"],
|
506 |
+
"Roswaal K Mathers": ["ロズワール", "K", "メイザース"],
|
507 |
+
"Roswaal L Mathers": ["ロズワール", "L", "メイザース"],
|
508 |
+
"Roy Alphard": ["ロイ", "アルファルド"],
|
509 |
+
"Rudar Iglesia": ["ルダー", "イグレシア"],
|
510 |
+
"Russell Fellow": ["ラッセル", "フェロー"],
|
511 |
+
"Ryuzu Meyer": ["リューズ", "メイエル"],
|
512 |
+
"Sakura Element": ["サクラ", "エレメント"],
|
513 |
+
"Salum Pristis": ["サラム", "プリスティス"],
|
514 |
+
"Sandra Benedict": ["サンドラ", "ベネディクト"],
|
515 |
+
"Serena Dracroy": ["セリーナ", "ドラクロイ"],
|
516 |
+
"Shiroro Tonerico": ["シロロ", "トネリコ"],
|
517 |
+
"Sithonia Featherrun": ["シトニア", "フェザーラン"],
|
518 |
+
"Stride Vollachia": ["ストライド", "ヴォラキア"],
|
519 |
+
"Thames Astrea": ["テムズ", "アストレア"],
|
520 |
+
"Theresia van Astrea": ["テレシア", "ヴァン", "アストレア"],
|
521 |
+
"Tholter Weasily": ["トルタ", "ウィズリー"],
|
522 |
+
"Tiga Rauleon": ["ティーガ", "ラウレオン"],
|
523 |
+
"Tishua Astrea": ["ティシュア", "アストレア"],
|
524 |
+
"Tivey Pearlbaton": ["ティビー", "パールバトン"],
|
525 |
+
"Todd Fang": ["トッド", "ファング"],
|
526 |
+
"Valga Cromwell": ["バルガ", "クロムウェル"],
|
527 |
+
"Veltol Astrea": ["ベルトール", "アストレア"],
|
528 |
+
"Victor Orcos": ["ヴィクター", "オルコス"],
|
529 |
+
"Vincent Vollachia": ["ヴィンセント", "ヴォラキア"],
|
530 |
+
"Vincent Abellux": ["ヴィンセント", "アベルクス"],
|
531 |
+
"Weitz Rogen": ["ヴァイツ", "ログン"],
|
532 |
+
"Wilhelm van Astrea": ["ヴィルヘルム", "ヴァン", "アストレア"],
|
533 |
+
"Yae Tenzen": ["ヤエ", "テンゼン"],
|
534 |
+
"Yaktol Suwen": ["ヤクトル", "スーウェン"],
|
535 |
+
"Yorna Mishigure": ["ヨルナ", "ミシグレ"],
|
536 |
+
"Zabinel Lugunica": ["ザビーネル", "ルグニカ"],
|
537 |
+
"Zelga Iglesia": ["ゼルガ", "イグレシア"],
|
538 |
+
"Zikr Osman": ["ズィクル", "オスマン"]
|
539 |
+
},
|
540 |
+
|
541 |
+
"enhanced_check_whitelist": {
|
542 |
+
|
543 |
+
}
|
544 |
+
|
545 |
+
}
|
jsons/teis_replacements.json
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"honorifics": {
|
3 |
+
"ちゃん": "chan",
|
4 |
+
"殿": "dono",
|
5 |
+
"くん": "kun",
|
6 |
+
"君": "kun",
|
7 |
+
"後輩": "kōhai",
|
8 |
+
"様": "sama",
|
9 |
+
"さん": "san",
|
10 |
+
"せんぱい": "senpai",
|
11 |
+
"先輩": "senpai",
|
12 |
+
"先生": "sensei",
|
13 |
+
"氏": "shi",
|
14 |
+
"上": "ue"
|
15 |
+
},
|
16 |
+
|
17 |
+
"single_words": {
|
18 |
+
"アレクサンドリア": "Alexandria",
|
19 |
+
"アーティファクト": "Artifact",
|
20 |
+
"獣人": "Beastman",
|
21 |
+
"四つ葉": "Clovers",
|
22 |
+
"エルフ": "Elf",
|
23 |
+
"処刑人": "Executioner",
|
24 |
+
"グール": "Ghoul",
|
25 |
+
"ラワガス": "Laugus",
|
26 |
+
"リンドブルム": "Lindwurm",
|
27 |
+
"間合い": "Maai",
|
28 |
+
"聖騎士": "Paladin",
|
29 |
+
"魔界":"Realms",
|
30 |
+
"テンプラー": "Templar",
|
31 |
+
"暴君": "Tyrant",
|
32 |
+
"吸血鬼": "Vampire"
|
33 |
+
},
|
34 |
+
|
35 |
+
"unicode": {
|
36 |
+
"\u3000": " ",
|
37 |
+
"\u2026":"..."
|
38 |
+
},
|
39 |
+
|
40 |
+
"phrases": {
|
41 |
+
"アルテナ帝国": "Altena Empire",
|
42 |
+
"黒キ薔薇": "Black Rose",
|
43 |
+
"身体強化": "Body Strengthening",
|
44 |
+
"都市国家群": "City-State Alliance",
|
45 |
+
"紅の騎士団":"Crimson Order",
|
46 |
+
"ディアボロス教団":"Cult of Diablos",
|
47 |
+
"暗黒微笑": "Dark Smile",
|
48 |
+
"悪魔憑き": "Demon Possession",
|
49 |
+
"強欲の瞳": "Eyes of Avarice",
|
50 |
+
"叛逆遊戯": "Game of Betrayal",
|
51 |
+
"無法 都市": "Lawless City",
|
52 |
+
"無法都市": "Lawless City",
|
53 |
+
"一葉": "Leaf One",
|
54 |
+
"二葉": "Leaf Two",
|
55 |
+
"三葉": "Leaf Three",
|
56 |
+
"四葉":"Leaf Four",
|
57 |
+
"魔獣": "Magical Beast",
|
58 |
+
"魔力": "Magical Power",
|
59 |
+
"大 商会 連合": "Major Corporate Alliance",
|
60 |
+
"大商会連合": "Major Corporate Alliance",
|
61 |
+
"魔剣士協会":"Magic Swordsmen Association",
|
62 |
+
"ミドガル魔剣士学園": "Midgar Royal Spellsword Academy",
|
63 |
+
"ミドガル王国": "Midgar Kingdom",
|
64 |
+
"霧の龍": "Mist Dragon",
|
65 |
+
"ミツゴシ商会": "Mitsugoshi Company",
|
66 |
+
"オリアナ王国":"Oriana Kingdom",
|
67 |
+
"赤き月": "Red Moon",
|
68 |
+
"聖地":"Sacred Land",
|
69 |
+
"桜坂高等学校": "Sakurazaka High School",
|
70 |
+
"聖域": "Sanctuary",
|
71 |
+
"シャドウガーデン": "Shadow Garden",
|
72 |
+
"流星": "Shooting Star",
|
73 |
+
"スライムボディスーツ": "Slime Bodysuit",
|
74 |
+
"雪狐商会": "Snow Fox Corporation",
|
75 |
+
"闘剣嵐武": "Sword storm",
|
76 |
+
"ベガルタ帝国":"Velgalta Empire",
|
77 |
+
"ベガルタ七武剣": "Velgalta's Seven Blades",
|
78 |
+
"ディアボロスの雫":"Tears of Diablos",
|
79 |
+
"十三の夜剣": "Thirteen Night Swords",
|
80 |
+
"三人の英雄":"Three Heroes",
|
81 |
+
"不敗神話":"Unbeaten Legend",
|
82 |
+
"常勝金龍":"Victorious Golden Dragon",
|
83 |
+
"武神":"War Goddess",
|
84 |
+
"流浪の剣士": "Wandering Swordsman",
|
85 |
+
"水の龍": "Water Dragon",
|
86 |
+
"武器強化": "Weapon Strengthening",
|
87 |
+
"白い悪魔": "White Demon"
|
88 |
+
},
|
89 |
+
|
90 |
+
"kutouten": {
|
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 |
+
"name_like": {
|
117 |
+
|
118 |
+
},
|
119 |
+
|
120 |
+
"single_names": {
|
121 |
+
"Alpha": ["アルファ"],
|
122 |
+
"Aurora":["アウロラ"],
|
123 |
+
"Beatrix":["ベアトリクス"],
|
124 |
+
"Beta": ["ベータ"],
|
125 |
+
"Chi": ["カイ"],
|
126 |
+
"Claudia":["クローディア"],
|
127 |
+
"Crimson":["クリムゾン"],
|
128 |
+
"Delta": ["デルタ"],
|
129 |
+
"Drake": ["ドレイク"],
|
130 |
+
"Epsilon": ["イプシロン"],
|
131 |
+
"Elisabeth":["エリザベート"],
|
132 |
+
"Eta": ["イータ"],
|
133 |
+
"Fenrir":["フェンリル"],
|
134 |
+
"Freya":["フレイヤ"],
|
135 |
+
"Gamma": ["ガンマ"],
|
136 |
+
"Gettan":["月丹"],
|
137 |
+
"Glen": ["グレン"],
|
138 |
+
"Grant": ["グラント"],
|
139 |
+
"Haitani":["灰谷"],
|
140 |
+
"Heru": ["ヘル"],
|
141 |
+
"Hubb":["ハブ"],
|
142 |
+
"Issac":["アイザック"],
|
143 |
+
"Jean":["ジャン"],
|
144 |
+
"Juggernaut":["ジャガノート"],
|
145 |
+
"Jormungandr":["ヨルムンガンド"],
|
146 |
+
"Kana":["カナ"],
|
147 |
+
"Lambda": ["ラムダ"],
|
148 |
+
"Lili":["リリ"],
|
149 |
+
"Loki":["ロキ"],
|
150 |
+
"Lukreia":["ルクレイア"],
|
151 |
+
"Malak":["マラック"],
|
152 |
+
"Margaret":["マーガレット"],
|
153 |
+
"Mary":["メアリー"],
|
154 |
+
"Marie":["マリー"],
|
155 |
+
"Millia":["ミリア"],
|
156 |
+
"Mordred":["モードレッド"],
|
157 |
+
"Mu": ["ミュウ"],
|
158 |
+
"Nami": ["ナミ"],
|
159 |
+
"Natsu": ["ナツ"],
|
160 |
+
"Nidhogg":["ニーズヘッグ"],
|
161 |
+
"Nina":["ニーナ"],
|
162 |
+
"Nu": ["ニュー"],
|
163 |
+
"Olivier":["オリヴィエ"],
|
164 |
+
"Omega": ["オメガ"],
|
165 |
+
"Petos":["ペトス"],
|
166 |
+
"Pi": ["パイ"],
|
167 |
+
"Quinton":["クイントン"],
|
168 |
+
"Ragnarok":["ラグナロク"],
|
169 |
+
"Rex": ["レックス"],
|
170 |
+
"Rude": ["ルード"],
|
171 |
+
"Venom":["ヴェノム"],
|
172 |
+
"Victoria":["ウィクトーリア"],
|
173 |
+
"Yukime":["ユキメ"],
|
174 |
+
"Yuuka":["ユウカ"],
|
175 |
+
"Zabra":["ザブラ"],
|
176 |
+
"Zeta": ["ゼータ"]
|
177 |
+
},
|
178 |
+
|
179 |
+
"full_names": {
|
180 |
+
"Aizawa Daisuke": ["逢沢","大介"],
|
181 |
+
"Asshat Perv": ["ケツハット","ドエム"],
|
182 |
+
"Barnett Lutheran": ["バーネット","ルスラン"],
|
183 |
+
"Barnett Sherry": ["バーネット","シェリー"],
|
184 |
+
"Etel Skel":["ガリ", "ヒョロ"],
|
185 |
+
"Granger Marco": ["グランジャー","マルコ"],
|
186 |
+
"Griffey Zenon": ["グリフィ","ゼノン"],
|
187 |
+
"Gorman Sergey": ["ゴーマン","セルゲイ"],
|
188 |
+
"Herzog von Karen": ["ヘルツォーク","フォン","カレン"],
|
189 |
+
"Hope Christina": ["ホープ","クリスティーナ"],
|
190 |
+
"hope Suzuki": ["ホープ","スズーキ"],
|
191 |
+
"Kagenō Claire": ["カゲノー", "クレア"],
|
192 |
+
"Kagenō Cid": ["カゲノー", "シド"],
|
193 |
+
"Kagenō Oton": ["カゲノー", "オトン"],
|
194 |
+
"Kagenō Otan": ["カゲノー", "オタン"],
|
195 |
+
"Kikuchi Garter":["キクチ", "ガーター"],
|
196 |
+
"Kinmeki Goldoh":["キンメキ", "ゴルドー"],
|
197 |
+
"Midgar Alexia": ["ミドガル","アレクシア"],
|
198 |
+
"Midgar Iris": ["ミドガル","アイリス"],
|
199 |
+
"Midgar Klaus": ["ミドガル","クラウス"],
|
200 |
+
"Machom Gonzales": ["マチョム","ゴンザレス"],
|
201 |
+
"Mundane Mann": ["ジミナ","セーネン"],
|
202 |
+
"Nelson Jack": ["ネルソン","ジャック"],
|
203 |
+
"Nichtsehen Annerose": ["フシアナス", "アンネローゼ"],
|
204 |
+
"Nishino Akane": ["西野","アカネ"],
|
205 |
+
"Nishino Akira": ["西野","アキラ"],
|
206 |
+
"Nottaloos Imatry":["マッケンジー", "ツギーデ"],
|
207 |
+
"Oriana Raphael": ["オリアナ","ラファエロ"],
|
208 |
+
"Oriana Reina": ["オリアナ","レイナ"],
|
209 |
+
"Oriana Rose": ["オリアナ","ローズ"],
|
210 |
+
"Tato Po": ["イモ","ジャガ"],
|
211 |
+
"Saejima Yuudai": ["冴島","ユウダイ"]
|
212 |
+
},
|
213 |
+
|
214 |
+
"enhanced_check_whitelist": {
|
215 |
+
|
216 |
+
}
|
217 |
+
|
218 |
+
}
|
jsons/tensura_replacements.json
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
|
3 |
+
"honorifics": {
|
4 |
+
"さん": "san",
|
5 |
+
"くん": "kun",
|
6 |
+
"ちゃん": "chan",
|
7 |
+
"せんぱい": "senpai",
|
8 |
+
"上": "ue",
|
9 |
+
"氏": "shi",
|
10 |
+
"君": "kun",
|
11 |
+
"様": "sama",
|
12 |
+
"先輩": "senpai",
|
13 |
+
"後輩": "kōhai",
|
14 |
+
"先生": "sensei",
|
15 |
+
"殿": "dono"
|
16 |
+
},
|
17 |
+
|
18 |
+
"single_words": {
|
19 |
+
"イングラシア" : "Ingracia",
|
20 |
+
"魔物" : "Monster"
|
21 |
+
},
|
22 |
+
|
23 |
+
"unicode": {
|
24 |
+
"\u3000": " ",
|
25 |
+
"\u2026":"..."
|
26 |
+
},
|
27 |
+
|
28 |
+
"phrases": {
|
29 |
+
"開国祭" : "Founder's Festival",
|
30 |
+
"獣魔術" : "Beast Magic",
|
31 |
+
"獣魔" : "Beast Demon",
|
32 |
+
"万能感知" :"Universal Detect",
|
33 |
+
"思考加速" : "Thought Acceleration",
|
34 |
+
"霊子崩壊" : "Disintegration",
|
35 |
+
"万能糸" : "Universal Thread",
|
36 |
+
"智慧之王": "Lord of Wisdom",
|
37 |
+
"ヴェルドラ流闘殺法" : "Veldora-Style Killing Arts",
|
38 |
+
"Holy Magic" : "神聖魔法",
|
39 |
+
"Elemental Magic" : "元素魔法",
|
40 |
+
"Spatial Motion" : "空間移動"
|
41 |
+
|
42 |
+
|
43 |
+
},
|
44 |
+
|
45 |
+
"kutouten": {
|
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 |
+
"name_like": {
|
74 |
+
|
75 |
+
},
|
76 |
+
|
77 |
+
"single_names": {
|
78 |
+
"Kenya" :"ケンヤ",
|
79 |
+
"Hinata": "ヒナタ",
|
80 |
+
"Ryota": "リョウタ",
|
81 |
+
"Alice": "アリス",
|
82 |
+
"Chloe" : "クロエ",
|
83 |
+
"Gail" : "ゲイル",
|
84 |
+
"Rimuru": "リムル",
|
85 |
+
"Veldora":"ヴェルドラ",
|
86 |
+
"Yukki":"ユウキ",
|
87 |
+
"Luminous":"ルミナス",
|
88 |
+
"Ramiris":"ラミリス",
|
89 |
+
"Shuna" : "シュナ",
|
90 |
+
"Benimaru" : "ベニマル",
|
91 |
+
"Souei" : "ソウエイ",
|
92 |
+
"Gabil" : "ガビル",
|
93 |
+
"Hakurou" : "ハクロウ",
|
94 |
+
"Gobta" : "ゴブタ",
|
95 |
+
"Beretta" : "ベレッタ",
|
96 |
+
"Shion": "シオン",
|
97 |
+
"Kaijin" : "カイジン",
|
98 |
+
"Diablo" : "ディアブロ",
|
99 |
+
"Treyni" : "トレイニー"
|
100 |
+
|
101 |
+
|
102 |
+
|
103 |
+
},
|
104 |
+
|
105 |
+
"full_names": {
|
106 |
+
|
107 |
+
|
108 |
+
},
|
109 |
+
|
110 |
+
"enhanced_check_whitelist": {
|
111 |
+
|
112 |
+
}
|
113 |
+
|
114 |
+
}
|
kudasai.py
ADDED
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
import json
|
5 |
+
import asyncio
|
6 |
+
import re
|
7 |
+
import typing
|
8 |
+
|
9 |
+
## third-party libraries
|
10 |
+
from kairyou import Kairyou
|
11 |
+
from kairyou import Indexer
|
12 |
+
from kairyou.types import NameAndOccurrence
|
13 |
+
|
14 |
+
## custom modules
|
15 |
+
from models.kaiseki import Kaiseki
|
16 |
+
from models.kijiku import Kijiku
|
17 |
+
|
18 |
+
from handlers.json_handler import JsonHandler
|
19 |
+
|
20 |
+
from modules.common.toolkit import Toolkit
|
21 |
+
from modules.common.file_ensurer import FileEnsurer
|
22 |
+
from modules.common.logger import Logger
|
23 |
+
|
24 |
+
##-------------------start-of-Kudasai---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
25 |
+
|
26 |
+
class Kudasai:
|
27 |
+
|
28 |
+
"""
|
29 |
+
|
30 |
+
Kudasai class is the main class for the Kudasai program. It handles all logic for CLI & Console versions of Kudasai.
|
31 |
+
|
32 |
+
"""
|
33 |
+
|
34 |
+
connection:bool
|
35 |
+
|
36 |
+
text_to_preprocess:str
|
37 |
+
replacement_json:dict
|
38 |
+
|
39 |
+
need_to_run_kairyou:bool = True
|
40 |
+
|
41 |
+
##-------------------start-of-boot()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
42 |
+
|
43 |
+
@staticmethod
|
44 |
+
def boot() -> None:
|
45 |
+
|
46 |
+
"""
|
47 |
+
|
48 |
+
Does some logging and sets up the console window, regardless of whether the user is running the CLI, WebGUI, or Console version of Kudasai.
|
49 |
+
|
50 |
+
"""
|
51 |
+
|
52 |
+
os.system("title " + "Kudasai")
|
53 |
+
|
54 |
+
Toolkit.clear_console()
|
55 |
+
|
56 |
+
FileEnsurer.setup_needed_files()
|
57 |
+
|
58 |
+
Logger.clear_log_file()
|
59 |
+
|
60 |
+
Logger.log_barrier()
|
61 |
+
Logger.log_action("Kudasai started")
|
62 |
+
Logger.log_action("Current version: " + Toolkit.CURRENT_VERSION)
|
63 |
+
Logger.log_barrier()
|
64 |
+
|
65 |
+
Logger.push_batch()
|
66 |
+
Logger.clear_batch()
|
67 |
+
|
68 |
+
try:
|
69 |
+
|
70 |
+
with open(FileEnsurer.config_kijiku_rules_path, "r") as kijiku_rules_file:
|
71 |
+
JsonHandler.current_kijiku_rules = json.load(kijiku_rules_file)
|
72 |
+
|
73 |
+
JsonHandler.validate_json()
|
74 |
+
|
75 |
+
assert JsonHandler.current_kijiku_rules != FileEnsurer.INVALID_KIJIKU_RULES_PLACEHOLDER
|
76 |
+
|
77 |
+
except:
|
78 |
+
|
79 |
+
print("Invalid kijiku_rules.json file. Please check the file for errors. If you are unsure, delete the file and run Kudasai again. Your kijiku rules file is located at: " + FileEnsurer.config_kijiku_rules_path)
|
80 |
+
|
81 |
+
Toolkit.pause_console()
|
82 |
+
|
83 |
+
raise Exception("Invalid kijiku_rules.json file. Please check the file for errors. If you are unsure, delete the file and run Kudasai again. Your kijiku rules file is located at: " + FileEnsurer.config_kijiku_rules_path)
|
84 |
+
|
85 |
+
##-------------------start-of-run_kairyou_indexer()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
86 |
+
|
87 |
+
@staticmethod
|
88 |
+
def run_kairyou_indexer(text_to_index:str, replacement_json:typing.Union[dict,str]) -> typing.Tuple[str, str]:
|
89 |
+
|
90 |
+
"""
|
91 |
+
|
92 |
+
Runs the Kairyou Indexer.
|
93 |
+
|
94 |
+
Parameters:
|
95 |
+
text_to_index (str): The text to index.
|
96 |
+
replacement_json (dict): The replacement json.
|
97 |
+
|
98 |
+
Returns:
|
99 |
+
text_to_index (str): The indexed text.
|
100 |
+
indexing_log (str): The log of the indexing process.
|
101 |
+
|
102 |
+
"""
|
103 |
+
|
104 |
+
Toolkit.clear_console()
|
105 |
+
|
106 |
+
knowledge_base = input("Please enter the path to the knowledge base you would like to use for the indexer (can be text, a path to a txt file, or a path to a directory of txt files):\n").strip('"')
|
107 |
+
|
108 |
+
## unique names is a list of named tuples, with the fields name and occurrence
|
109 |
+
unique_names, indexing_log = Indexer.index(text_to_index, knowledge_base, replacement_json)
|
110 |
+
|
111 |
+
## for each name in unique_names, we need to replace that name in the text_to_process with >>>name<<<
|
112 |
+
## but since it returns the occurrence of the name, we only need to replace that occurrence of the name in the text_to_process
|
113 |
+
## So if a name has 42 occurrences, but only the 3rd and 4th occurrence were flagged, we only need to replace the 3rd and 4th occurrence of the name in the text_to_process
|
114 |
+
|
115 |
+
text_to_index = Kudasai.mark_indexed_names(text_to_index, unique_names)
|
116 |
+
|
117 |
+
return text_to_index, indexing_log
|
118 |
+
|
119 |
+
##-------------------start-of-mark_indexed_names()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
120 |
+
|
121 |
+
@staticmethod
|
122 |
+
def mark_indexed_names(text:str, unique_names:typing.List[NameAndOccurrence]) -> str:
|
123 |
+
|
124 |
+
"""
|
125 |
+
|
126 |
+
Marks indexed names in the text.
|
127 |
+
This does not mark all names, but rather the specific occurrences of the names that were flagged by the indexer.
|
128 |
+
|
129 |
+
Parameters:
|
130 |
+
text (str): The text to mark.
|
131 |
+
unique_names (list - NameAndOccurrence): The list of unique names.
|
132 |
+
|
133 |
+
Returns:
|
134 |
+
str: The marked text.
|
135 |
+
|
136 |
+
"""
|
137 |
+
|
138 |
+
for name_tuple in unique_names:
|
139 |
+
name = name_tuple.name
|
140 |
+
pattern = re.compile(re.escape(name)) ## Prepare regex pattern, escaping the name to handle special characters
|
141 |
+
|
142 |
+
current_pos = 0
|
143 |
+
new_text = ""
|
144 |
+
last_end = 0
|
145 |
+
|
146 |
+
for match in pattern.finditer(text):
|
147 |
+
current_pos += 1
|
148 |
+
if(current_pos == name_tuple.occurrence):
|
149 |
+
new_text += text[last_end:match.start()] + f">>>{name}<<<"
|
150 |
+
last_end = match.end()
|
151 |
+
|
152 |
+
new_text += text[last_end:] # Append the rest of the text
|
153 |
+
text = new_text
|
154 |
+
|
155 |
+
return text
|
156 |
+
|
157 |
+
##-------------------start-of-run_kudasai()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
158 |
+
|
159 |
+
@staticmethod
|
160 |
+
async def run_kudasai() -> None:
|
161 |
+
|
162 |
+
"""
|
163 |
+
|
164 |
+
Runs the Kudasai program. Used for CLI and Console versions of Kudasai. Not used for the WebGUI version of Kudasai.
|
165 |
+
|
166 |
+
"""
|
167 |
+
|
168 |
+
Kudasai.handle_update_check()
|
169 |
+
|
170 |
+
if(Kudasai.need_to_run_kairyou):
|
171 |
+
|
172 |
+
indexing_log = ""
|
173 |
+
|
174 |
+
if(Kudasai.replacement_json not in ["", FileEnsurer.blank_rules_path, FileEnsurer.standard_read_json(FileEnsurer.blank_rules_path)] and input("Would you like to use Kairyou's Indexer to index the preprocessed text? (1 for yes, 2 for no)\n") == "1"):
|
175 |
+
Kudasai.text_to_preprocess, indexing_log = Kudasai.run_kairyou_indexer(Kudasai.text_to_preprocess, Kudasai.replacement_json)
|
176 |
+
|
177 |
+
preprocessed_text, preprocessing_log, error_log = Kairyou.preprocess(Kudasai.text_to_preprocess, Kudasai.replacement_json)
|
178 |
+
|
179 |
+
## Need to set this so auto-translation can use the preprocessed text
|
180 |
+
Kudasai.text_to_preprocess = preprocessed_text
|
181 |
+
|
182 |
+
## add index log to preprocessing log
|
183 |
+
if(indexing_log != ""):
|
184 |
+
preprocessing_log = indexing_log + "\n\n" + preprocessing_log
|
185 |
+
|
186 |
+
print(preprocessing_log)
|
187 |
+
|
188 |
+
timestamp = Toolkit.get_timestamp(is_archival=True)
|
189 |
+
|
190 |
+
FileEnsurer.write_kairyou_results(preprocessed_text, preprocessing_log, error_log, timestamp)
|
191 |
+
|
192 |
+
Toolkit.pause_console("\nPress any key to continue to Auto-Translation...")
|
193 |
+
Toolkit.clear_console()
|
194 |
+
|
195 |
+
else:
|
196 |
+
print("(Preprocessing skipped)")
|
197 |
+
|
198 |
+
await Kudasai.determine_autotranslation_module()
|
199 |
+
|
200 |
+
Toolkit.pause_console("\nPress any key to exit...")
|
201 |
+
|
202 |
+
##-------------------start-of-handle_update_check()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
203 |
+
|
204 |
+
@staticmethod
|
205 |
+
def handle_update_check() -> None:
|
206 |
+
|
207 |
+
"""
|
208 |
+
|
209 |
+
Checks for updates and prompts the user to update if there is an update available.
|
210 |
+
|
211 |
+
"""
|
212 |
+
|
213 |
+
Kudasai.connection, update_prompt = Toolkit.check_update()
|
214 |
+
|
215 |
+
if(update_prompt != ""):
|
216 |
+
|
217 |
+
print(update_prompt)
|
218 |
+
|
219 |
+
Toolkit.pause_console()
|
220 |
+
Toolkit.clear_console()
|
221 |
+
|
222 |
+
##-------------------start-of-determine_autotranslation_module()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
223 |
+
|
224 |
+
@staticmethod
|
225 |
+
async def determine_autotranslation_module() -> None:
|
226 |
+
|
227 |
+
"""
|
228 |
+
|
229 |
+
If the user is running the CLI or Console version of Kudasai, this function is called to determine which autotranslation module to use.
|
230 |
+
|
231 |
+
"""
|
232 |
+
|
233 |
+
if(not Kudasai.connection):
|
234 |
+
Toolkit.clear_console()
|
235 |
+
|
236 |
+
print("You are not connected to the internet. Please connect to the internet to use the autotranslation feature.\n")
|
237 |
+
Toolkit.pause_console()
|
238 |
+
|
239 |
+
exit()
|
240 |
+
|
241 |
+
pathing = ""
|
242 |
+
|
243 |
+
pathing_msg = "Please select an auto-translation module:\n\n1.Kaiseki (deepL)\n2.Kijiku (OpenAI/Gemini)\n3.Exit\n\n"
|
244 |
+
|
245 |
+
pathing = input(pathing_msg)
|
246 |
+
|
247 |
+
Toolkit.clear_console()
|
248 |
+
|
249 |
+
if(pathing == "1"):
|
250 |
+
Kudasai.run_kaiseki()
|
251 |
+
elif(pathing == "2"):
|
252 |
+
await Kudasai.run_kijiku()
|
253 |
+
else:
|
254 |
+
Toolkit.clear_console()
|
255 |
+
exit()
|
256 |
+
|
257 |
+
##-------------------start-of-run_kaiseki()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
258 |
+
|
259 |
+
@staticmethod
|
260 |
+
def run_kaiseki() -> None:
|
261 |
+
|
262 |
+
"""
|
263 |
+
|
264 |
+
If the user is running the CLI or Console version of Kudasai, this function is called to run the Kaiseki module.
|
265 |
+
|
266 |
+
"""
|
267 |
+
|
268 |
+
Logger.log_action("--------------------")
|
269 |
+
Logger.log_action("Kaiseki started")
|
270 |
+
Logger.log_action("--------------------")
|
271 |
+
|
272 |
+
Kaiseki.text_to_translate = [line for line in Kudasai.text_to_preprocess.splitlines()]
|
273 |
+
|
274 |
+
Kaiseki.translate()
|
275 |
+
|
276 |
+
Toolkit.clear_console()
|
277 |
+
|
278 |
+
print(Kaiseki.translation_print_result)
|
279 |
+
|
280 |
+
Kaiseki.write_kaiseki_results()
|
281 |
+
|
282 |
+
##-------------------start-of-run_kijiku()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
283 |
+
|
284 |
+
@staticmethod
|
285 |
+
async def run_kijiku() -> None:
|
286 |
+
|
287 |
+
"""
|
288 |
+
|
289 |
+
If the user is running the CLI or Console version of Kudasai, this function is called to run the Kijiku module.
|
290 |
+
|
291 |
+
"""
|
292 |
+
|
293 |
+
Logger.log_action("--------------------")
|
294 |
+
Logger.log_action("Kijiku started")
|
295 |
+
Logger.log_action("--------------------")
|
296 |
+
|
297 |
+
Toolkit.clear_console()
|
298 |
+
|
299 |
+
Kijiku.text_to_translate = [line for line in Kudasai.text_to_preprocess.splitlines()]
|
300 |
+
|
301 |
+
await Kijiku.translate()
|
302 |
+
|
303 |
+
Toolkit.clear_console()
|
304 |
+
|
305 |
+
print(Kijiku.translation_print_result)
|
306 |
+
|
307 |
+
Kijiku.write_kijiku_results()
|
308 |
+
|
309 |
+
##-------------------start-of-main()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
310 |
+
|
311 |
+
async def main() -> None:
|
312 |
+
|
313 |
+
"""
|
314 |
+
|
315 |
+
The main function of the Kudasai program.
|
316 |
+
|
317 |
+
"""
|
318 |
+
|
319 |
+
Kudasai.boot()
|
320 |
+
Toolkit.clear_console()
|
321 |
+
|
322 |
+
try:
|
323 |
+
|
324 |
+
if(len(sys.argv) <= 1):
|
325 |
+
await run_console_version()
|
326 |
+
|
327 |
+
elif(len(sys.argv) in [2, 3]):
|
328 |
+
await run_cli_version()
|
329 |
+
|
330 |
+
else:
|
331 |
+
print_usage_statement()
|
332 |
+
|
333 |
+
except Exception as e:
|
334 |
+
FileEnsurer.handle_critical_exception(e)
|
335 |
+
|
336 |
+
##-------------------start-of-run_console_version()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
337 |
+
|
338 |
+
async def run_console_version():
|
339 |
+
|
340 |
+
"""
|
341 |
+
|
342 |
+
Runs the console version of Kudasai.
|
343 |
+
|
344 |
+
"""
|
345 |
+
|
346 |
+
try:
|
347 |
+
|
348 |
+
path_to_text_to_preprocess = input("Please enter the path to the input file to be processed:\n").strip('"')
|
349 |
+
Kudasai.text_to_preprocess = FileEnsurer.standard_read_file(path_to_text_to_preprocess)
|
350 |
+
Toolkit.clear_console()
|
351 |
+
|
352 |
+
path_to_replacement_json = input("Please enter the path to the replacement json file:\n").strip('"')
|
353 |
+
Kudasai.replacement_json = FileEnsurer.standard_read_json(path_to_replacement_json if path_to_replacement_json else FileEnsurer.blank_rules_path)
|
354 |
+
Toolkit.clear_console()
|
355 |
+
|
356 |
+
except Exception as e:
|
357 |
+
print_usage_statement()
|
358 |
+
|
359 |
+
raise e
|
360 |
+
|
361 |
+
await Kudasai.run_kudasai()
|
362 |
+
Logger.push_batch()
|
363 |
+
|
364 |
+
##-------------------start-of-run_cli_version()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
365 |
+
|
366 |
+
async def run_cli_version():
|
367 |
+
|
368 |
+
"""
|
369 |
+
|
370 |
+
Runs the CLI version of Kudasai.
|
371 |
+
|
372 |
+
"""
|
373 |
+
|
374 |
+
try:
|
375 |
+
|
376 |
+
Kudasai.text_to_preprocess = FileEnsurer.standard_read_file(sys.argv[1].strip('"'))
|
377 |
+
Kudasai.replacement_json = FileEnsurer.standard_read_json(sys.argv[2].strip('"') if(len(sys.argv) == 3) else FileEnsurer.blank_rules_path)
|
378 |
+
|
379 |
+
except Exception as e:
|
380 |
+
print_usage_statement()
|
381 |
+
|
382 |
+
raise e
|
383 |
+
|
384 |
+
if(len(sys.argv) == 2):
|
385 |
+
Kudasai.need_to_run_kairyou = False
|
386 |
+
|
387 |
+
await Kudasai.run_kudasai()
|
388 |
+
Logger.push_batch()
|
389 |
+
|
390 |
+
##-------------------start-of-print_usage_statement()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
391 |
+
|
392 |
+
def print_usage_statement():
|
393 |
+
|
394 |
+
"""
|
395 |
+
|
396 |
+
Prints the usage statement for the CLI version of Kudasai.
|
397 |
+
|
398 |
+
"""
|
399 |
+
|
400 |
+
Logger.log_action("Usage: python Kudasai.py <input_file> <replacement_json>", output=True, omit_timestamp=True)
|
401 |
+
Logger.log_action("or run Kudasai.py without any arguments to run the console version.", output=True, omit_timestamp=True)
|
402 |
+
|
403 |
+
print("\n")
|
404 |
+
|
405 |
+
##-------------------start-of-submain()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
406 |
+
|
407 |
+
|
408 |
+
if(__name__ == '__main__'):
|
409 |
+
asyncio.run(main())
|
lib/gui/Kudasai_Logo.png
ADDED
models/kaiseki.py
ADDED
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Basically Deprecated, use Kijiku instead. Currently only maintained for backwards compatibility.
|
2 |
+
##---------------------------------------
|
3 |
+
## built-in libraries
|
4 |
+
import string
|
5 |
+
import time
|
6 |
+
import re
|
7 |
+
import base64
|
8 |
+
import time
|
9 |
+
|
10 |
+
## custom modules
|
11 |
+
from translation_services.deepl_service import DeepLService
|
12 |
+
from modules.common.toolkit import Toolkit
|
13 |
+
from modules.common.file_ensurer import FileEnsurer
|
14 |
+
from modules.common.logger import Logger
|
15 |
+
from modules.common.decorators import permission_error_decorator
|
16 |
+
from modules.common.exceptions import AuthorizationException, QuotaExceededException
|
17 |
+
|
18 |
+
##-------------------start-of-Kaiseki--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
19 |
+
|
20 |
+
class Kaiseki:
|
21 |
+
|
22 |
+
"""
|
23 |
+
|
24 |
+
Kaiseki is a secondary class that is used to interact with the Deepl API and translate Japanese text sentence by sentence.
|
25 |
+
|
26 |
+
Kaiseki is considered inferior to Kijiku, please consider using Kijiku instead.
|
27 |
+
|
28 |
+
"""
|
29 |
+
|
30 |
+
##---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
31 |
+
|
32 |
+
text_to_translate = []
|
33 |
+
|
34 |
+
translated_text = []
|
35 |
+
|
36 |
+
je_check_text = []
|
37 |
+
|
38 |
+
error_text = []
|
39 |
+
|
40 |
+
translation_print_result = ""
|
41 |
+
|
42 |
+
##---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
43 |
+
|
44 |
+
sentence_parts = []
|
45 |
+
|
46 |
+
sentence_punctuation = []
|
47 |
+
|
48 |
+
## [0] = "" [1] = ~ [2] = '' in Kaiseki.current_sentence but not entire Kaiseki.current_sentence [3] = '' but entire Kaiseki.current_sentence [3] if () in Kaiseki.current_sentence
|
49 |
+
special_punctuation = []
|
50 |
+
|
51 |
+
current_sentence = ""
|
52 |
+
|
53 |
+
translated_sentence = ""
|
54 |
+
|
55 |
+
##-------------------start-of-translate()--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
56 |
+
|
57 |
+
@staticmethod
|
58 |
+
def translate() -> None:
|
59 |
+
|
60 |
+
"""
|
61 |
+
|
62 |
+
Translates the text.
|
63 |
+
|
64 |
+
"""
|
65 |
+
|
66 |
+
Logger.clear_batch()
|
67 |
+
|
68 |
+
time_start = time.time()
|
69 |
+
|
70 |
+
try:
|
71 |
+
|
72 |
+
Kaiseki.initialize()
|
73 |
+
|
74 |
+
## offset time, for if the user doesn't get through Kaiseki.initialize() before the translation starts.
|
75 |
+
time_start = time.time()
|
76 |
+
|
77 |
+
Kaiseki.commence_translation()
|
78 |
+
|
79 |
+
except Exception as e:
|
80 |
+
|
81 |
+
Kaiseki.translation_print_result += "An error has occurred, outputting results so far..."
|
82 |
+
|
83 |
+
FileEnsurer.handle_critical_exception(e)
|
84 |
+
|
85 |
+
finally:
|
86 |
+
|
87 |
+
time_end = time.time()
|
88 |
+
|
89 |
+
Kaiseki.assemble_results(time_start, time_end)
|
90 |
+
|
91 |
+
##-------------------start-of-initialize()--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
92 |
+
|
93 |
+
@staticmethod
|
94 |
+
def initialize() -> None:
|
95 |
+
|
96 |
+
"""
|
97 |
+
|
98 |
+
Initializes the Kaiseki class by getting the API key and creating the translator object.
|
99 |
+
|
100 |
+
"""
|
101 |
+
|
102 |
+
## get saved api key if exists
|
103 |
+
try:
|
104 |
+
|
105 |
+
with open(FileEnsurer.deepl_api_key_path, 'r', encoding='utf-8') as file:
|
106 |
+
api_key = base64.b64decode((file.read()).encode('utf-8')).decode('utf-8')
|
107 |
+
|
108 |
+
DeepLService.set_api_key(api_key)
|
109 |
+
DeepLService.test_api_key_validity()
|
110 |
+
|
111 |
+
Logger.log_action("Used saved api key in " + FileEnsurer.deepl_api_key_path, output=True)
|
112 |
+
|
113 |
+
## else try to get api key manually
|
114 |
+
except Exception as e:
|
115 |
+
|
116 |
+
api_key = input("DO NOT DELETE YOUR COPY OF THE API KEY\n\nPlease enter the deepL api key you have : ")
|
117 |
+
|
118 |
+
## if valid save the api key
|
119 |
+
try:
|
120 |
+
|
121 |
+
DeepLService.set_api_key(api_key)
|
122 |
+
DeepLService.test_api_key_validity()
|
123 |
+
|
124 |
+
time.sleep(.1)
|
125 |
+
|
126 |
+
FileEnsurer.standard_overwrite_file(FileEnsurer.deepl_api_key_path, base64.b64encode(api_key.encode('utf-8')).decode('utf-8'), omit=True)
|
127 |
+
|
128 |
+
time.sleep(.1)
|
129 |
+
|
130 |
+
## if invalid key exit
|
131 |
+
except AuthorizationException:
|
132 |
+
|
133 |
+
Toolkit.clear_console()
|
134 |
+
|
135 |
+
Logger.log_action("Authorization error with creating translator object, please double check your api key as it appears to be incorrect.\nKaiseki will now exit.", output=True)
|
136 |
+
|
137 |
+
Toolkit.pause_console()
|
138 |
+
|
139 |
+
raise e
|
140 |
+
|
141 |
+
## other error, alert user and raise it
|
142 |
+
except Exception as e:
|
143 |
+
|
144 |
+
Toolkit.clear_console()
|
145 |
+
|
146 |
+
Logger.log_action("Unknown error with creating translator object, The error is as follows " + str(e) + "\nKaiseki will now exit.", output=True)
|
147 |
+
|
148 |
+
Toolkit.pause_console()
|
149 |
+
|
150 |
+
raise e
|
151 |
+
|
152 |
+
Toolkit.clear_console()
|
153 |
+
Logger.log_barrier()
|
154 |
+
|
155 |
+
##-------------------start-of-reset_static_variables()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
156 |
+
|
157 |
+
@staticmethod
|
158 |
+
def reset_static_variables() -> None:
|
159 |
+
|
160 |
+
"""
|
161 |
+
|
162 |
+
Resets the static variables of the Kaiseki class.
|
163 |
+
For when running multiple translations in a row through webgui.
|
164 |
+
|
165 |
+
"""
|
166 |
+
|
167 |
+
Logger.clear_batch()
|
168 |
+
|
169 |
+
Kaiseki.text_to_translate = []
|
170 |
+
Kaiseki.translated_text = []
|
171 |
+
Kaiseki.je_check_text = []
|
172 |
+
Kaiseki.error_text = []
|
173 |
+
Kaiseki.translation_print_result = ""
|
174 |
+
Kaiseki.sentence_parts = []
|
175 |
+
Kaiseki.sentence_punctuation = []
|
176 |
+
Kaiseki.special_punctuation = []
|
177 |
+
Kaiseki.current_sentence = ""
|
178 |
+
Kaiseki.translated_sentence = ""
|
179 |
+
|
180 |
+
##-------------------start-of-commence_translation()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
181 |
+
|
182 |
+
@staticmethod
|
183 |
+
def commence_translation() -> None:
|
184 |
+
|
185 |
+
"""
|
186 |
+
|
187 |
+
Commences the translation process using all the functions in the Kaiseki class.
|
188 |
+
|
189 |
+
"""
|
190 |
+
|
191 |
+
i = 0
|
192 |
+
|
193 |
+
while(i < len(Kaiseki.text_to_translate)):
|
194 |
+
|
195 |
+
## for webgui, if the user presses the clear button, raise an exception to stop the translation
|
196 |
+
if(FileEnsurer.do_interrupt == True):
|
197 |
+
raise Exception("Interrupted by user.")
|
198 |
+
|
199 |
+
Kaiseki.current_sentence = Kaiseki.text_to_translate[i]
|
200 |
+
|
201 |
+
Logger.log_action("Initial Sentence : " + Kaiseki.current_sentence)
|
202 |
+
|
203 |
+
## Kaiseki is an in-place translation, so it'll build the translated text into Kaiseki.translated_text as it goes.
|
204 |
+
if(any(char in Kaiseki.current_sentence for char in ["▼", "△", "◇"])):
|
205 |
+
Kaiseki.translated_text.append(Kaiseki.current_sentence + '\n')
|
206 |
+
Logger.log_action("Sentence : " + Kaiseki.current_sentence + ", Sentence is a pov change... leaving intact.")
|
207 |
+
|
208 |
+
elif("part" in Kaiseki.current_sentence.lower() or all(char in ["1","2","3","4","5","6","7","8","9", " "] for char in Kaiseki.current_sentence) and not all(char in [" "] for char in Kaiseki.current_sentence) and Kaiseki.current_sentence != '"..."' and Kaiseki.current_sentence != "..."):
|
209 |
+
Kaiseki.translated_text.append(Kaiseki.current_sentence + '\n')
|
210 |
+
Logger.log_action("Sentence : " + Kaiseki.current_sentence + ", Sentence is part marker... leaving intact.")
|
211 |
+
|
212 |
+
elif bool(re.match(r'^[\W_\s\n-]+$', Kaiseki.current_sentence)) and not any(char in Kaiseki.current_sentence for char in ["」", "「", "«", "»"]):
|
213 |
+
Logger.log_action("Sentence : " + Kaiseki.current_sentence + ", Sentence is punctuation... skipping.")
|
214 |
+
Kaiseki.translated_text.append(Kaiseki.current_sentence + "\n")
|
215 |
+
|
216 |
+
elif(bool(re.match(r'^[A-Za-z0-9\s\.,\'\?!]+\n*$', Kaiseki.current_sentence))):
|
217 |
+
Logger.log_action("Sentence : " + Kaiseki.current_sentence + ", Sentence is english... skipping translation.")
|
218 |
+
Kaiseki.translated_text.append(Kaiseki.current_sentence + "\n")
|
219 |
+
|
220 |
+
elif(len(Kaiseki.current_sentence) == 0 or Kaiseki.current_sentence.isspace() == True):
|
221 |
+
Logger.log_action("Sentence is empty... skipping translation.\n")
|
222 |
+
Kaiseki.translated_text.append(Kaiseki.current_sentence + "\n")
|
223 |
+
|
224 |
+
else:
|
225 |
+
|
226 |
+
Kaiseki.separate_sentence()
|
227 |
+
|
228 |
+
Kaiseki.translate_sentence()
|
229 |
+
|
230 |
+
## this is for adding a period if it's missing
|
231 |
+
if(len(Kaiseki.translated_text[i]) > 0 and Kaiseki.translated_text[i] != "" and Kaiseki.translated_text[i][-2] not in string.punctuation and Kaiseki.sentence_punctuation[-1] == None):
|
232 |
+
Kaiseki.translated_text[i] = Kaiseki.translated_text[i] + "."
|
233 |
+
|
234 |
+
## re-adds quotes
|
235 |
+
if(Kaiseki.special_punctuation[0] == True):
|
236 |
+
Kaiseki.translated_text[i] = '"' + Kaiseki.translated_text[i] + '"'
|
237 |
+
|
238 |
+
## replaces quotes because deepL messes up quotes
|
239 |
+
elif('"' in Kaiseki.translated_text[i]):
|
240 |
+
Kaiseki.translated_text[i] = Kaiseki.translated_text[i].replace('"',"'")
|
241 |
+
|
242 |
+
## re-adds single quotes
|
243 |
+
if(Kaiseki.special_punctuation[3] == True):
|
244 |
+
Kaiseki.translated_text[i] = "'" + Kaiseki.translated_text[i] + "'"
|
245 |
+
|
246 |
+
## re-adds parentheses
|
247 |
+
if(Kaiseki.special_punctuation[4] == True):
|
248 |
+
Kaiseki.translated_text[i] = "(" + Kaiseki.translated_text[i] + ")"
|
249 |
+
|
250 |
+
Logger.log_action("Translated and Reassembled Sentence : " + Kaiseki.translated_text[i])
|
251 |
+
|
252 |
+
Kaiseki.translated_text[i] += "\n"
|
253 |
+
|
254 |
+
Kaiseki.je_check_text.append(str(i+1) + ": " + Kaiseki.current_sentence + "\n " + Kaiseki.translated_text[i] + "\n")
|
255 |
+
|
256 |
+
i+=1
|
257 |
+
|
258 |
+
Toolkit.clear_console()
|
259 |
+
|
260 |
+
Logger.log_action(str(i) + "/" + str(len(Kaiseki.text_to_translate)) + " completed.", output=True)
|
261 |
+
Logger.log_barrier()
|
262 |
+
|
263 |
+
##-------------------start-of-separate_sentence()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
264 |
+
|
265 |
+
@staticmethod
|
266 |
+
def separate_sentence() -> None:
|
267 |
+
|
268 |
+
"""
|
269 |
+
|
270 |
+
This function separates the sentence into parts and punctuation.
|
271 |
+
|
272 |
+
"""
|
273 |
+
|
274 |
+
## resets variables for current_sentence
|
275 |
+
Kaiseki.sentence_parts = []
|
276 |
+
Kaiseki.sentence_punctuation = []
|
277 |
+
Kaiseki.special_punctuation = [False,False,False,False,False]
|
278 |
+
|
279 |
+
i = 0
|
280 |
+
|
281 |
+
buildString = ""
|
282 |
+
|
283 |
+
## checks if quotes are in the sentence and removes them
|
284 |
+
if('"' in Kaiseki.current_sentence):
|
285 |
+
Kaiseki.current_sentence = Kaiseki.current_sentence.replace('"', '')
|
286 |
+
Kaiseki.special_punctuation[0] = True
|
287 |
+
|
288 |
+
## checks if tildes are in the sentence
|
289 |
+
if('~' in Kaiseki.current_sentence):
|
290 |
+
Kaiseki.special_punctuation[1] = True
|
291 |
+
|
292 |
+
## checks if apostrophes are in the sentence but not at the beginning or end
|
293 |
+
if(Kaiseki.current_sentence.count("'") == 2 and (Kaiseki.current_sentence[0] != "'" and Kaiseki.current_sentence[-1] != "'")):
|
294 |
+
Kaiseki.special_punctuation[2] = True
|
295 |
+
|
296 |
+
## checks if apostrophes are in the sentence and removes them
|
297 |
+
elif(Kaiseki.current_sentence.count("'") == 2):
|
298 |
+
Kaiseki.special_punctuation[3] = True
|
299 |
+
Kaiseki.current_sentence = Kaiseki.current_sentence.replace("'", "")
|
300 |
+
|
301 |
+
## checks if parentheses are in the sentence and removes them
|
302 |
+
if("(" in Kaiseki.current_sentence and ")" in Kaiseki.current_sentence):
|
303 |
+
Kaiseki.special_punctuation[4] = True
|
304 |
+
Kaiseki.current_sentence= Kaiseki.current_sentence.replace("(","")
|
305 |
+
Kaiseki.current_sentence= Kaiseki.current_sentence.replace(")","")
|
306 |
+
|
307 |
+
while(i < len(Kaiseki.current_sentence)):
|
308 |
+
|
309 |
+
if(Kaiseki.current_sentence[i] in [".","!","?","-"]):
|
310 |
+
|
311 |
+
if(i+5 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+6] in ["......"]):
|
312 |
+
|
313 |
+
if(i+6 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+7] in ["......'"]):
|
314 |
+
buildString += "'"
|
315 |
+
i+=1
|
316 |
+
|
317 |
+
if(buildString != ""):
|
318 |
+
Kaiseki.sentence_parts.append(buildString)
|
319 |
+
|
320 |
+
Kaiseki.sentence_punctuation.append(Kaiseki.current_sentence[i:i+6])
|
321 |
+
i+=5
|
322 |
+
buildString = ""
|
323 |
+
|
324 |
+
if(i+4 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+5] in [".....","...!?"]):
|
325 |
+
|
326 |
+
if(i+5 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+6] in [".....'","...!?'"]):
|
327 |
+
buildString += "'"
|
328 |
+
i+=1
|
329 |
+
|
330 |
+
if(buildString != ""):
|
331 |
+
Kaiseki.sentence_parts.append(buildString)
|
332 |
+
|
333 |
+
Kaiseki.sentence_punctuation.append(Kaiseki.current_sentence[i:i+5])
|
334 |
+
i+=4
|
335 |
+
buildString = ""
|
336 |
+
|
337 |
+
elif(i+3 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+4] in ["...!","...?","---.","....","!..."]):
|
338 |
+
|
339 |
+
if(i+4 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+5] in ["...!'","...?'","---.'","....'","!...'"]):
|
340 |
+
buildString += "'"
|
341 |
+
i+=1
|
342 |
+
|
343 |
+
if(buildString != ""):
|
344 |
+
Kaiseki.sentence_parts.append(buildString)
|
345 |
+
|
346 |
+
Kaiseki.sentence_punctuation.append(Kaiseki.current_sentence[i:i+4])
|
347 |
+
i+=3
|
348 |
+
buildString = ""
|
349 |
+
|
350 |
+
elif(i+2 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+3] in ["---","..."]):
|
351 |
+
|
352 |
+
if(i+3 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+4] in ["---'","...'"]):
|
353 |
+
buildString += "'"
|
354 |
+
i+=1
|
355 |
+
|
356 |
+
if(buildString != ""):
|
357 |
+
Kaiseki.sentence_parts.append(buildString)
|
358 |
+
|
359 |
+
Kaiseki.sentence_punctuation.append(Kaiseki.current_sentence[i:i+3])
|
360 |
+
i+=2
|
361 |
+
buildString = ""
|
362 |
+
|
363 |
+
elif(i+1 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+2] == '!?'):
|
364 |
+
|
365 |
+
if(i+2 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i:i+3] == "!?'"):
|
366 |
+
buildString += "'"
|
367 |
+
i+=1
|
368 |
+
|
369 |
+
if(buildString != ""):
|
370 |
+
Kaiseki.sentence_parts.append(buildString)
|
371 |
+
|
372 |
+
Kaiseki.sentence_punctuation.append(Kaiseki.current_sentence[i:i+2])
|
373 |
+
i+=1
|
374 |
+
buildString = ""
|
375 |
+
|
376 |
+
## if punctuation that was found is not a hyphen then just follow normal punctuation separation rules
|
377 |
+
elif(Kaiseki.current_sentence[i] != "-"):
|
378 |
+
|
379 |
+
if(i+1 < len(Kaiseki.current_sentence) and Kaiseki.current_sentence[i+1] == "'"):
|
380 |
+
buildString += "'"
|
381 |
+
|
382 |
+
if(buildString != ""):
|
383 |
+
Kaiseki.sentence_parts.append(buildString)
|
384 |
+
|
385 |
+
Kaiseki.sentence_punctuation.append(Kaiseki.current_sentence[i])
|
386 |
+
buildString = ""
|
387 |
+
|
388 |
+
## if it is just a singular hyphen, do not consider it punctuation as they are used in honorifics
|
389 |
+
else:
|
390 |
+
buildString += Kaiseki.current_sentence[i]
|
391 |
+
else:
|
392 |
+
buildString += Kaiseki.current_sentence[i]
|
393 |
+
|
394 |
+
i += 1
|
395 |
+
|
396 |
+
## if end of line, add none punctuation which means a period needs to be added later
|
397 |
+
if(buildString):
|
398 |
+
Kaiseki.sentence_parts.append(buildString)
|
399 |
+
Kaiseki.sentence_punctuation.append(None)
|
400 |
+
|
401 |
+
Logger.log_action("Fragmented Sentence Parts " + str(Kaiseki.sentence_parts))
|
402 |
+
Logger.log_action("Sentence Punctuation " + str(Kaiseki.sentence_punctuation))
|
403 |
+
Logger.log_action("Does Sentence Have Special Punctuation : " + str(Kaiseki.special_punctuation))
|
404 |
+
|
405 |
+
## strip the sentence parts
|
406 |
+
Kaiseki.sentence_parts = [part.strip() for part in Kaiseki.sentence_parts]
|
407 |
+
|
408 |
+
##-------------------start-of-translate_sentence()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
409 |
+
|
410 |
+
@staticmethod
|
411 |
+
def translate_sentence() -> None:
|
412 |
+
|
413 |
+
"""
|
414 |
+
|
415 |
+
This function translates each part of a sentence.
|
416 |
+
|
417 |
+
"""
|
418 |
+
|
419 |
+
i = 0
|
420 |
+
ii = 0
|
421 |
+
|
422 |
+
quote = ""
|
423 |
+
error = ""
|
424 |
+
|
425 |
+
tilde_active = False
|
426 |
+
single_quote_active = False
|
427 |
+
|
428 |
+
while(i < len(Kaiseki.sentence_parts)):
|
429 |
+
|
430 |
+
## if tilde is present in part, delete it and set tilde active to true, so we can add it back in a bit
|
431 |
+
if(Kaiseki.special_punctuation[1] == True and "~" in Kaiseki.sentence_parts[i]):
|
432 |
+
Kaiseki.sentence_parts[i] = Kaiseki.sentence_parts[i].replace("~","")
|
433 |
+
tilde_active = True
|
434 |
+
|
435 |
+
## a quote is present in the sentence, but not enclosing the sentence, we need to isolate it
|
436 |
+
if(Kaiseki.special_punctuation[2] == True and "'" in Kaiseki.sentence_parts[i] and (Kaiseki.sentence_parts[i][0] != "'" and Kaiseki.sentence_parts[i][-1] != "'")):
|
437 |
+
|
438 |
+
sentence = Kaiseki.sentence_parts[i]
|
439 |
+
substring_start = sentence.index("'")
|
440 |
+
substring_end = 0
|
441 |
+
quote = ""
|
442 |
+
|
443 |
+
ii = substring_start
|
444 |
+
while(ii < len(sentence)):
|
445 |
+
if(sentence[ii] == "'"):
|
446 |
+
substring_end = ii
|
447 |
+
ii+=1
|
448 |
+
|
449 |
+
quote = sentence[substring_start+1:substring_end]
|
450 |
+
Kaiseki.sentence_parts[i] = sentence[:substring_start+1] + "quote" + sentence[substring_end:]
|
451 |
+
|
452 |
+
single_quote_active = True
|
453 |
+
|
454 |
+
try:
|
455 |
+
results = DeepLService.translate(Kaiseki.sentence_parts[i], source_lang= "JA", target_lang="EN-US")
|
456 |
+
|
457 |
+
translated_part = results.rstrip(''.join(c for c in string.punctuation if c not in "'\""))
|
458 |
+
translated_part = translated_part.rstrip()
|
459 |
+
|
460 |
+
## here we re-add the tilde, (note not always accurate but mostly is)
|
461 |
+
if(tilde_active == True):
|
462 |
+
translated_part += "~"
|
463 |
+
tilde_active = False
|
464 |
+
|
465 |
+
## translates the quote and re-adds it back to the sentence part
|
466 |
+
if(single_quote_active == True):
|
467 |
+
quote = DeepLService.translate(quote, source_lang= "JA", target_lang="EN-US")
|
468 |
+
|
469 |
+
quote = quote.rstrip(''.join(c for c in string.punctuation if c not in "'\""))
|
470 |
+
quote = quote.rstrip()
|
471 |
+
|
472 |
+
translated_part = translated_part.replace("'quote'","'" + quote + "'",1)
|
473 |
+
|
474 |
+
## if punctuation appears first and before any text, add the punctuation and remove it form the list.
|
475 |
+
if(len(Kaiseki.sentence_punctuation) > len(Kaiseki.sentence_parts)):
|
476 |
+
Kaiseki.translated_sentence += Kaiseki.sentence_punctuation[0]
|
477 |
+
Kaiseki.sentence_punctuation.pop(0)
|
478 |
+
|
479 |
+
if(Kaiseki.sentence_punctuation[i] != None):
|
480 |
+
Kaiseki.translated_sentence += translated_part + Kaiseki.sentence_punctuation[i]
|
481 |
+
else:
|
482 |
+
Kaiseki.translated_sentence += translated_part
|
483 |
+
|
484 |
+
if(i != len(Kaiseki.sentence_punctuation)-1):
|
485 |
+
Kaiseki.translated_sentence += " "
|
486 |
+
|
487 |
+
except QuotaExceededException as e:
|
488 |
+
|
489 |
+
Logger.log_action("DeepL API quota exceeded.", output=True)
|
490 |
+
|
491 |
+
Toolkit.pause_console()
|
492 |
+
|
493 |
+
raise e
|
494 |
+
|
495 |
+
except ValueError as e:
|
496 |
+
|
497 |
+
if(str(e) == "Text must not be empty."):
|
498 |
+
Kaiseki.translated_sentence += ""
|
499 |
+
else:
|
500 |
+
Kaiseki.translated_sentence += "ERROR"
|
501 |
+
error = str(e)
|
502 |
+
|
503 |
+
Logger.log_action("Error is : " + error)
|
504 |
+
Kaiseki.error_text.append("Error is : " + error)
|
505 |
+
|
506 |
+
i+=1
|
507 |
+
|
508 |
+
Kaiseki.translated_text.append(Kaiseki.translated_sentence)
|
509 |
+
Kaiseki.translated_sentence = ""
|
510 |
+
|
511 |
+
##-------------------start-of-assemble_results()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
512 |
+
|
513 |
+
@staticmethod
|
514 |
+
def assemble_results(time_start:float, time_end:float) -> None:
|
515 |
+
|
516 |
+
"""
|
517 |
+
|
518 |
+
Prepares the results of the translation for printing.
|
519 |
+
|
520 |
+
Parameters:
|
521 |
+
time_start (float) : the time the translation started.
|
522 |
+
time_end (float) : the time the translation ended.
|
523 |
+
|
524 |
+
"""
|
525 |
+
|
526 |
+
Kaiseki.translation_print_result += "Time Elapsed : " + Toolkit.get_elapsed_time(time_start, time_end)
|
527 |
+
|
528 |
+
Kaiseki.translation_print_result += "\n\nDebug text have been written to : " + FileEnsurer.debug_log_path
|
529 |
+
Kaiseki.translation_print_result += "\nJ->E text have been written to : " + FileEnsurer.je_check_path
|
530 |
+
Kaiseki.translation_print_result += "\nTranslated text has been written to : " + FileEnsurer.translated_text_path
|
531 |
+
Kaiseki.translation_print_result += "\nErrors have been written to : " + FileEnsurer.error_log_path + "\n"
|
532 |
+
|
533 |
+
##-------------------start-of-write_kaiseki_results()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
534 |
+
|
535 |
+
@staticmethod
|
536 |
+
@permission_error_decorator()
|
537 |
+
def write_kaiseki_results() -> None:
|
538 |
+
|
539 |
+
"""
|
540 |
+
|
541 |
+
This function is called to write the results of the Kaiseki translation module to the output directory.
|
542 |
+
|
543 |
+
"""
|
544 |
+
|
545 |
+
## ensures the output directory exists, cause it could get moved or fucked with.
|
546 |
+
FileEnsurer.standard_create_directory(FileEnsurer.output_dir)
|
547 |
+
|
548 |
+
with open(FileEnsurer.error_log_path, 'a+', encoding='utf-8') as file:
|
549 |
+
file.writelines(Kaiseki.error_text)
|
550 |
+
|
551 |
+
with open(FileEnsurer.je_check_path, 'w', encoding='utf-8') as file:
|
552 |
+
file.writelines(Kaiseki.je_check_text)
|
553 |
+
|
554 |
+
with open(FileEnsurer.translated_text_path, 'w', encoding='utf-8') as file:
|
555 |
+
file.writelines(Kaiseki.translated_text)
|
556 |
+
|
557 |
+
## Instructions to create a copy of the output for archival
|
558 |
+
FileEnsurer.standard_create_directory(FileEnsurer.archive_dir)
|
559 |
+
|
560 |
+
timestamp = Toolkit.get_timestamp(is_archival=True)
|
561 |
+
|
562 |
+
## pushes the tl debug log to the file without clearing the file
|
563 |
+
Logger.push_batch()
|
564 |
+
Logger.clear_batch()
|
565 |
+
|
566 |
+
list_of_result_tuples = [('kaiseki_translated_text', Kaiseki.translated_text),
|
567 |
+
('kaiseki_je_check_text', Kaiseki.je_check_text),
|
568 |
+
('kaiseki_error_log', Kaiseki.error_text),
|
569 |
+
('debug_log', FileEnsurer.standard_read_file(Logger.log_file_path))]
|
570 |
+
|
571 |
+
FileEnsurer.archive_results(list_of_result_tuples,
|
572 |
+
module='kaiseki', timestamp=timestamp)
|
models/kijiku.py
ADDED
@@ -0,0 +1,1154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libaries
|
2 |
+
import typing
|
3 |
+
import base64
|
4 |
+
import re
|
5 |
+
import time
|
6 |
+
import typing
|
7 |
+
import asyncio
|
8 |
+
import os
|
9 |
+
|
10 |
+
## third party modules
|
11 |
+
from kairyou import KatakanaUtil
|
12 |
+
|
13 |
+
import tiktoken
|
14 |
+
import backoff
|
15 |
+
|
16 |
+
## custom modules
|
17 |
+
from handlers.json_handler import JsonHandler
|
18 |
+
|
19 |
+
from modules.common.file_ensurer import FileEnsurer
|
20 |
+
from modules.common.logger import Logger
|
21 |
+
from modules.common.toolkit import Toolkit
|
22 |
+
from modules.common.exceptions import AuthenticationError, MaxBatchDurationExceededException, AuthenticationError, InternalServerError, RateLimitError, APITimeoutError
|
23 |
+
from modules.common.decorators import permission_error_decorator
|
24 |
+
|
25 |
+
from custom_classes.messages import SystemTranslationMessage, ModelTranslationMessage, Message
|
26 |
+
|
27 |
+
from translation_services.openai_service import OpenAIService
|
28 |
+
from translation_services.gemini_service import GeminiService
|
29 |
+
|
30 |
+
##-------------------start-of-Kijiku--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
31 |
+
|
32 |
+
class Kijiku:
|
33 |
+
|
34 |
+
"""
|
35 |
+
|
36 |
+
Kijiku is a secondary class that is used to interact with LLMs and translate text.
|
37 |
+
Currently supports OpenAI and Gemini.
|
38 |
+
|
39 |
+
"""
|
40 |
+
|
41 |
+
text_to_translate:typing.List[str] = []
|
42 |
+
|
43 |
+
translated_text:typing.List[str] = []
|
44 |
+
|
45 |
+
je_check_text:typing.List[str] = []
|
46 |
+
|
47 |
+
error_text:typing.List[str] = []
|
48 |
+
|
49 |
+
## the messages that will be sent to the api, contains a system message and a model message, system message is the instructions,
|
50 |
+
## model message is the text that will be translated
|
51 |
+
openai_translation_batches:typing.List[Message] = []
|
52 |
+
|
53 |
+
## meanwhile for gemini, we just need to send the prompt and the text to be translated concatenated together
|
54 |
+
gemini_translation_batches:typing.List[str] = []
|
55 |
+
|
56 |
+
num_occurred_malformed_batches = 0
|
57 |
+
|
58 |
+
## semaphore to limit the number of concurrent batches
|
59 |
+
_semaphore = asyncio.Semaphore(5)
|
60 |
+
|
61 |
+
##--------------------------------------------------------------------------------------------------------------------------
|
62 |
+
|
63 |
+
LLM_TYPE:typing.Literal["openai", "gemini"] = "openai"
|
64 |
+
|
65 |
+
translation_print_result = ""
|
66 |
+
|
67 |
+
##--------------------------------------------------------------------------------------------------------------------------
|
68 |
+
|
69 |
+
prompt_assembly_mode:int
|
70 |
+
number_of_lines_per_batch:int
|
71 |
+
sentence_fragmenter_mode:int
|
72 |
+
je_check_mode:int
|
73 |
+
number_of_malformed_batch_retries:int
|
74 |
+
batch_retry_timeout:float
|
75 |
+
num_concurrent_batches:int
|
76 |
+
|
77 |
+
##-------------------start-of-get_max_batch_duration()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
78 |
+
|
79 |
+
@staticmethod
|
80 |
+
def get_max_batch_duration() -> float:
|
81 |
+
|
82 |
+
"""
|
83 |
+
|
84 |
+
Returns the max batch duration.
|
85 |
+
Structured as a function so that it can be used as a lambda function in the backoff decorator. As decorators call the function when they are defined/runtime, not when they are called.
|
86 |
+
|
87 |
+
Returns:
|
88 |
+
max_batch_duration (float) : the max batch duration.
|
89 |
+
|
90 |
+
"""
|
91 |
+
|
92 |
+
return Kijiku.max_batch_duration
|
93 |
+
|
94 |
+
##-------------------start-of-log_retry()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
95 |
+
|
96 |
+
@staticmethod
|
97 |
+
def log_retry(details) -> None:
|
98 |
+
|
99 |
+
"""
|
100 |
+
|
101 |
+
Logs the retry message.
|
102 |
+
|
103 |
+
Parameters:
|
104 |
+
details (dict) : the details of the retry.
|
105 |
+
|
106 |
+
"""
|
107 |
+
|
108 |
+
retry_msg = f"Retrying translation after {details['wait']} seconds after {details['tries']} tries {details['target']} due to {details['exception']}."
|
109 |
+
|
110 |
+
Logger.log_barrier()
|
111 |
+
Logger.log_action(retry_msg)
|
112 |
+
Logger.log_barrier()
|
113 |
+
|
114 |
+
##-------------------start-of-log_failure()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
115 |
+
|
116 |
+
@staticmethod
|
117 |
+
def log_failure(details) -> None:
|
118 |
+
|
119 |
+
"""
|
120 |
+
|
121 |
+
Logs the translation batch failure message.
|
122 |
+
|
123 |
+
Parameters:
|
124 |
+
details (dict) : the details of the failure.
|
125 |
+
|
126 |
+
"""
|
127 |
+
|
128 |
+
error_msg = f"Exceeded duration, returning untranslated text after {details['tries']} tries {details['target']}."
|
129 |
+
|
130 |
+
Logger.log_barrier()
|
131 |
+
Logger.log_error(error_msg)
|
132 |
+
Logger.log_barrier()
|
133 |
+
|
134 |
+
raise MaxBatchDurationExceededException(error_msg)
|
135 |
+
|
136 |
+
##-------------------start-of-translate()--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
137 |
+
|
138 |
+
@staticmethod
|
139 |
+
async def translate() -> None:
|
140 |
+
|
141 |
+
"""
|
142 |
+
|
143 |
+
Translate the text in the file at the path given.
|
144 |
+
|
145 |
+
"""
|
146 |
+
|
147 |
+
Logger.clear_batch()
|
148 |
+
|
149 |
+
## set this here cause the try-except could throw before we get past the settings configuration
|
150 |
+
time_start = time.time()
|
151 |
+
|
152 |
+
try:
|
153 |
+
|
154 |
+
await Kijiku.initialize()
|
155 |
+
|
156 |
+
JsonHandler.validate_json()
|
157 |
+
|
158 |
+
await Kijiku.check_settings()
|
159 |
+
|
160 |
+
## set actual start time to the end of the settings configuration
|
161 |
+
time_start = time.time()
|
162 |
+
|
163 |
+
await Kijiku.commence_translation()
|
164 |
+
|
165 |
+
except Exception as e:
|
166 |
+
|
167 |
+
Kijiku.translation_print_result += "An error has occurred, outputting results so far..."
|
168 |
+
|
169 |
+
FileEnsurer.handle_critical_exception(e)
|
170 |
+
|
171 |
+
finally:
|
172 |
+
|
173 |
+
time_end = time.time()
|
174 |
+
|
175 |
+
Kijiku.assemble_results(time_start, time_end)
|
176 |
+
|
177 |
+
##-------------------start-of-initialize()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
178 |
+
|
179 |
+
@staticmethod
|
180 |
+
async def initialize() -> None:
|
181 |
+
|
182 |
+
"""
|
183 |
+
|
184 |
+
Sets the API Key for the respective service and loads the kijiku rules.
|
185 |
+
|
186 |
+
"""
|
187 |
+
|
188 |
+
print("What LLM do you want to use? (1 for OpenAI or 2 for Gemini) : ")
|
189 |
+
|
190 |
+
if(input("\n") == "1"):
|
191 |
+
Kijiku.LLM_TYPE = "openai"
|
192 |
+
|
193 |
+
else:
|
194 |
+
Kijiku.LLM_TYPE = "gemini"
|
195 |
+
|
196 |
+
Toolkit.clear_console()
|
197 |
+
|
198 |
+
if(Kijiku.LLM_TYPE == "openai"):
|
199 |
+
await Kijiku.init_api_key("OpenAI", FileEnsurer.openai_api_key_path, OpenAIService.set_api_key, OpenAIService.test_api_key_validity)
|
200 |
+
|
201 |
+
else:
|
202 |
+
await Kijiku.init_api_key("Gemini", FileEnsurer.gemini_api_key_path, GeminiService.set_api_key, GeminiService.test_api_key_validity)
|
203 |
+
|
204 |
+
## try to load the kijiku rules
|
205 |
+
try:
|
206 |
+
|
207 |
+
JsonHandler.load_kijiku_rules()
|
208 |
+
|
209 |
+
## if the kijiku rules don't exist, create them
|
210 |
+
except:
|
211 |
+
|
212 |
+
JsonHandler.reset_kijiku_rules_to_default()
|
213 |
+
|
214 |
+
JsonHandler.load_kijiku_rules()
|
215 |
+
|
216 |
+
Toolkit.clear_console()
|
217 |
+
|
218 |
+
##-------------------start-of-init_openai_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
219 |
+
|
220 |
+
@staticmethod
|
221 |
+
async def init_api_key(service:str, api_key_path:str, api_key_setter:typing.Callable, api_key_tester:typing.Callable) -> None:
|
222 |
+
|
223 |
+
"""
|
224 |
+
|
225 |
+
Sets up the api key for the respective service.
|
226 |
+
|
227 |
+
Parameters:
|
228 |
+
service (string) : the name of the service.
|
229 |
+
api_key_path (string) : the path to the api key.
|
230 |
+
api_key_setter (callable) : the function that sets the api key.
|
231 |
+
api_key_tester (callable) : the function that tests the api key.
|
232 |
+
|
233 |
+
"""
|
234 |
+
|
235 |
+
if(service != "OpenAI"):
|
236 |
+
GeminiService.redefine_client()
|
237 |
+
|
238 |
+
## get saved API key if exists
|
239 |
+
try:
|
240 |
+
with open(api_key_path, 'r', encoding='utf-8') as file:
|
241 |
+
api_key = base64.b64decode((file.read()).encode('utf-8')).decode('utf-8')
|
242 |
+
|
243 |
+
api_key_setter(api_key)
|
244 |
+
|
245 |
+
is_valid, e = await api_key_tester()
|
246 |
+
|
247 |
+
## if not valid, raise the exception that caused the test to fail
|
248 |
+
if(not is_valid and e is not None):
|
249 |
+
raise e
|
250 |
+
|
251 |
+
Logger.log_action("Used saved API key in " + api_key_path, output=True)
|
252 |
+
Logger.log_barrier()
|
253 |
+
|
254 |
+
time.sleep(2)
|
255 |
+
|
256 |
+
## else try to get API key manually
|
257 |
+
except:
|
258 |
+
|
259 |
+
Toolkit.clear_console()
|
260 |
+
|
261 |
+
api_key = input(f"DO NOT DELETE YOUR COPY OF THE API KEY\n\nPlease enter the {service} API key you have : ")
|
262 |
+
|
263 |
+
## if valid save the API key
|
264 |
+
try:
|
265 |
+
|
266 |
+
api_key_setter(api_key)
|
267 |
+
|
268 |
+
is_valid, e = await api_key_tester()
|
269 |
+
|
270 |
+
if(not is_valid and e is not None):
|
271 |
+
raise e
|
272 |
+
|
273 |
+
FileEnsurer.standard_overwrite_file(api_key_path, base64.b64encode(api_key.encode('utf-8')).decode('utf-8'), omit=True)
|
274 |
+
|
275 |
+
## if invalid key exit
|
276 |
+
except AuthenticationError:
|
277 |
+
|
278 |
+
Toolkit.clear_console()
|
279 |
+
|
280 |
+
Logger.log_action(f"Authorization error while setting up {service}, please double check your API key as it appears to be incorrect.", output=True)
|
281 |
+
|
282 |
+
Toolkit.pause_console()
|
283 |
+
|
284 |
+
exit()
|
285 |
+
|
286 |
+
## other error, alert user and raise it
|
287 |
+
except Exception as e:
|
288 |
+
|
289 |
+
Toolkit.clear_console()
|
290 |
+
|
291 |
+
Logger.log_action(f"Unknown error while setting up {service}, The error is as follows " + str(e) + "\nThe exception will now be raised.", output=True)
|
292 |
+
|
293 |
+
Toolkit.pause_console()
|
294 |
+
|
295 |
+
raise e
|
296 |
+
|
297 |
+
##-------------------start-of-reset_static_variables()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
298 |
+
|
299 |
+
@staticmethod
|
300 |
+
def reset_static_variables() -> None:
|
301 |
+
|
302 |
+
"""
|
303 |
+
|
304 |
+
Resets the static variables.
|
305 |
+
Done to prevent issues with the webgui.
|
306 |
+
|
307 |
+
"""
|
308 |
+
|
309 |
+
Logger.clear_batch()
|
310 |
+
|
311 |
+
Kijiku.text_to_translate = []
|
312 |
+
Kijiku.translated_text = []
|
313 |
+
Kijiku.je_check_text = []
|
314 |
+
Kijiku.error_text = []
|
315 |
+
Kijiku.openai_translation_batches = []
|
316 |
+
Kijiku.gemini_translation_batches = []
|
317 |
+
Kijiku.num_occurred_malformed_batches = 0
|
318 |
+
Kijiku.translation_print_result = ""
|
319 |
+
Kijiku.LLM_TYPE = "openai"
|
320 |
+
|
321 |
+
##-------------------start-of-check-settings()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
322 |
+
|
323 |
+
@staticmethod
|
324 |
+
async def check_settings() -> None:
|
325 |
+
|
326 |
+
"""
|
327 |
+
|
328 |
+
Prompts the user to confirm the settings in the kijiku rules file.
|
329 |
+
|
330 |
+
"""
|
331 |
+
|
332 |
+
print("Are these settings okay? (1 for yes or 2 for no) : \n\n")
|
333 |
+
|
334 |
+
try:
|
335 |
+
|
336 |
+
JsonHandler.print_kijiku_rules(output=True)
|
337 |
+
|
338 |
+
except:
|
339 |
+
Toolkit.clear_console()
|
340 |
+
|
341 |
+
if(input("It's likely that you're using an outdated version of the kijiku rules file, press 1 to reset these to default or 2 to exit and resolve manually : ") == "1"):
|
342 |
+
Toolkit.clear_console()
|
343 |
+
JsonHandler.reset_kijiku_rules_to_default()
|
344 |
+
JsonHandler.load_kijiku_rules()
|
345 |
+
|
346 |
+
print("Are these settings okay? (1 for yes or 2 for no) : \n\n")
|
347 |
+
JsonHandler.print_kijiku_rules(output=True)
|
348 |
+
|
349 |
+
else:
|
350 |
+
FileEnsurer.exit_kudasai()
|
351 |
+
|
352 |
+
if(input("\n") == "1"):
|
353 |
+
pass
|
354 |
+
else:
|
355 |
+
JsonHandler.change_kijiku_settings()
|
356 |
+
|
357 |
+
Toolkit.clear_console()
|
358 |
+
|
359 |
+
print("Do you want to change your API key? (1 for yes or 2 for no) : ")
|
360 |
+
|
361 |
+
if(input("\n") == "1"):
|
362 |
+
|
363 |
+
if(Kijiku.LLM_TYPE == "openai"):
|
364 |
+
|
365 |
+
if(os.path.exists(FileEnsurer.openai_api_key_path)):
|
366 |
+
|
367 |
+
os.remove(FileEnsurer.openai_api_key_path)
|
368 |
+
await Kijiku.init_api_key("OpenAI", FileEnsurer.openai_api_key_path, OpenAIService.set_api_key, OpenAIService.test_api_key_validity)
|
369 |
+
|
370 |
+
else:
|
371 |
+
|
372 |
+
if(os.path.exists(FileEnsurer.gemini_api_key_path)):
|
373 |
+
|
374 |
+
os.remove(FileEnsurer.gemini_api_key_path)
|
375 |
+
await Kijiku.init_api_key("Gemini", FileEnsurer.gemini_api_key_path, GeminiService.set_api_key, GeminiService.test_api_key_validity)
|
376 |
+
|
377 |
+
Toolkit.clear_console()
|
378 |
+
|
379 |
+
##-------------------start-of-commence_translation()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
380 |
+
|
381 |
+
@staticmethod
|
382 |
+
async def commence_translation(is_webgui:bool=False) -> None:
|
383 |
+
|
384 |
+
"""
|
385 |
+
|
386 |
+
Uses all the other functions to translate the text provided by Kudasai.
|
387 |
+
|
388 |
+
Parameters:
|
389 |
+
is_webgui (bool | optional | default=False) : A bool representing whether the function is being called by the webgui.
|
390 |
+
|
391 |
+
"""
|
392 |
+
|
393 |
+
Logger.log_barrier()
|
394 |
+
Logger.log_action("Kijiku Activated, Settings are as follows : ")
|
395 |
+
Logger.log_barrier()
|
396 |
+
|
397 |
+
JsonHandler.print_kijiku_rules()
|
398 |
+
|
399 |
+
Kijiku.prompt_assembly_mode = int(JsonHandler.current_kijiku_rules["base kijiku settings"]["prompt_assembly_mode"])
|
400 |
+
Kijiku.number_of_lines_per_batch = int(JsonHandler.current_kijiku_rules["base kijiku settings"]["number_of_lines_per_batch"])
|
401 |
+
Kijiku.sentence_fragmenter_mode = int(JsonHandler.current_kijiku_rules["base kijiku settings"]["sentence_fragmenter_mode"])
|
402 |
+
Kijiku.je_check_mode = int(JsonHandler.current_kijiku_rules["base kijiku settings"]["je_check_mode"])
|
403 |
+
Kijiku.num_of_malform_retries = int(JsonHandler.current_kijiku_rules["base kijiku settings"]["number_of_malformed_batch_retries"])
|
404 |
+
Kijiku.max_batch_duration = float(JsonHandler.current_kijiku_rules["base kijiku settings"]["batch_retry_timeout"])
|
405 |
+
Kijiku.num_concurrent_batches = int(JsonHandler.current_kijiku_rules["base kijiku settings"]["number_of_concurrent_batches"])
|
406 |
+
|
407 |
+
Kijiku._semaphore = asyncio.Semaphore(Kijiku.num_concurrent_batches)
|
408 |
+
|
409 |
+
OpenAIService.model = JsonHandler.current_kijiku_rules["openai settings"]["openai_model"]
|
410 |
+
OpenAIService.system_message = JsonHandler.current_kijiku_rules["openai settings"]["openai_system_message"]
|
411 |
+
OpenAIService.temperature = float(JsonHandler.current_kijiku_rules["openai settings"]["openai_temperature"])
|
412 |
+
OpenAIService.top_p = float(JsonHandler.current_kijiku_rules["openai settings"]["openai_top_p"])
|
413 |
+
OpenAIService.n = int(JsonHandler.current_kijiku_rules["openai settings"]["openai_n"])
|
414 |
+
OpenAIService.stream = bool(JsonHandler.current_kijiku_rules["openai settings"]["openai_stream"])
|
415 |
+
OpenAIService.stop = JsonHandler.current_kijiku_rules["openai settings"]["openai_stop"]
|
416 |
+
OpenAIService.logit_bias = JsonHandler.current_kijiku_rules["openai settings"]["openai_logit_bias"]
|
417 |
+
OpenAIService.max_tokens = JsonHandler.current_kijiku_rules["openai settings"]["openai_max_tokens"]
|
418 |
+
OpenAIService.presence_penalty = float(JsonHandler.current_kijiku_rules["openai settings"]["openai_presence_penalty"])
|
419 |
+
OpenAIService.frequency_penalty = float(JsonHandler.current_kijiku_rules["openai settings"]["openai_frequency_penalty"])
|
420 |
+
|
421 |
+
GeminiService.model = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_model"]
|
422 |
+
GeminiService.prompt = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_prompt"]
|
423 |
+
GeminiService.temperature = float(JsonHandler.current_kijiku_rules["gemini settings"]["gemini_temperature"])
|
424 |
+
GeminiService.top_p = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_top_p"]
|
425 |
+
GeminiService.top_k = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_top_k"]
|
426 |
+
GeminiService.candidate_count = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_candidate_count"]
|
427 |
+
GeminiService.stream = bool(JsonHandler.current_kijiku_rules["gemini settings"]["gemini_stream"])
|
428 |
+
GeminiService.stop_sequences = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_stop_sequences"]
|
429 |
+
GeminiService.max_output_tokens = JsonHandler.current_kijiku_rules["gemini settings"]["gemini_max_output_tokens"]
|
430 |
+
|
431 |
+
if(Kijiku.LLM_TYPE == "openai"):
|
432 |
+
|
433 |
+
## set the decorator to use
|
434 |
+
decorator_to_use = backoff.on_exception(backoff.expo, max_time=lambda: Kijiku.get_max_batch_duration(), exception=(AuthenticationError, InternalServerError, RateLimitError, APITimeoutError), on_backoff=lambda details: Kijiku.log_retry(details), on_giveup=lambda details: Kijiku.log_failure(details), raise_on_giveup=False)
|
435 |
+
|
436 |
+
OpenAIService.set_decorator(decorator_to_use)
|
437 |
+
|
438 |
+
else:
|
439 |
+
|
440 |
+
decorator_to_use = backoff.on_exception(backoff.expo, max_time=lambda: Kijiku.get_max_batch_duration(), exception=(Exception), on_backoff=lambda details: Kijiku.log_retry(details), on_giveup=lambda details: Kijiku.log_failure(details), raise_on_giveup=False)
|
441 |
+
|
442 |
+
GeminiService.redefine_client()
|
443 |
+
GeminiService.set_decorator(decorator_to_use)
|
444 |
+
|
445 |
+
Toolkit.clear_console()
|
446 |
+
|
447 |
+
Logger.log_barrier()
|
448 |
+
Logger.log_action("Starting Prompt Building")
|
449 |
+
Logger.log_barrier()
|
450 |
+
|
451 |
+
if(Kijiku.LLM_TYPE == "openai"):
|
452 |
+
Kijiku.build_openai_translation_batches()
|
453 |
+
model = OpenAIService.model
|
454 |
+
|
455 |
+
else:
|
456 |
+
Kijiku.build_gemini_translation_batches()
|
457 |
+
model = GeminiService.model
|
458 |
+
|
459 |
+
await Kijiku.handle_cost_estimate_prompt(model, omit_prompt=is_webgui)
|
460 |
+
|
461 |
+
Toolkit.clear_console()
|
462 |
+
|
463 |
+
Logger.log_barrier()
|
464 |
+
|
465 |
+
Logger.log_action("Starting Translation...", output=not is_webgui)
|
466 |
+
Logger.log_barrier()
|
467 |
+
|
468 |
+
## requests to run asynchronously
|
469 |
+
async_requests = Kijiku.build_async_requests(model)
|
470 |
+
|
471 |
+
## Use asyncio.gather to run tasks concurrently/asynchronously and wait for all of them to complete
|
472 |
+
results = await asyncio.gather(*async_requests)
|
473 |
+
|
474 |
+
Logger.log_barrier()
|
475 |
+
Logger.log_action("Translation Complete!", output=not is_webgui)
|
476 |
+
|
477 |
+
Logger.log_barrier()
|
478 |
+
Logger.log_action("Starting Redistribution...", output=not is_webgui)
|
479 |
+
|
480 |
+
Logger.log_barrier()
|
481 |
+
|
482 |
+
## Sort results based on the index to maintain order
|
483 |
+
sorted_results = sorted(results, key=lambda x: x[0])
|
484 |
+
|
485 |
+
## Redistribute the sorted results
|
486 |
+
for index, translated_prompt, translated_message in sorted_results:
|
487 |
+
Kijiku.redistribute(translated_prompt, translated_message)
|
488 |
+
|
489 |
+
## try to pair the text for j-e checking if the mode is 2
|
490 |
+
if(Kijiku.je_check_mode == 2):
|
491 |
+
Kijiku.je_check_text = Kijiku.fix_je()
|
492 |
+
|
493 |
+
Toolkit.clear_console()
|
494 |
+
|
495 |
+
Logger.log_action("Done!", output=not is_webgui)
|
496 |
+
Logger.log_barrier()
|
497 |
+
|
498 |
+
## assemble error text based of the error list
|
499 |
+
Kijiku.error_text = Logger.errors
|
500 |
+
|
501 |
+
##-------------------start-of-build_async_requests()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
502 |
+
|
503 |
+
@staticmethod
|
504 |
+
def build_async_requests(model:str) -> list[typing.Coroutine]:
|
505 |
+
|
506 |
+
"""
|
507 |
+
|
508 |
+
Builds the asynchronous requests.
|
509 |
+
|
510 |
+
Parameters:
|
511 |
+
model (string) : the model used to translate the text.
|
512 |
+
|
513 |
+
Returns:
|
514 |
+
async_requests (list - coroutine) : A list of coroutines that represent the asynchronous requests.
|
515 |
+
|
516 |
+
"""
|
517 |
+
|
518 |
+
async_requests = []
|
519 |
+
|
520 |
+
translation_batches = Kijiku.openai_translation_batches if Kijiku.LLM_TYPE == "openai" else Kijiku.gemini_translation_batches
|
521 |
+
|
522 |
+
for i in range(0, len(translation_batches), 2):
|
523 |
+
async_requests.append(Kijiku.handle_translation(model, i, len(translation_batches), translation_batches[i], translation_batches[i+1]))
|
524 |
+
|
525 |
+
return async_requests
|
526 |
+
|
527 |
+
##-------------------start-of-generate_text_to_translate_batches()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
528 |
+
|
529 |
+
@staticmethod
|
530 |
+
def generate_text_to_translate_batches(index:int) -> tuple[typing.List[str],int]:
|
531 |
+
|
532 |
+
"""
|
533 |
+
|
534 |
+
Generates prompts for the messages meant for the API.
|
535 |
+
|
536 |
+
Parameters:
|
537 |
+
index (int) : An int representing where we currently are in the text file.
|
538 |
+
|
539 |
+
Returns:
|
540 |
+
prompt (list - string) : A list of Japanese lines that will be assembled into messages.
|
541 |
+
index (int) : An updated int representing where we currently are in the text file.
|
542 |
+
|
543 |
+
"""
|
544 |
+
|
545 |
+
prompt = []
|
546 |
+
non_word_pattern = re.compile(r'^[\W_\s\n-]+$')
|
547 |
+
|
548 |
+
while(index < len(Kijiku.text_to_translate)):
|
549 |
+
|
550 |
+
sentence = Kijiku.text_to_translate[index]
|
551 |
+
stripped_sentence = sentence.strip()
|
552 |
+
lower_sentence = sentence.lower()
|
553 |
+
|
554 |
+
has_quotes = any(char in sentence for char in ["「", "」", "『", "』", "【", "】", "\"", "'"])
|
555 |
+
is_part_in_sentence = "part" in lower_sentence
|
556 |
+
|
557 |
+
if(len(prompt) < Kijiku.number_of_lines_per_batch):
|
558 |
+
|
559 |
+
if(any(char in sentence for char in ["▼", "△", "◇"])):
|
560 |
+
prompt.append(f'{sentence}\n')
|
561 |
+
Logger.log_action(f"Sentence : {sentence}, Sentence is a pov change... adding to prompt.")
|
562 |
+
|
563 |
+
elif(stripped_sentence == ''):
|
564 |
+
Logger.log_action(f"Sentence : {sentence} is empty... skipping.")
|
565 |
+
|
566 |
+
elif(is_part_in_sentence or all(char in ["1","2","3","4","5","6","7","8","9", " "] for char in sentence)):
|
567 |
+
prompt.append(f'{sentence}\n')
|
568 |
+
Logger.log_action(f"Sentence : {sentence}, Sentence is part marker... adding to prompt.")
|
569 |
+
|
570 |
+
elif(non_word_pattern.match(sentence) or KatakanaUtil.is_punctuation(stripped_sentence) and not has_quotes):
|
571 |
+
Logger.log_action(f"Sentence : {sentence}, Sentence is punctuation... skipping.")
|
572 |
+
|
573 |
+
else:
|
574 |
+
prompt.append(f'{sentence}\n')
|
575 |
+
Logger.log_action(f"Sentence : {sentence}, Sentence is a valid sentence... adding to prompt.")
|
576 |
+
|
577 |
+
else:
|
578 |
+
return prompt, index
|
579 |
+
|
580 |
+
index += 1
|
581 |
+
|
582 |
+
return prompt, index
|
583 |
+
|
584 |
+
##-------------------start-of-build_openai_translation_batches()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
585 |
+
|
586 |
+
@staticmethod
|
587 |
+
def build_openai_translation_batches() -> None:
|
588 |
+
|
589 |
+
"""
|
590 |
+
|
591 |
+
Builds translations batches dict for the OpenAI service.
|
592 |
+
|
593 |
+
"""
|
594 |
+
|
595 |
+
i = 0
|
596 |
+
|
597 |
+
while i < len(Kijiku.text_to_translate):
|
598 |
+
batch, i = Kijiku.generate_text_to_translate_batches(i)
|
599 |
+
|
600 |
+
batch = ''.join(batch)
|
601 |
+
|
602 |
+
## message mode one structures the first message as a system message and the second message as a model message
|
603 |
+
if(Kijiku.prompt_assembly_mode == 1):
|
604 |
+
system_msg = SystemTranslationMessage(content=str(OpenAIService.system_message))
|
605 |
+
|
606 |
+
## while message mode two structures the first message as a model message and the second message as a model message too, typically used for non-gpt-4 models if at all
|
607 |
+
else:
|
608 |
+
system_msg = ModelTranslationMessage(content=str(OpenAIService.system_message))
|
609 |
+
|
610 |
+
Kijiku.openai_translation_batches.append(system_msg)
|
611 |
+
|
612 |
+
model_msg = ModelTranslationMessage(content=batch)
|
613 |
+
|
614 |
+
Kijiku.openai_translation_batches.append(model_msg)
|
615 |
+
|
616 |
+
Logger.log_barrier()
|
617 |
+
Logger.log_action("Built Messages : ")
|
618 |
+
Logger.log_barrier()
|
619 |
+
|
620 |
+
i = 0
|
621 |
+
|
622 |
+
for message in Kijiku.openai_translation_batches:
|
623 |
+
|
624 |
+
i+=1
|
625 |
+
|
626 |
+
if(i % 2 == 0):
|
627 |
+
|
628 |
+
Logger.log_action(str(message))
|
629 |
+
|
630 |
+
else:
|
631 |
+
|
632 |
+
Logger.log_action(str(message))
|
633 |
+
Logger.log_barrier()
|
634 |
+
|
635 |
+
##-------------------start-of-build_gemini_translation_batches()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
636 |
+
|
637 |
+
@staticmethod
|
638 |
+
def build_gemini_translation_batches() -> None:
|
639 |
+
|
640 |
+
"""
|
641 |
+
|
642 |
+
Builds translations batches dict for the Gemini service.
|
643 |
+
|
644 |
+
"""
|
645 |
+
|
646 |
+
i = 0
|
647 |
+
|
648 |
+
while i < len(Kijiku.text_to_translate):
|
649 |
+
batch, i = Kijiku.generate_text_to_translate_batches(i)
|
650 |
+
|
651 |
+
batch = ''.join(batch)
|
652 |
+
|
653 |
+
## Gemini does not use system messages or model messages, and instead just takes a string input, so we just need to place the prompt before the text to be translated
|
654 |
+
Kijiku.gemini_translation_batches.append(GeminiService.prompt)
|
655 |
+
Kijiku.gemini_translation_batches.append(batch)
|
656 |
+
|
657 |
+
Logger.log_barrier()
|
658 |
+
Logger.log_action("Built Messages : ")
|
659 |
+
Logger.log_barrier()
|
660 |
+
|
661 |
+
i = 0
|
662 |
+
|
663 |
+
for message in Kijiku.gemini_translation_batches:
|
664 |
+
|
665 |
+
i+=1
|
666 |
+
|
667 |
+
if(i % 2 == 0):
|
668 |
+
|
669 |
+
Logger.log_action(str(message))
|
670 |
+
|
671 |
+
else:
|
672 |
+
|
673 |
+
Logger.log_action(str(message))
|
674 |
+
Logger.log_barrier()
|
675 |
+
|
676 |
+
##-------------------start-of-estimate_cost()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
677 |
+
|
678 |
+
@staticmethod
|
679 |
+
def estimate_cost(model:str, price_case:int | None = None) -> typing.Tuple[int, float, str]:
|
680 |
+
|
681 |
+
"""
|
682 |
+
|
683 |
+
Attempts to estimate cost.
|
684 |
+
|
685 |
+
Parameters:
|
686 |
+
model (string) : the model used to translate the text.
|
687 |
+
price_case (int) : the price case used to calculate the cost.
|
688 |
+
|
689 |
+
Returns:
|
690 |
+
num_tokens (int) : the number of tokens used.
|
691 |
+
min_cost (float) : the minimum cost of translation.
|
692 |
+
model (string) : the model used to translate the text.
|
693 |
+
|
694 |
+
"""
|
695 |
+
|
696 |
+
MODEL_COSTS = {
|
697 |
+
"gpt-3.5-turbo": {"price_case": 2, "input_cost": 0.0010, "output_cost": 0.0020},
|
698 |
+
"gpt-4": {"price_case": 4, "input_cost": 0.01, "output_cost": 0.03},
|
699 |
+
"gpt-4-turbo-preview": {"price_case": 4, "input_cost": 0.01, "output_cost": 0.03},
|
700 |
+
"gpt-3.5-turbo-0613": {"price_case": 1, "input_cost": 0.0015, "output_cost": 0.0020},
|
701 |
+
"gpt-3.5-turbo-0301": {"price_case": 1, "input_cost": 0.0015, "output_cost": 0.0020},
|
702 |
+
"gpt-3.5-turbo-1106": {"price_case": 2, "input_cost": 0.0010, "output_cost": 0.0020},
|
703 |
+
"gpt-3.5-turbo-0125": {"price_case": 7, "input_cost": 0.0005, "output_cost": 0.0015},
|
704 |
+
"gpt-3.5-turbo-16k-0613": {"price_case": 3, "input_cost": 0.0030, "output_cost": 0.0040},
|
705 |
+
"gpt-4-1106-preview": {"price_case": 4, "input_cost": 0.01, "output_cost": 0.03},
|
706 |
+
"gpt-4-0125-preview": {"price_case": 4, "input_cost": 0.01, "output_cost": 0.03},
|
707 |
+
"gpt-4-0314": {"price_case": 5, "input_cost": 0.03, "output_cost": 0.06},
|
708 |
+
"gpt-4-0613": {"price_case": 5, "input_cost": 0.03, "output_cost": 0.06},
|
709 |
+
"gpt-4-32k-0314": {"price_case": 6, "input_cost": 0.06, "output_cost": 0.012},
|
710 |
+
"gpt-4-32k-0613": {"price_case": 6, "input_cost": 0.06, "output_cost": 0.012},
|
711 |
+
"gemini-1.0-pro-001": {"price_case": 8, "input_cost": 0.0, "output_cost": 0.0},
|
712 |
+
"gemini-1.0-pro-vision-001": {"price_case": 8, "input_cost": 0.0, "output_cost": 0.0},
|
713 |
+
"gemini-1.0-pro": {"price_case": 8, "input_cost": 0.0, "output_cost": 0.0},
|
714 |
+
"gemini-1.0-pro-vision": {"price_case": 8, "input_cost": 0.0, "output_cost": 0.0},
|
715 |
+
"gemini-pro": {"price_case": 8, "input_cost": 0.0, "output_cost": 0.0},
|
716 |
+
"gemini-pro-vision": {"price_case": 8, "input_cost": 0.0, "output_cost": 0.0}
|
717 |
+
}
|
718 |
+
|
719 |
+
assert model in FileEnsurer.ALLOWED_OPENAI_MODELS or model in FileEnsurer.ALLOWED_GEMINI_MODELS, f"""Kudasai does not support : {model}"""
|
720 |
+
|
721 |
+
## default models are first, then the rest are sorted by price case
|
722 |
+
if(price_case is None):
|
723 |
+
|
724 |
+
if(model == "gpt-3.5-turbo"):
|
725 |
+
print("Warning: gpt-3.5-turbo may change over time. Returning num tokens assuming gpt-3.5-turbo-1106 as it is the most recent version of gpt-3.5-turbo.")
|
726 |
+
return Kijiku.estimate_cost("gpt-3.5-turbo-1106", price_case=2)
|
727 |
+
|
728 |
+
elif(model == "gpt-4"):
|
729 |
+
print("Warning: gpt-4 may change over time. Returning num tokens assuming gpt-4-1106-preview as it is the most recent version of gpt-4.")
|
730 |
+
return Kijiku.estimate_cost("gpt-4-1106-preview", price_case=4)
|
731 |
+
|
732 |
+
elif(model == "gpt-4-turbo-preview"):
|
733 |
+
print("Warning: gpt-4-turbo-preview may change over time. Returning num tokens assuming gpt-4-0125-preview as it is the most recent version of gpt-4-turbo-preview.")
|
734 |
+
return Kijiku.estimate_cost("gpt-4-0125-preview", price_case=4)
|
735 |
+
|
736 |
+
elif(model == "gpt-3.5-turbo-0613"):
|
737 |
+
print("Warning: gpt-3.5-turbo-0613 is considered depreciated by OpenAI as of November 6, 2023 and could be shutdown as early as June 13, 2024. Consider switching to gpt-3.5-turbo-1106.")
|
738 |
+
return Kijiku.estimate_cost(model, price_case=1)
|
739 |
+
|
740 |
+
elif(model == "gpt-3.5-turbo-0301"):
|
741 |
+
print("Warning: gpt-3.5-turbo-0301 is considered depreciated by OpenAI as of June 13, 2023 and could be shutdown as early as June 13, 2024. Consider switching to gpt-3.5-turbo-1106 unless you are specifically trying to break the filter.")
|
742 |
+
return Kijiku.estimate_cost(model, price_case=1)
|
743 |
+
|
744 |
+
elif(model == "gpt-3.5-turbo-1106"):
|
745 |
+
return Kijiku.estimate_cost(model, price_case=2)
|
746 |
+
|
747 |
+
elif(model == "gpt-3.5-turbo-0125"):
|
748 |
+
return Kijiku.estimate_cost(model, price_case=7)
|
749 |
+
|
750 |
+
elif(model == "gpt-3.5-turbo-16k-0613"):
|
751 |
+
print("Warning: gpt-3.5-turbo-16k-0613 is considered depreciated by OpenAI as of November 6, 2023 and could be shutdown as early as June 13, 2024. Consider switching to gpt-3.5-turbo-1106.")
|
752 |
+
return Kijiku.estimate_cost(model, price_case=3)
|
753 |
+
|
754 |
+
elif(model == "gpt-4-1106-preview"):
|
755 |
+
return Kijiku.estimate_cost(model, price_case=4)
|
756 |
+
|
757 |
+
elif(model == "gpt-4-0125-preview"):
|
758 |
+
return Kijiku.estimate_cost(model, price_case=4)
|
759 |
+
|
760 |
+
elif(model == "gpt-4-0314"):
|
761 |
+
print("Warning: gpt-4-0314 is considered depreciated by OpenAI as of June 13, 2023 and could be shutdown as early as June 13, 2024. Consider switching to gpt-4-0613.")
|
762 |
+
return Kijiku.estimate_cost(model, price_case=5)
|
763 |
+
|
764 |
+
elif(model == "gpt-4-0613"):
|
765 |
+
return Kijiku.estimate_cost(model, price_case=5)
|
766 |
+
|
767 |
+
elif(model == "gpt-4-32k-0314"):
|
768 |
+
print("Warning: gpt-4-32k-0314 is considered depreciated by OpenAI as of June 13, 2023 and could be shutdown as early as June 13, 2024. Consider switching to gpt-4-32k-0613.")
|
769 |
+
return Kijiku.estimate_cost(model, price_case=6)
|
770 |
+
|
771 |
+
elif(model == "gpt-4-32k-0613"):
|
772 |
+
return Kijiku.estimate_cost(model, price_case=6)
|
773 |
+
|
774 |
+
elif(model == "gemini-pro"):
|
775 |
+
print(f"Warning: gemini-pro may change over time. Returning num tokens assuming gemini-1.0-pro-001 as it is the most recent version of gemini-1.0-pro.")
|
776 |
+
return Kijiku.estimate_cost("gemini-1.0-pro-001", price_case=8)
|
777 |
+
|
778 |
+
elif(model == "gemini-pro-vision"):
|
779 |
+
print("Warning: gemini-pro-vision may change over time. Returning num tokens assuming gemini-1.0-pro-vision-001 as it is the most recent version of gemini-1.0-pro-vision.")
|
780 |
+
return Kijiku.estimate_cost("gemini-1.0-pro-vision-001", price_case=8)
|
781 |
+
|
782 |
+
elif(model == "gemini-1.0-pro"):
|
783 |
+
print(f"Warning: gemini-1.0-pro may change over time. Returning num tokens assuming gemini-1.0-pro-001 as it is the most recent version of gemini-1.0-pro.")
|
784 |
+
return Kijiku.estimate_cost(model, price_case=8)
|
785 |
+
|
786 |
+
elif(model == "gemini-1.0-pro-vision"):
|
787 |
+
print("Warning: gemini-1.0-pro-vision may change over time. Returning num tokens assuming gemini-1.0-pro-vision-001 as it is the most recent version of gemini-1.0-pro-vision.")
|
788 |
+
return Kijiku.estimate_cost(model, price_case=8)
|
789 |
+
|
790 |
+
elif(model == "gemini-1.0-pro-001"):
|
791 |
+
return Kijiku.estimate_cost(model, price_case=8)
|
792 |
+
|
793 |
+
elif(model == "gemini-1.0-pro-vision-001"):
|
794 |
+
return Kijiku.estimate_cost(model, price_case=8)
|
795 |
+
|
796 |
+
else:
|
797 |
+
|
798 |
+
cost_details = MODEL_COSTS.get(model)
|
799 |
+
|
800 |
+
if(not cost_details):
|
801 |
+
raise ValueError(f"Cost details not found for model: {model}.")
|
802 |
+
|
803 |
+
## break down the text into a string than into tokens
|
804 |
+
text = ''.join(Kijiku.text_to_translate)
|
805 |
+
|
806 |
+
if(Kijiku.LLM_TYPE == "openai"):
|
807 |
+
encoding = tiktoken.encoding_for_model(model)
|
808 |
+
num_tokens = len(encoding.encode(text))
|
809 |
+
|
810 |
+
else:
|
811 |
+
num_tokens = GeminiService.count_tokens(text)
|
812 |
+
|
813 |
+
input_cost = cost_details["input_cost"]
|
814 |
+
output_cost = cost_details["output_cost"]
|
815 |
+
|
816 |
+
min_cost_for_input = (num_tokens / 1000) * input_cost
|
817 |
+
min_cost_for_output = (num_tokens / 1000) * output_cost
|
818 |
+
min_cost = min_cost_for_input + min_cost_for_output
|
819 |
+
|
820 |
+
return num_tokens, min_cost, model
|
821 |
+
|
822 |
+
## type checker doesn't like the chance of None being returned, so we raise an exception here if it gets to this point
|
823 |
+
raise Exception("An unknown error occurred while calculating the minimum cost of translation.")
|
824 |
+
|
825 |
+
##-------------------start-of-handle_cost_estimate_prompt()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
826 |
+
|
827 |
+
@staticmethod
|
828 |
+
async def handle_cost_estimate_prompt(model:str, omit_prompt:bool=False) -> str:
|
829 |
+
|
830 |
+
"""
|
831 |
+
|
832 |
+
Handles the cost estimate prompt.
|
833 |
+
|
834 |
+
Parameters:
|
835 |
+
model (string) : the model used to translate the text.
|
836 |
+
omit_prompt (bool) : whether or not to omit the prompt.
|
837 |
+
|
838 |
+
Returns:
|
839 |
+
model (string) : the model used to translate the text.
|
840 |
+
|
841 |
+
"""
|
842 |
+
|
843 |
+
## get cost estimate and confirm
|
844 |
+
num_tokens, min_cost, model = Kijiku.estimate_cost(model)
|
845 |
+
|
846 |
+
print("\nNote that the cost estimate is not always accurate, and may be higher than the actual cost. However cost calculation now includes output tokens.\n")
|
847 |
+
|
848 |
+
Logger.log_barrier()
|
849 |
+
Logger.log_action("Calculating cost")
|
850 |
+
Logger.log_barrier()
|
851 |
+
|
852 |
+
if(Kijiku.LLM_TYPE == "gemini"):
|
853 |
+
print("As of Kudasai v3.4.0, Gemini Pro is Free to use")
|
854 |
+
|
855 |
+
Logger.log_action("Estimated number of tokens : " + str(num_tokens), output=True, omit_timestamp=True)
|
856 |
+
Logger.log_action("Estimated minimum cost : " + str(min_cost) + " USD", output=True, omit_timestamp=True)
|
857 |
+
Logger.log_barrier()
|
858 |
+
|
859 |
+
if(not omit_prompt):
|
860 |
+
if(input("\nContinue? (1 for yes or 2 for no) : ") == "1"):
|
861 |
+
Logger.log_action("User confirmed translation.")
|
862 |
+
|
863 |
+
else:
|
864 |
+
Logger.log_action("User cancelled translation.")
|
865 |
+
Logger.push_batch()
|
866 |
+
exit()
|
867 |
+
|
868 |
+
return model
|
869 |
+
|
870 |
+
##-------------------start-of-handle_translation()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
871 |
+
|
872 |
+
@staticmethod
|
873 |
+
async def handle_translation(model:str, index:int, length:int, translation_instructions:typing.Union[str, Message], translation_prompt:typing.Union[str, Message]) -> tuple[int, typing.Union[str, Message], str]:
|
874 |
+
|
875 |
+
"""
|
876 |
+
Handles the translation for a given system and user message.
|
877 |
+
|
878 |
+
Parameters:
|
879 |
+
model (string) : the model used to translate the text.
|
880 |
+
index (int) : the index of the message in the text file.
|
881 |
+
length (int) : the length of the text file.
|
882 |
+
translation_instructions (typing.Union[str, Message]) : the translation instructions.
|
883 |
+
translation_prompt (typing.Union[str, Message]) : the translation prompt.
|
884 |
+
|
885 |
+
Returns:
|
886 |
+
index (int) : the index of the message in the text file.
|
887 |
+
translation_prompt (typing.Union[str, Message]) : the translation prompt.
|
888 |
+
translated_message (str) : the translated message.
|
889 |
+
|
890 |
+
"""
|
891 |
+
|
892 |
+
## Basically limits the number of concurrent batches
|
893 |
+
async with Kijiku._semaphore:
|
894 |
+
num_tries = 0
|
895 |
+
|
896 |
+
while True:
|
897 |
+
|
898 |
+
## For the webgui
|
899 |
+
if(FileEnsurer.do_interrupt == True):
|
900 |
+
raise Exception("Interrupted by user.")
|
901 |
+
|
902 |
+
message_number = (index // 2) + 1
|
903 |
+
Logger.log_action(f"Trying translation for batch {message_number} of {length//2}...", output=True)
|
904 |
+
|
905 |
+
try:
|
906 |
+
|
907 |
+
if(Kijiku.LLM_TYPE == "openai"):
|
908 |
+
translated_message = await OpenAIService.translate_message(translation_instructions, translation_prompt) # type: ignore
|
909 |
+
|
910 |
+
else:
|
911 |
+
translated_message = await GeminiService.translate_message(translation_instructions, translation_prompt) # type: ignore
|
912 |
+
|
913 |
+
## will only occur if the max_batch_duration is exceeded, so we just return the untranslated text
|
914 |
+
except MaxBatchDurationExceededException:
|
915 |
+
translated_message = translation_prompt.content if isinstance(translation_prompt, Message) else translation_prompt
|
916 |
+
Logger.log_error(f"Batch {message_number} of {length//2} was not translated due to exceeding the max request duration, returning the untranslated text...", output=True)
|
917 |
+
break
|
918 |
+
|
919 |
+
## do not even bother if not a gpt 4 model, because gpt-3 seems unable to format properly
|
920 |
+
if("gpt-4" not in model):
|
921 |
+
break
|
922 |
+
|
923 |
+
if(await Kijiku.check_if_translation_is_good(translated_message, translation_prompt)):
|
924 |
+
Logger.log_action(f"Translation for batch {message_number} of {length//2} successful!", output=True)
|
925 |
+
break
|
926 |
+
|
927 |
+
if(num_tries >= Kijiku.num_of_malform_retries):
|
928 |
+
Logger.log_action(f"Batch {message_number} of {length//2} was malformed, but exceeded the maximum number of retries, Translation successful!", output=True)
|
929 |
+
break
|
930 |
+
|
931 |
+
else:
|
932 |
+
num_tries += 1
|
933 |
+
Logger.log_error(f"Batch {message_number} of {length//2} was malformed, retrying...", output=True)
|
934 |
+
Kijiku.num_occurred_malformed_batches += 1
|
935 |
+
|
936 |
+
return index, translation_prompt, translated_message
|
937 |
+
|
938 |
+
##-------------------start-of-check_if_translation_is_good()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
939 |
+
|
940 |
+
@staticmethod
|
941 |
+
async def check_if_translation_is_good(translated_message:str, translation_prompt:typing.Union[Message, str]) -> bool:
|
942 |
+
|
943 |
+
"""
|
944 |
+
|
945 |
+
Checks if the translation is good, i.e. the number of lines in the prompt and the number of lines in the translated message are the same.
|
946 |
+
|
947 |
+
Parameters:
|
948 |
+
translated_message (str) : the translated message.
|
949 |
+
translation_prompt (typing.Union[str, Message]) : the translation prompt.
|
950 |
+
|
951 |
+
Returns:
|
952 |
+
is_valid (bool) : whether or not the translation is valid.
|
953 |
+
|
954 |
+
"""
|
955 |
+
|
956 |
+
if(not isinstance(translation_prompt, str)):
|
957 |
+
prompt = translation_prompt.content
|
958 |
+
|
959 |
+
else:
|
960 |
+
prompt = translation_prompt
|
961 |
+
|
962 |
+
is_valid = False
|
963 |
+
|
964 |
+
jap = [line for line in prompt.split('\n') if line.strip()] ## Remove blank lines
|
965 |
+
eng = [line for line in translated_message.split('\n') if line.strip()] ## Remove blank lines
|
966 |
+
|
967 |
+
if(len(jap) == len(eng)):
|
968 |
+
is_valid = True
|
969 |
+
|
970 |
+
return is_valid
|
971 |
+
|
972 |
+
##-------------------start-of-redistribute()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
973 |
+
|
974 |
+
@staticmethod
|
975 |
+
def redistribute(translation_prompt:typing.Union[Message, str], translated_message:str) -> None:
|
976 |
+
|
977 |
+
"""
|
978 |
+
|
979 |
+
Puts translated text back into the text file.
|
980 |
+
|
981 |
+
Parameters:
|
982 |
+
translation_prompt (typing.Union[str, Message]) : the translation prompt.
|
983 |
+
translated_message (str) : the translated message.
|
984 |
+
|
985 |
+
"""
|
986 |
+
|
987 |
+
if(not isinstance(translation_prompt, str)):
|
988 |
+
prompt = translation_prompt.content
|
989 |
+
|
990 |
+
else:
|
991 |
+
prompt = translation_prompt
|
992 |
+
|
993 |
+
## Separates with hyphens if the mode is 1
|
994 |
+
if(Kijiku.je_check_mode == 1):
|
995 |
+
|
996 |
+
Kijiku.je_check_text.append("\n-------------------------\n"+ prompt + "\n\n")
|
997 |
+
Kijiku.je_check_text.append(translated_message + '\n')
|
998 |
+
|
999 |
+
## Mode two tries to pair the text for j-e checking, see fix_je() for more details
|
1000 |
+
elif(Kijiku.je_check_mode == 2):
|
1001 |
+
Kijiku.je_check_text.append(prompt)
|
1002 |
+
Kijiku.je_check_text.append(translated_message)
|
1003 |
+
|
1004 |
+
## mode 1 is the default mode, uses regex and other nonsense to split sentences
|
1005 |
+
if(Kijiku.sentence_fragmenter_mode == 1):
|
1006 |
+
|
1007 |
+
sentences = re.findall(r"(.*?(?:(?:\"|\'|-|~|!|\?|%|\(|\)|\.\.\.|\.|---|\[|\])))(?:\s|$)", translated_message)
|
1008 |
+
|
1009 |
+
patched_sentences = []
|
1010 |
+
build_string = None
|
1011 |
+
|
1012 |
+
for sentence in sentences:
|
1013 |
+
|
1014 |
+
sentence:str = sentence
|
1015 |
+
|
1016 |
+
if(sentence.startswith("\"") and not sentence.endswith("\"") and build_string is None):
|
1017 |
+
build_string = sentence
|
1018 |
+
continue
|
1019 |
+
elif(not sentence.startswith("\"") and sentence.endswith("\"") and build_string is not None):
|
1020 |
+
build_string += f" {sentence}"
|
1021 |
+
patched_sentences.append(build_string)
|
1022 |
+
build_string = None
|
1023 |
+
continue
|
1024 |
+
elif(build_string is not None):
|
1025 |
+
build_string += f" {sentence}"
|
1026 |
+
continue
|
1027 |
+
|
1028 |
+
Kijiku.translated_text.append(sentence + '\n')
|
1029 |
+
|
1030 |
+
for i in range(len(Kijiku.translated_text)):
|
1031 |
+
if Kijiku.translated_text[i] in patched_sentences:
|
1032 |
+
index = patched_sentences.index(Kijiku.translated_text[i])
|
1033 |
+
Kijiku.translated_text[i] = patched_sentences[index]
|
1034 |
+
|
1035 |
+
## mode 2 just assumes the LLM formatted it properly
|
1036 |
+
elif(Kijiku.sentence_fragmenter_mode == 2):
|
1037 |
+
|
1038 |
+
Kijiku.translated_text.append(translated_message + '\n\n')
|
1039 |
+
|
1040 |
+
##-------------------start-of-fix_je()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
1041 |
+
|
1042 |
+
@staticmethod
|
1043 |
+
def fix_je() -> typing.List[str]:
|
1044 |
+
|
1045 |
+
"""
|
1046 |
+
|
1047 |
+
Fixes the J->E text to be more j-e check friendly.
|
1048 |
+
|
1049 |
+
Note that fix_je() is not always accurate, and may use standard j-e formatting instead of the corrected formatting.
|
1050 |
+
|
1051 |
+
Returns:
|
1052 |
+
final_list (list - str) : the 'fixed' J->E text.
|
1053 |
+
|
1054 |
+
"""
|
1055 |
+
|
1056 |
+
i = 1
|
1057 |
+
final_list = []
|
1058 |
+
|
1059 |
+
while i < len(Kijiku.je_check_text):
|
1060 |
+
jap = Kijiku.je_check_text[i-1].split('\n')
|
1061 |
+
eng = Kijiku.je_check_text[i].split('\n')
|
1062 |
+
|
1063 |
+
jap = [line for line in jap if line.strip()] ## Remove blank lines
|
1064 |
+
eng = [line for line in eng if line.strip()] ## Remove blank lines
|
1065 |
+
|
1066 |
+
final_list.append("-------------------------\n")
|
1067 |
+
|
1068 |
+
if(len(jap) == len(eng)):
|
1069 |
+
|
1070 |
+
for jap_line,eng_line in zip(jap,eng):
|
1071 |
+
if(jap_line and eng_line): ## check if jap_line and eng_line aren't blank
|
1072 |
+
final_list.append(jap_line + '\n\n')
|
1073 |
+
final_list.append(eng_line + '\n\n')
|
1074 |
+
|
1075 |
+
final_list.append("--------------------------------------------------\n")
|
1076 |
+
|
1077 |
+
|
1078 |
+
else:
|
1079 |
+
|
1080 |
+
final_list.append(Kijiku.je_check_text[i-1] + '\n\n')
|
1081 |
+
final_list.append(Kijiku.je_check_text[i] + '\n\n')
|
1082 |
+
|
1083 |
+
final_list.append("--------------------------------------------------\n")
|
1084 |
+
|
1085 |
+
i+=2
|
1086 |
+
|
1087 |
+
return final_list
|
1088 |
+
|
1089 |
+
##-------------------start-of-assemble_results()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
1090 |
+
|
1091 |
+
@staticmethod
|
1092 |
+
def assemble_results(time_start:float, time_end:float) -> None:
|
1093 |
+
|
1094 |
+
"""
|
1095 |
+
|
1096 |
+
Generates the Kijiku translation print result, does not directly output/return, but rather sets Kijiku.translation_print_result to the output.
|
1097 |
+
|
1098 |
+
Parameters:
|
1099 |
+
time_start (float) : When the translation started.
|
1100 |
+
time_end (float) : When the translation finished.
|
1101 |
+
|
1102 |
+
"""
|
1103 |
+
|
1104 |
+
result = (
|
1105 |
+
f"Time Elapsed : {Toolkit.get_elapsed_time(time_start, time_end)}\n"
|
1106 |
+
f"Number of malformed batches : {Kijiku.num_occurred_malformed_batches}\n\n"
|
1107 |
+
f"Debug text have been written to : {FileEnsurer.debug_log_path}\n"
|
1108 |
+
f"J->E text have been written to : {FileEnsurer.je_check_path}\n"
|
1109 |
+
f"Translated text has been written to : {FileEnsurer.translated_text_path}\n"
|
1110 |
+
f"Errors have been written to : {FileEnsurer.error_log_path}\n"
|
1111 |
+
)
|
1112 |
+
|
1113 |
+
Kijiku.translation_print_result = result
|
1114 |
+
|
1115 |
+
##-------------------start-of-write_kijiku_results()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
1116 |
+
|
1117 |
+
@staticmethod
|
1118 |
+
@permission_error_decorator()
|
1119 |
+
def write_kijiku_results() -> None:
|
1120 |
+
|
1121 |
+
"""
|
1122 |
+
|
1123 |
+
This function is called to write the results of the Kijiku translation module to the output directory.
|
1124 |
+
|
1125 |
+
"""
|
1126 |
+
|
1127 |
+
## ensures the output directory exists, cause it could get moved or fucked with.
|
1128 |
+
FileEnsurer.standard_create_directory(FileEnsurer.output_dir)
|
1129 |
+
|
1130 |
+
with open(FileEnsurer.error_log_path, 'a+', encoding='utf-8') as file:
|
1131 |
+
file.writelines(Kijiku.error_text)
|
1132 |
+
|
1133 |
+
with open(FileEnsurer.je_check_path, 'w', encoding='utf-8') as file:
|
1134 |
+
file.writelines(Kijiku.je_check_text)
|
1135 |
+
|
1136 |
+
with open(FileEnsurer.translated_text_path, 'w', encoding='utf-8') as file:
|
1137 |
+
file.writelines(Kijiku.translated_text)
|
1138 |
+
|
1139 |
+
## Instructions to create a copy of the output for archival
|
1140 |
+
FileEnsurer.standard_create_directory(FileEnsurer.archive_dir)
|
1141 |
+
|
1142 |
+
timestamp = Toolkit.get_timestamp(is_archival=True)
|
1143 |
+
|
1144 |
+
## pushes the tl debug log to the file without clearing the file
|
1145 |
+
Logger.push_batch()
|
1146 |
+
Logger.clear_batch()
|
1147 |
+
|
1148 |
+
list_of_result_tuples = [('kijiku_translated_text', Kijiku.translated_text),
|
1149 |
+
('kijiku_je_check_text', Kijiku.je_check_text),
|
1150 |
+
('kijiku_error_log', Kijiku.error_text),
|
1151 |
+
('debug_log', FileEnsurer.standard_read_file(Logger.log_file_path))]
|
1152 |
+
|
1153 |
+
FileEnsurer.archive_results(list_of_result_tuples,
|
1154 |
+
module='kijiku', timestamp=timestamp)
|
modules/common/decorators.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## build-in libraries
|
2 |
+
import typing
|
3 |
+
import time
|
4 |
+
|
5 |
+
## custom modules
|
6 |
+
from modules.common.exceptions import TooManyFileAccessAttemptsException
|
7 |
+
|
8 |
+
##--------------------start-of-permission_error_decorator------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
9 |
+
|
10 |
+
def permission_error_decorator() -> typing.Callable:
|
11 |
+
|
12 |
+
"""
|
13 |
+
|
14 |
+
Returns a decorator that will catch a PermissionError and keep trying until the file is no longer in use.
|
15 |
+
Timeout is set to 100 retries or 20 seconds.
|
16 |
+
Mostly done because my computer has this weird issue, likely won't be noticed by anyone else.
|
17 |
+
|
18 |
+
"""
|
19 |
+
|
20 |
+
def decorator(func):
|
21 |
+
|
22 |
+
max_retries = 100
|
23 |
+
|
24 |
+
def wrapper(*args, **kwargs):
|
25 |
+
retries = 0
|
26 |
+
while(retries < max_retries):
|
27 |
+
try:
|
28 |
+
return func(*args, **kwargs)
|
29 |
+
except PermissionError:
|
30 |
+
retries += 1
|
31 |
+
time.sleep(0.2)
|
32 |
+
|
33 |
+
raise TooManyFileAccessAttemptsException(f"Failed to execute {func.__name__} after {max_retries} retries.")
|
34 |
+
|
35 |
+
return wrapper
|
36 |
+
return decorator
|
modules/common/exceptions.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## third-party libraries
|
2 |
+
|
3 |
+
## for importing, other scripts will use from common.exceptions instead of from the third-party libraries themselves
|
4 |
+
from openai import AuthenticationError, InternalServerError, RateLimitError, APITimeoutError
|
5 |
+
from deepl.exceptions import AuthorizationException, QuotaExceededException
|
6 |
+
|
7 |
+
##-------------------start-of-MaxBatchDurationExceededException--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
8 |
+
|
9 |
+
class MaxBatchDurationExceededException(Exception):
|
10 |
+
|
11 |
+
"""
|
12 |
+
|
13 |
+
MaxBatchDurationExceededException is an exception that is raised when the max batch duration is exceeded.
|
14 |
+
|
15 |
+
"""
|
16 |
+
|
17 |
+
pass
|
18 |
+
|
19 |
+
##-------------------start-of-InvalidAPIKeyException--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
20 |
+
|
21 |
+
class InvalidAPIKeyException(Exception):
|
22 |
+
|
23 |
+
"""
|
24 |
+
|
25 |
+
InvalidAPIKeyException is an exception that is raised when the API key is invalid.
|
26 |
+
|
27 |
+
"""
|
28 |
+
|
29 |
+
def __init__(self, model_name:str) -> None:
|
30 |
+
|
31 |
+
"""
|
32 |
+
|
33 |
+
Parameters:
|
34 |
+
model_name (string) : The name of the model that the API key is invalid for.
|
35 |
+
|
36 |
+
"""
|
37 |
+
|
38 |
+
self.message = f"The API key is invalid for the model {model_name}."
|
39 |
+
|
40 |
+
##-------------------start-of-TooManyFileAccessAttemptsException--------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
41 |
+
|
42 |
+
class TooManyFileAccessAttemptsException(Exception):
|
43 |
+
|
44 |
+
"""
|
45 |
+
|
46 |
+
TooManyFileAccessAttemptsException is an exception that is raised when too many attempts are made to access a file.
|
47 |
+
|
48 |
+
"""
|
49 |
+
|
50 |
+
def __init__(self, message:str) -> None:
|
51 |
+
|
52 |
+
"""
|
53 |
+
|
54 |
+
Parameters:
|
55 |
+
message (string) : The message to display.
|
56 |
+
|
57 |
+
"""
|
58 |
+
|
59 |
+
self.message = message
|
modules/common/file_ensurer.py
ADDED
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libaries
|
2 |
+
import os
|
3 |
+
import traceback
|
4 |
+
import json
|
5 |
+
import typing
|
6 |
+
|
7 |
+
## custom modules
|
8 |
+
from modules.common.decorators import permission_error_decorator
|
9 |
+
from modules.common.logger import Logger
|
10 |
+
from modules.common.toolkit import Toolkit
|
11 |
+
|
12 |
+
class FileEnsurer():
|
13 |
+
|
14 |
+
"""
|
15 |
+
|
16 |
+
FileEnsurer is a class that is used to ensure that the required files and directories exist.
|
17 |
+
Also serves as a place to store the paths to the files and directories. Some file related functions are also stored here.
|
18 |
+
As well as some variables that are used to store the default kijiku rules and the allowed models across Kudasai.
|
19 |
+
|
20 |
+
"""
|
21 |
+
|
22 |
+
## main dirs
|
23 |
+
script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
24 |
+
output_dir = os.path.join(script_dir, "output")
|
25 |
+
archive_dir = os.path.join(output_dir, "archive")
|
26 |
+
|
27 |
+
## main dirs (config is just under userprofile on windows, and under home on linux); secrets are under appdata on windows, and under .config on linux
|
28 |
+
if(os.name == 'nt'): ## Windows
|
29 |
+
config_dir = os.path.join(os.environ['USERPROFILE'],"KudasaiConfig")
|
30 |
+
secrets_dir = os.path.join(os.environ['APPDATA'],"KudasaiSecrets")
|
31 |
+
else: ## Linux
|
32 |
+
config_dir = os.path.join(os.path.expanduser("~"), "KudasaiConfig")
|
33 |
+
secrets_dir = os.path.join(os.path.expanduser("~"), ".config", "KudasaiSecrets")
|
34 |
+
|
35 |
+
Logger.log_file_path = os.path.join(output_dir, "debug_log.txt")
|
36 |
+
|
37 |
+
##----------------------------------/
|
38 |
+
|
39 |
+
## sub dirs
|
40 |
+
lib_dir = os.path.join(script_dir, "lib")
|
41 |
+
gui_lib = os.path.join(lib_dir, "gui")
|
42 |
+
jsons_dir = os.path.join(script_dir, "jsons")
|
43 |
+
|
44 |
+
##----------------------------------/
|
45 |
+
|
46 |
+
## output files
|
47 |
+
preprocessed_text_path = os.path.join(output_dir, "preprocessed_text.txt") ## path for the preprocessed text
|
48 |
+
translated_text_path = os.path.join(output_dir, "translated_text.txt") ## path for translated text
|
49 |
+
|
50 |
+
je_check_path = os.path.join(output_dir, "je_check_text.txt") ## path for je check text (text generated by the translation modules to compare against the translated text)
|
51 |
+
|
52 |
+
kairyou_log_path = os.path.join(output_dir, "preprocessing_results.txt") ## path for kairyou log (the results of preprocessing)
|
53 |
+
error_log_path = os.path.join(output_dir, "error_log.txt") ## path for the error log (errors generated by the preprocessing and translation modules)
|
54 |
+
debug_log_path = Logger.log_file_path ## path for the debug log (debug info generated by the preprocessing and translation modules)
|
55 |
+
|
56 |
+
## kijiku rules
|
57 |
+
external_kijiku_rules_path = os.path.join(script_dir,'kijiku_rules.json')
|
58 |
+
config_kijiku_rules_path = os.path.join(config_dir,'kijiku_rules.json')
|
59 |
+
|
60 |
+
## api keys
|
61 |
+
deepl_api_key_path = os.path.join(secrets_dir, "deepl_api_key.txt")
|
62 |
+
openai_api_key_path = os.path.join(secrets_dir,'openai_api_key.txt')
|
63 |
+
gemini_api_key_path = os.path.join(secrets_dir,'gemini_api_key.txt')
|
64 |
+
|
65 |
+
## favicon
|
66 |
+
favicon_path = os.path.join(gui_lib, "Kudasai_Logo.png")
|
67 |
+
|
68 |
+
DEFAULT_KIJIKU_RULES = {
|
69 |
+
"base kijiku settings": {
|
70 |
+
"prompt_assembly_mode": 1,
|
71 |
+
"number_of_lines_per_batch": 36,
|
72 |
+
"sentence_fragmenter_mode": 2,
|
73 |
+
"je_check_mode": 2,
|
74 |
+
"number_of_malformed_batch_retries": 1,
|
75 |
+
"batch_retry_timeout": 300,
|
76 |
+
"number_of_concurrent_batches": 5
|
77 |
+
},
|
78 |
+
|
79 |
+
"openai settings": {
|
80 |
+
"openai_model": "gpt-4",
|
81 |
+
"openai_system_message": "As a Japanese to English translator, translate narration into English simple past, everything else should remain in its original tense. Maintain original formatting, punctuation, and paragraph structure. Keep pre-translated terms and anticipate names not replaced. Preserve terms and markers marked with >>><<< and match the output's line count to the input's. Note: 〇 indicates chapter changes.",
|
82 |
+
"openai_temperature": 0.3,
|
83 |
+
"openai_top_p": 1,
|
84 |
+
"openai_n": 1,
|
85 |
+
"openai_stream": False,
|
86 |
+
"openai_stop": None,
|
87 |
+
"openai_logit_bias": None,
|
88 |
+
"openai_max_tokens": None,
|
89 |
+
"openai_presence_penalty": 0,
|
90 |
+
"openai_frequency_penalty": 0
|
91 |
+
},
|
92 |
+
|
93 |
+
"gemini settings": {
|
94 |
+
"gemini_model": "gemini-pro",
|
95 |
+
"gemini_prompt": "As a Japanese to English translator, translate narration into English simple past, everything else should remain in its original tense. Maintain original formatting, punctuation, and paragraph structure. Keep pre-translated terms and anticipate names not replaced. Preserve terms and markers marked with >>><<< and match the output's line count to the input's. Note: 〇 indicates chapter changes.",
|
96 |
+
"gemini_temperature": 0.3,
|
97 |
+
"gemini_top_p": None,
|
98 |
+
"gemini_top_k": None,
|
99 |
+
"gemini_candidate_count": 1,
|
100 |
+
"gemini_stream": False,
|
101 |
+
"gemini_stop_sequences": None,
|
102 |
+
"gemini_max_output_tokens": None
|
103 |
+
}
|
104 |
+
}
|
105 |
+
|
106 |
+
|
107 |
+
ALLOWED_OPENAI_MODELS = [
|
108 |
+
"gpt-3.5-turbo",
|
109 |
+
"gpt-4",
|
110 |
+
"gpt-4-turbo-preview",
|
111 |
+
"gpt-3.5-turbo-0301",
|
112 |
+
"gpt-4-0314",
|
113 |
+
"gpt-4-32k-0314",
|
114 |
+
"gpt-3.5-turbo-0613",
|
115 |
+
"gpt-3.5-turbo-0125",
|
116 |
+
"gpt-3.5-turbo-16k-0613",
|
117 |
+
"gpt-3.5-turbo-1106",
|
118 |
+
"gpt-4-0613",
|
119 |
+
"gpt-4-32k-0613",
|
120 |
+
"gpt-4-1106-preview",
|
121 |
+
"gpt-4-0125-preview"
|
122 |
+
]
|
123 |
+
|
124 |
+
ALLOWED_GEMINI_MODELS = [
|
125 |
+
"gemini-1.0-pro-001",
|
126 |
+
"gemini-1.0-pro-vision-001",
|
127 |
+
"gemini-1.0-pro",
|
128 |
+
"gemini-1.0-pro-vision",
|
129 |
+
"gemini-pro",
|
130 |
+
"gemini-pro-vision"
|
131 |
+
]
|
132 |
+
|
133 |
+
INVALID_KIJIKU_RULES_PLACEHOLDER = {
|
134 |
+
"INVALID JSON":
|
135 |
+
{
|
136 |
+
"INVALID JSON":"INVALID JSON"
|
137 |
+
}
|
138 |
+
}
|
139 |
+
|
140 |
+
## rules
|
141 |
+
blank_rules_path = os.path.join(jsons_dir, "blank_replacements.json")
|
142 |
+
|
143 |
+
do_interrupt = False
|
144 |
+
need_to_run_kairyou = True
|
145 |
+
|
146 |
+
##--------------------start-of-exit_kudasai()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
147 |
+
|
148 |
+
@staticmethod
|
149 |
+
def exit_kudasai():
|
150 |
+
|
151 |
+
"""
|
152 |
+
|
153 |
+
Pushes the log batch to the log and exits.
|
154 |
+
|
155 |
+
"""
|
156 |
+
|
157 |
+
print("Cleaning up and exiting...")
|
158 |
+
|
159 |
+
Logger.push_batch()
|
160 |
+
|
161 |
+
exit()
|
162 |
+
|
163 |
+
##-------------------start-of-setup_needed_files()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
164 |
+
|
165 |
+
@staticmethod
|
166 |
+
@permission_error_decorator()
|
167 |
+
def setup_needed_files() -> None:
|
168 |
+
|
169 |
+
"""
|
170 |
+
|
171 |
+
Ensures that the required files and directories exist.
|
172 |
+
|
173 |
+
"""
|
174 |
+
|
175 |
+
## creates the output directory and config directory if they don't exist
|
176 |
+
FileEnsurer.standard_create_directory(FileEnsurer.config_dir)
|
177 |
+
FileEnsurer.standard_create_directory(FileEnsurer.output_dir)
|
178 |
+
FileEnsurer.standard_create_directory(FileEnsurer.secrets_dir)
|
179 |
+
|
180 |
+
## creates and clears the log file
|
181 |
+
Logger.clear_log_file()
|
182 |
+
|
183 |
+
## creates the 5 output files
|
184 |
+
FileEnsurer.standard_create_file(FileEnsurer.preprocessed_text_path)
|
185 |
+
FileEnsurer.standard_create_file(FileEnsurer.translated_text_path)
|
186 |
+
FileEnsurer.standard_create_file(FileEnsurer.je_check_path)
|
187 |
+
FileEnsurer.standard_create_file(FileEnsurer.kairyou_log_path)
|
188 |
+
FileEnsurer.standard_create_file(FileEnsurer.error_log_path)
|
189 |
+
|
190 |
+
## creates the kijiku rules file if it doesn't exist
|
191 |
+
if(os.path.exists(FileEnsurer.config_kijiku_rules_path) == False):
|
192 |
+
with open(FileEnsurer.config_kijiku_rules_path, 'w+', encoding='utf-8') as file:
|
193 |
+
json.dump(FileEnsurer.DEFAULT_KIJIKU_RULES, file)
|
194 |
+
|
195 |
+
##--------------------start-of-standard_create_directory()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
196 |
+
|
197 |
+
@staticmethod
|
198 |
+
@permission_error_decorator()
|
199 |
+
def standard_create_directory(directory_path:str) -> None:
|
200 |
+
|
201 |
+
"""
|
202 |
+
|
203 |
+
Creates a directory if it doesn't exist, as well as logs what was created.
|
204 |
+
|
205 |
+
Parameters:
|
206 |
+
directory_path (str) : path to the directory to be created.
|
207 |
+
|
208 |
+
"""
|
209 |
+
|
210 |
+
if(os.path.isdir(directory_path) == False):
|
211 |
+
os.mkdir(directory_path)
|
212 |
+
Logger.log_action(directory_path + " created due to lack of the folder")
|
213 |
+
|
214 |
+
##--------------------start-of-standard_create_file()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
215 |
+
|
216 |
+
@staticmethod
|
217 |
+
@permission_error_decorator()
|
218 |
+
def standard_create_file(file_path:str) -> None:
|
219 |
+
|
220 |
+
"""
|
221 |
+
|
222 |
+
Creates a file if it doesn't exist, truncates it, as well as logs what was created.
|
223 |
+
|
224 |
+
Parameters:
|
225 |
+
file_path (str) : path to the file to be created.
|
226 |
+
|
227 |
+
"""
|
228 |
+
|
229 |
+
if(os.path.exists(file_path) == False):
|
230 |
+
Logger.log_action(file_path + " was created due to lack of the file")
|
231 |
+
with open(file_path, "w+", encoding="utf-8") as file:
|
232 |
+
file.truncate()
|
233 |
+
|
234 |
+
##--------------------start-of-modified_create_file()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
235 |
+
|
236 |
+
@staticmethod
|
237 |
+
@permission_error_decorator()
|
238 |
+
def modified_create_file(file_path:str, content_to_write:str) -> bool:
|
239 |
+
|
240 |
+
"""
|
241 |
+
|
242 |
+
Creates a path if it doesn't exist or if it is blank or empty, writes to it, as well as logs what was created.
|
243 |
+
|
244 |
+
Parameters:
|
245 |
+
file_path (str) : path to the file to be created.
|
246 |
+
content to write (str) : content to be written to the file.
|
247 |
+
|
248 |
+
Returns:
|
249 |
+
bool : whether or not the file was overwritten.
|
250 |
+
|
251 |
+
"""
|
252 |
+
|
253 |
+
did_overwrite = False
|
254 |
+
|
255 |
+
if(os.path.exists(file_path) == False or os.path.getsize(file_path) == 0):
|
256 |
+
Logger.log_action(file_path + " was created due to lack of the file or because it is blank")
|
257 |
+
with open(file_path, "w+", encoding="utf-8") as file:
|
258 |
+
file.write(content_to_write)
|
259 |
+
|
260 |
+
did_overwrite = True
|
261 |
+
|
262 |
+
return did_overwrite
|
263 |
+
|
264 |
+
##--------------------start-of-standard_overwrite_file()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
265 |
+
|
266 |
+
@staticmethod
|
267 |
+
@permission_error_decorator()
|
268 |
+
def standard_overwrite_file(file_path:str, content_to_write:str, omit:bool = True) -> None:
|
269 |
+
|
270 |
+
"""
|
271 |
+
|
272 |
+
Writes to a file, creates it if it doesn't exist, overwrites it if it does, as well as logs what occurred.
|
273 |
+
|
274 |
+
Parameters:
|
275 |
+
file_path (str) : path to the file to be overwritten.
|
276 |
+
content to write (str) : content to be written to the file.
|
277 |
+
omit (bool | optional) : whether or not to omit the content from the log.
|
278 |
+
|
279 |
+
"""
|
280 |
+
|
281 |
+
with open(file_path, "w+", encoding="utf-8") as file:
|
282 |
+
file.write(content_to_write)
|
283 |
+
|
284 |
+
if(omit):
|
285 |
+
content_to_write = "(Content was omitted)"
|
286 |
+
|
287 |
+
Logger.log_action(file_path + " was overwritten with the following content: " + content_to_write)
|
288 |
+
|
289 |
+
##--------------------start-of-clear_file()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
290 |
+
|
291 |
+
@staticmethod
|
292 |
+
@permission_error_decorator()
|
293 |
+
def clear_file(file_path:str) -> None:
|
294 |
+
|
295 |
+
"""
|
296 |
+
|
297 |
+
Clears a file, as well as logs what occurred.
|
298 |
+
|
299 |
+
Parameters:
|
300 |
+
file_path (str) : path to the file to be cleared.
|
301 |
+
|
302 |
+
"""
|
303 |
+
|
304 |
+
with open(file_path, "w+", encoding="utf-8") as file:
|
305 |
+
file.truncate()
|
306 |
+
|
307 |
+
Logger.log_action(file_path + " was cleared")
|
308 |
+
|
309 |
+
##--------------------start-of-standard_read_file()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
310 |
+
|
311 |
+
@staticmethod
|
312 |
+
@permission_error_decorator()
|
313 |
+
def standard_read_file(file_path:str) -> str:
|
314 |
+
|
315 |
+
"""
|
316 |
+
|
317 |
+
Reads a file.
|
318 |
+
|
319 |
+
Parameters:
|
320 |
+
file_path (str) : path to the file to be read.
|
321 |
+
|
322 |
+
Returns:
|
323 |
+
content (str) : the content of the file.
|
324 |
+
|
325 |
+
"""
|
326 |
+
|
327 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
328 |
+
content = file.read()
|
329 |
+
|
330 |
+
return content
|
331 |
+
|
332 |
+
##-------------------start-of-handle_critical_exception()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
333 |
+
|
334 |
+
@staticmethod
|
335 |
+
def handle_critical_exception(critical_exception:Exception) -> None:
|
336 |
+
|
337 |
+
"""
|
338 |
+
|
339 |
+
Handles a critical exception by logging it, pausing the console so the user can see the error, and then re-raising it.
|
340 |
+
|
341 |
+
Parameters:
|
342 |
+
critical_exception (object - Exception) : the exception to be handled.
|
343 |
+
|
344 |
+
"""
|
345 |
+
|
346 |
+
Logger.log_barrier()
|
347 |
+
Logger.log_action("Kudasai has crashed", output=True)
|
348 |
+
Logger.log_action("Please send the following to the developer on github at https://github.com/Bikatr7/Kudasai/issues :", output=True, omit_timestamp=True)
|
349 |
+
|
350 |
+
traceback_msg = traceback.format_exc()
|
351 |
+
|
352 |
+
Logger.log_action(traceback_msg ,output=True, omit_timestamp=True)
|
353 |
+
|
354 |
+
Logger.push_batch()
|
355 |
+
|
356 |
+
Toolkit.pause_console()
|
357 |
+
|
358 |
+
raise critical_exception
|
359 |
+
|
360 |
+
##-------------------start-of-archive_results()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
361 |
+
|
362 |
+
|
363 |
+
@staticmethod
|
364 |
+
@permission_error_decorator()
|
365 |
+
def archive_results(list_of_result_tuples:typing.List[typing.Tuple[str,str]], module:str, timestamp:str) -> None:
|
366 |
+
|
367 |
+
"""
|
368 |
+
|
369 |
+
Creates a directory in the archive folder and writes the results to files in that directory.
|
370 |
+
|
371 |
+
Parameters:
|
372 |
+
list_of_result_tuples (list - tuple - str, str) : list of tuples containing the filename and content of the results to be archived.
|
373 |
+
module (str) : name of the module that generated the results.
|
374 |
+
timestamp (str) : timestamp of when the results were generated.
|
375 |
+
|
376 |
+
"""
|
377 |
+
|
378 |
+
archival_path = os.path.join(FileEnsurer.archive_dir, f'{module}_run_{timestamp}')
|
379 |
+
FileEnsurer.standard_create_directory(archival_path)
|
380 |
+
|
381 |
+
for result in list_of_result_tuples:
|
382 |
+
(filename, content) = result
|
383 |
+
result_file_path = os.path.join(archival_path, f'{filename}_{timestamp}.txt')
|
384 |
+
|
385 |
+
with open(result_file_path, "w", encoding="utf-8") as file:
|
386 |
+
file.writelines(content)
|
387 |
+
|
388 |
+
##-------------------start-of-standard_read_json()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
389 |
+
|
390 |
+
@staticmethod
|
391 |
+
@permission_error_decorator()
|
392 |
+
def standard_read_json(file_path:str) -> dict:
|
393 |
+
|
394 |
+
"""
|
395 |
+
|
396 |
+
Reads a json file and returns the json object.
|
397 |
+
|
398 |
+
Parameters:
|
399 |
+
file_path (str) : path to the json file to be read.
|
400 |
+
|
401 |
+
Returns:
|
402 |
+
json_object (dict) : the json object.
|
403 |
+
|
404 |
+
"""
|
405 |
+
|
406 |
+
with open(file_path, "r", encoding="utf-8") as file:
|
407 |
+
json_object = json.load(file)
|
408 |
+
|
409 |
+
return json_object
|
410 |
+
|
411 |
+
##-------------------start-of-write_kairyou_results()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
412 |
+
|
413 |
+
@staticmethod
|
414 |
+
@permission_error_decorator()
|
415 |
+
def write_kairyou_results(text_to_preprocess:str, preprocessing_log:str, error_log:str, timestamp:str) -> None:
|
416 |
+
|
417 |
+
"""
|
418 |
+
|
419 |
+
This function is called to write the results to the output directory.
|
420 |
+
|
421 |
+
Parameters:
|
422 |
+
text_to_preprocess (str) : the text that was preprocessed.
|
423 |
+
preprocessing_log (str) : the log of the preprocessing results.
|
424 |
+
error_log (str) : the log of any errors that occurred during preprocessing.
|
425 |
+
timestamp (str) : the timestamp of when the results were generated (Can be obtained from Toolkit.get_timestamp(is_archival=True))
|
426 |
+
|
427 |
+
"""
|
428 |
+
|
429 |
+
## ensures the output directory exists, cause it could get moved or fucked with.
|
430 |
+
FileEnsurer.standard_create_directory(FileEnsurer.output_dir)
|
431 |
+
|
432 |
+
with(open(FileEnsurer.preprocessed_text_path, 'w', encoding='utf-8')) as file:
|
433 |
+
file.write(text_to_preprocess)
|
434 |
+
|
435 |
+
with open(FileEnsurer.kairyou_log_path, 'w', encoding='utf-8') as file:
|
436 |
+
file.write(preprocessing_log)
|
437 |
+
|
438 |
+
with open(FileEnsurer.error_log_path, 'w', encoding='utf-8') as file:
|
439 |
+
file.write(error_log)
|
440 |
+
|
441 |
+
with open(FileEnsurer.je_check_path, 'w', encoding='utf-8') as file:
|
442 |
+
file.truncate()
|
443 |
+
|
444 |
+
with open(FileEnsurer.translated_text_path, 'w', encoding='utf-8') as file:
|
445 |
+
file.truncate()
|
446 |
+
|
447 |
+
## Instructions to create a copy of the output for archival
|
448 |
+
FileEnsurer.standard_create_directory(FileEnsurer.archive_dir)
|
449 |
+
|
450 |
+
Logger.push_batch()
|
451 |
+
Logger.clear_batch()
|
452 |
+
|
453 |
+
list_of_result_tuples = [('kairyou_preprocessed_text', text_to_preprocess),
|
454 |
+
('kairyou_preprocessing_log', preprocessing_log),
|
455 |
+
('kairyou_error_log', error_log),
|
456 |
+
('debug_log', FileEnsurer.standard_read_file(Logger.log_file_path))]
|
457 |
+
|
458 |
+
FileEnsurer.archive_results(list_of_result_tuples,
|
459 |
+
module='kairyou', timestamp=timestamp)
|
460 |
+
|
modules/common/logger.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## custom modules
|
2 |
+
from modules.common.toolkit import Toolkit
|
3 |
+
from modules.common.decorators import permission_error_decorator
|
4 |
+
|
5 |
+
class Logger:
|
6 |
+
|
7 |
+
"""
|
8 |
+
|
9 |
+
The logger class is used to log actions taken by Kudasai.
|
10 |
+
|
11 |
+
"""
|
12 |
+
|
13 |
+
log_file_path = ""
|
14 |
+
|
15 |
+
current_batch = ""
|
16 |
+
|
17 |
+
errors = []
|
18 |
+
|
19 |
+
##--------------------start-of-log_action()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
20 |
+
|
21 |
+
@staticmethod
|
22 |
+
def log_action(action:str, output:bool=False, omit_timestamp:bool=False) -> None:
|
23 |
+
|
24 |
+
"""
|
25 |
+
|
26 |
+
Logs an action.
|
27 |
+
|
28 |
+
Parameters:
|
29 |
+
action (str) : the action being logged.
|
30 |
+
output (bool | optional | defaults to false) : whether or not to output the action to the console.
|
31 |
+
omit_timestamp (bool | optional | defaults to false) : whether or not to omit the timestamp from the action.
|
32 |
+
|
33 |
+
"""
|
34 |
+
|
35 |
+
timestamp = Toolkit.get_timestamp()
|
36 |
+
|
37 |
+
log_line = timestamp + action + "\n"
|
38 |
+
|
39 |
+
Logger.current_batch += log_line
|
40 |
+
|
41 |
+
if(omit_timestamp):
|
42 |
+
log_line = action
|
43 |
+
|
44 |
+
if(output):
|
45 |
+
print(log_line)
|
46 |
+
|
47 |
+
##--------------------start-of-log_error()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
48 |
+
|
49 |
+
@staticmethod
|
50 |
+
def log_error(action:str, output:bool=False, omit_timestamp:bool=False) -> None:
|
51 |
+
|
52 |
+
"""
|
53 |
+
|
54 |
+
Logs an error.
|
55 |
+
|
56 |
+
Parameters:
|
57 |
+
action (str) : the action being logged.
|
58 |
+
output (bool | optional | defaults to false) : whether or not to output the action to the console.
|
59 |
+
omit_timestamp (bool | optional | defaults to false) : whether or not to omit the timestamp from the action.
|
60 |
+
|
61 |
+
"""
|
62 |
+
|
63 |
+
timestamp = Toolkit.get_timestamp()
|
64 |
+
|
65 |
+
log_line = timestamp + action + "\n"
|
66 |
+
|
67 |
+
Logger.current_batch += log_line
|
68 |
+
|
69 |
+
if(omit_timestamp):
|
70 |
+
log_line = action
|
71 |
+
|
72 |
+
if(output):
|
73 |
+
print(log_line)
|
74 |
+
|
75 |
+
Logger.errors.append(log_line)
|
76 |
+
|
77 |
+
##--------------------start-of-log_barrier()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
78 |
+
|
79 |
+
@staticmethod
|
80 |
+
def log_barrier() -> None:
|
81 |
+
|
82 |
+
"""
|
83 |
+
|
84 |
+
Logs a barrier.
|
85 |
+
|
86 |
+
"""
|
87 |
+
|
88 |
+
Logger.log_action("-------------------------")
|
89 |
+
|
90 |
+
##--------------------start-of-clear_batch()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
91 |
+
|
92 |
+
@staticmethod
|
93 |
+
def clear_batch() -> None:
|
94 |
+
|
95 |
+
"""
|
96 |
+
|
97 |
+
Clears the current batch.
|
98 |
+
|
99 |
+
"""
|
100 |
+
|
101 |
+
Logger.current_batch = ""
|
102 |
+
Logger.errors = []
|
103 |
+
|
104 |
+
##--------------------start-of-push_batch()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
105 |
+
|
106 |
+
@staticmethod
|
107 |
+
@permission_error_decorator()
|
108 |
+
def push_batch() -> None:
|
109 |
+
|
110 |
+
"""
|
111 |
+
|
112 |
+
Pushes all stored actions to the log file.
|
113 |
+
|
114 |
+
"""
|
115 |
+
|
116 |
+
with open(Logger.log_file_path, 'a+', encoding="utf-8") as file:
|
117 |
+
file.write(Logger.current_batch)
|
118 |
+
|
119 |
+
##--------------------start-of-clear_log_file()------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
120 |
+
|
121 |
+
@staticmethod
|
122 |
+
@permission_error_decorator()
|
123 |
+
def clear_log_file() -> None:
|
124 |
+
|
125 |
+
"""
|
126 |
+
|
127 |
+
Clears the log file.
|
128 |
+
|
129 |
+
"""
|
130 |
+
|
131 |
+
with open(Logger.log_file_path, 'w+', encoding="utf-8") as file:
|
132 |
+
file.truncate(0)
|
modules/common/toolkit.py
ADDED
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
from datetime import datetime
|
3 |
+
|
4 |
+
import os
|
5 |
+
import typing
|
6 |
+
import platform
|
7 |
+
import subprocess
|
8 |
+
|
9 |
+
class Toolkit():
|
10 |
+
"""
|
11 |
+
|
12 |
+
A class containing various functions that are used throughout Kudasai.
|
13 |
+
|
14 |
+
"""
|
15 |
+
|
16 |
+
CURRENT_VERSION = "v3.4.0-alpha"
|
17 |
+
|
18 |
+
##-------------------start-of-clear_console()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
19 |
+
|
20 |
+
@staticmethod
|
21 |
+
def clear_console() -> None:
|
22 |
+
|
23 |
+
"""
|
24 |
+
|
25 |
+
Clears the console.
|
26 |
+
|
27 |
+
"""
|
28 |
+
|
29 |
+
os.system('cls' if os.name == 'nt' else 'clear')
|
30 |
+
|
31 |
+
##-------------------start-of-pause_console()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
32 |
+
|
33 |
+
@staticmethod
|
34 |
+
def pause_console(message:str="Press any key to continue...") -> None:
|
35 |
+
|
36 |
+
"""
|
37 |
+
|
38 |
+
Pauses the console.
|
39 |
+
Requires msvcrt on Windows and termios on Linux/Mac, will do nothing if neither are present.
|
40 |
+
|
41 |
+
Parameters:
|
42 |
+
message (string | optional) : The custom message to be displayed to the user.
|
43 |
+
|
44 |
+
"""
|
45 |
+
|
46 |
+
try:
|
47 |
+
|
48 |
+
print(message)
|
49 |
+
|
50 |
+
## Windows
|
51 |
+
if(os.name == 'nt'):
|
52 |
+
|
53 |
+
import msvcrt
|
54 |
+
|
55 |
+
msvcrt.getch()
|
56 |
+
|
57 |
+
## Linux and Mac
|
58 |
+
elif(os.name == 'posix'):
|
59 |
+
|
60 |
+
import termios
|
61 |
+
|
62 |
+
## Save terminal settings
|
63 |
+
old_settings = termios.tcgetattr(0)
|
64 |
+
|
65 |
+
try:
|
66 |
+
new_settings = termios.tcgetattr(0)
|
67 |
+
new_settings[3] = new_settings[3] & ~termios.ICANON
|
68 |
+
termios.tcsetattr(0, termios.TCSANOW, new_settings)
|
69 |
+
os.read(0, 1) ## Wait for any key press
|
70 |
+
|
71 |
+
finally:
|
72 |
+
|
73 |
+
termios.tcsetattr(0, termios.TCSANOW, old_settings)
|
74 |
+
|
75 |
+
except ImportError:
|
76 |
+
|
77 |
+
pass
|
78 |
+
|
79 |
+
##-------------------start-of-maximize_window()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
80 |
+
|
81 |
+
@staticmethod
|
82 |
+
def maximize_window():
|
83 |
+
|
84 |
+
"""
|
85 |
+
|
86 |
+
Maximizes the console window.
|
87 |
+
|
88 |
+
"""
|
89 |
+
|
90 |
+
try:
|
91 |
+
|
92 |
+
system_name = platform.system()
|
93 |
+
|
94 |
+
if(system_name == "Windows"):
|
95 |
+
os.system('mode con: cols=140 lines=40')
|
96 |
+
|
97 |
+
elif(system_name == "Linux"):
|
98 |
+
print("\033[8;40;140t")
|
99 |
+
|
100 |
+
elif(system_name == "Darwin"):
|
101 |
+
subprocess.call(["printf", "'\\e[8;40;140t'"])
|
102 |
+
|
103 |
+
except:
|
104 |
+
pass
|
105 |
+
|
106 |
+
##-------------------start-of-minimize_window()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
107 |
+
|
108 |
+
@staticmethod
|
109 |
+
def minimize_window():
|
110 |
+
|
111 |
+
"""
|
112 |
+
|
113 |
+
Minimizes the console window.
|
114 |
+
|
115 |
+
"""
|
116 |
+
|
117 |
+
try:
|
118 |
+
|
119 |
+
system_name = platform.system()
|
120 |
+
|
121 |
+
if(system_name == "Windows"):
|
122 |
+
os.system('mode con: cols=80 lines=25')
|
123 |
+
|
124 |
+
elif(system_name == "Linux"):
|
125 |
+
print("\033[8;25;80t")
|
126 |
+
|
127 |
+
elif(system_name == "Darwin"):
|
128 |
+
subprocess.call(["printf", "'\\e[8;25;80t'"])
|
129 |
+
|
130 |
+
except:
|
131 |
+
pass
|
132 |
+
|
133 |
+
##-------------------start-of-get_elapsed_time()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
134 |
+
|
135 |
+
@staticmethod
|
136 |
+
def get_elapsed_time(start:float, end:float) -> str:
|
137 |
+
|
138 |
+
"""
|
139 |
+
|
140 |
+
Calculates elapsed time with an offset.
|
141 |
+
|
142 |
+
Parameters:
|
143 |
+
start (float) : Start time.
|
144 |
+
end (float) : End time.
|
145 |
+
|
146 |
+
Returns:
|
147 |
+
print_value (string): The elapsed time in a human-readable format.
|
148 |
+
|
149 |
+
"""
|
150 |
+
|
151 |
+
elapsed_time = end - start
|
152 |
+
print_value = ""
|
153 |
+
|
154 |
+
if(elapsed_time < 60.0):
|
155 |
+
print_value = str(round(elapsed_time, 2)) + " seconds"
|
156 |
+
elif(elapsed_time < 3600.0):
|
157 |
+
print_value = str(round(elapsed_time / 60, 2)) + " minutes"
|
158 |
+
else:
|
159 |
+
print_value = str(round(elapsed_time / 3600, 2)) + " hours"
|
160 |
+
|
161 |
+
return print_value
|
162 |
+
|
163 |
+
##-------------------start-of-check_update()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
164 |
+
|
165 |
+
@staticmethod
|
166 |
+
def check_update() -> typing.Tuple[bool, str]:
|
167 |
+
|
168 |
+
"""
|
169 |
+
|
170 |
+
Determines if Kudasai has a new latest release, and confirms if an internet connection is present or not.
|
171 |
+
|
172 |
+
Returns:
|
173 |
+
is_connection (bool) : Whether or not the user has an internet connection.
|
174 |
+
update_prompt (str) : The update prompt to be displayed to the user, can either be blank if there is no update or contain the update prompt if there is an update.
|
175 |
+
|
176 |
+
"""
|
177 |
+
|
178 |
+
update_prompt = ""
|
179 |
+
is_connection = True
|
180 |
+
|
181 |
+
try:
|
182 |
+
|
183 |
+
from urllib.request import urlopen
|
184 |
+
import json
|
185 |
+
from distutils.version import LooseVersion
|
186 |
+
|
187 |
+
response = urlopen("https://api.github.com/repos/Bikatr7/Kudasai/releases/latest")
|
188 |
+
data = json.loads(response.read().decode())
|
189 |
+
|
190 |
+
latest_version = str(data["tag_name"])
|
191 |
+
release_notes = data["body"]
|
192 |
+
|
193 |
+
if(LooseVersion(latest_version) > LooseVersion(Toolkit.CURRENT_VERSION)):
|
194 |
+
|
195 |
+
update_prompt += "There is a new update for Kudasai (" + latest_version + ")\nIt is recommended that you use the latest version of Kudasai\nYou can download it at https://github.com/Bikatr7/Kudasai/releases/latest \n"
|
196 |
+
|
197 |
+
if(release_notes):
|
198 |
+
update_prompt += "\nRelease notes:\n\n" + release_notes + '\n'
|
199 |
+
|
200 |
+
return is_connection, update_prompt
|
201 |
+
|
202 |
+
## used to determine if user lacks an internet connection.
|
203 |
+
except:
|
204 |
+
|
205 |
+
print("You seem to lack an internet connection, this will prevent you from checking from update notification and machine translation.\n")
|
206 |
+
|
207 |
+
Toolkit.pause_console()
|
208 |
+
|
209 |
+
is_connection = False
|
210 |
+
|
211 |
+
return is_connection, update_prompt
|
212 |
+
|
213 |
+
##-------------------start-of-get_timestamp()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
214 |
+
|
215 |
+
@staticmethod
|
216 |
+
def get_timestamp(is_archival:bool=False) -> str:
|
217 |
+
|
218 |
+
"""
|
219 |
+
|
220 |
+
Generates a timestamp for an action taken by Kudasai.
|
221 |
+
|
222 |
+
Parameters:
|
223 |
+
is_archival (bool | optional) : Whether or not the timestamp is for archival purposes.
|
224 |
+
|
225 |
+
Returns:
|
226 |
+
time_stamp (string) : The timestamp for the action.
|
227 |
+
|
228 |
+
"""
|
229 |
+
|
230 |
+
if(is_archival):
|
231 |
+
time_stamp = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
|
232 |
+
|
233 |
+
else:
|
234 |
+
time_stamp = "[" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "] "
|
235 |
+
|
236 |
+
return time_stamp
|
237 |
+
|
238 |
+
##-------------------start-of-string_to_bool()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
239 |
+
|
240 |
+
@staticmethod
|
241 |
+
def string_to_bool(string:str) -> bool:
|
242 |
+
|
243 |
+
"""
|
244 |
+
|
245 |
+
Converts a string to a boolean.
|
246 |
+
|
247 |
+
Parameters:
|
248 |
+
string (str) : The string to be converted.
|
249 |
+
|
250 |
+
Returns:
|
251 |
+
(bool) : The converted boolean.
|
252 |
+
|
253 |
+
"""
|
254 |
+
|
255 |
+
return string.lower() in ['true', '1', 'yes', 'y', 't']
|
modules/gui/gui_file_util.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import json
|
3 |
+
|
4 |
+
##-------------------start-of-gui_get_text_from_file()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
5 |
+
|
6 |
+
def gui_get_text_from_file(file) -> str:
|
7 |
+
|
8 |
+
"""
|
9 |
+
|
10 |
+
This function extracts the text from a file.
|
11 |
+
|
12 |
+
Parameters:
|
13 |
+
file (gr.File) : The file to extract the text from.
|
14 |
+
|
15 |
+
"""
|
16 |
+
|
17 |
+
file_path:str = file.name ## type: ignore | name is not type hinting for some fucking reason
|
18 |
+
|
19 |
+
with open(file_path, "r", encoding='utf-8') as file:
|
20 |
+
text = file.read()
|
21 |
+
|
22 |
+
return text
|
23 |
+
|
24 |
+
##-------------------start-of-gui_get_json_from_file()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
25 |
+
|
26 |
+
def gui_get_json_from_file(file) -> dict:
|
27 |
+
|
28 |
+
"""
|
29 |
+
|
30 |
+
This functions extracts the text from a json file and forms it into a dict.
|
31 |
+
|
32 |
+
Parameters:
|
33 |
+
file (gr.File) : The file to form a json from.
|
34 |
+
|
35 |
+
"""
|
36 |
+
|
37 |
+
file_path:str = file.name ## type: ignore | name is not type hinting for some fucking reason
|
38 |
+
|
39 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
40 |
+
json_dict = json.load(file)
|
41 |
+
|
42 |
+
return json_dict
|
modules/gui/gui_json_util.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import json
|
3 |
+
import typing
|
4 |
+
|
5 |
+
## third-party libraries
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
## custom modules
|
9 |
+
from modules.common.file_ensurer import FileEnsurer
|
10 |
+
|
11 |
+
from handlers.json_handler import JsonHandler
|
12 |
+
|
13 |
+
class GuiJsonUtil:
|
14 |
+
|
15 |
+
current_kijiku_rules = dict()
|
16 |
+
|
17 |
+
##-------------------start-of-fetch_kijiku_setting_key_values()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
18 |
+
|
19 |
+
@staticmethod
|
20 |
+
def fetch_kijiku_setting_key_values(header:str, key_name:str) -> str:
|
21 |
+
|
22 |
+
"""
|
23 |
+
|
24 |
+
Fetches the default values for the settings tab from the kijiku_settings.json file.
|
25 |
+
|
26 |
+
Parameters:
|
27 |
+
key_name (str) : Which value to fetch.
|
28 |
+
|
29 |
+
Returns:
|
30 |
+
(str) : The default value for the specified key.
|
31 |
+
|
32 |
+
"""
|
33 |
+
|
34 |
+
## Done this way because if the value is None, it'll be shown as a blank string in the settings tab, which is not what we want.
|
35 |
+
return GuiJsonUtil.current_kijiku_rules[header].get(key_name, "None")
|
36 |
+
|
37 |
+
##-------------------start-of-update_kijiku_settings_with_new_values()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
38 |
+
|
39 |
+
@staticmethod
|
40 |
+
def update_kijiku_settings_with_new_values(gradio_kijiku_rule:gr.File, new_values:typing.List[typing.Tuple[str,str]]) -> None:
|
41 |
+
|
42 |
+
"""
|
43 |
+
|
44 |
+
Dumps the new values for the settings tab into the kijiku_settings.json file.
|
45 |
+
|
46 |
+
Parameters:
|
47 |
+
new_values (typing.List[typing.Tuple[str,str]]) : A list of tuples containing the key and value to be updated.
|
48 |
+
|
49 |
+
"""
|
50 |
+
|
51 |
+
## save old json in case of need to revert
|
52 |
+
old_rules = GuiJsonUtil.current_kijiku_rules
|
53 |
+
new_rules = old_rules.copy()
|
54 |
+
|
55 |
+
try:
|
56 |
+
|
57 |
+
for header in new_rules.keys():
|
58 |
+
for key, value in new_values:
|
59 |
+
new_rules[header][key] = JsonHandler.convert_to_correct_type(key, str(value))
|
60 |
+
|
61 |
+
JsonHandler.current_kijiku_rules = new_rules
|
62 |
+
JsonHandler.validate_json()
|
63 |
+
|
64 |
+
## validate_json() sets a dict to the invalid placeholder if it's invalid, so if it's that, it's invalid
|
65 |
+
assert JsonHandler.current_kijiku_rules != FileEnsurer.INVALID_KIJIKU_RULES_PLACEHOLDER
|
66 |
+
|
67 |
+
## so, because of how gradio deals with temp file, we need to both dump into the settings file from FileEnsurer AND the gradio_kijiku_rule file which is stored in the temp folder under AppData
|
68 |
+
## name is the path to the file btw
|
69 |
+
with open(FileEnsurer.config_kijiku_rules_path, "w") as file:
|
70 |
+
json.dump(new_rules, file)
|
71 |
+
|
72 |
+
with open(gradio_kijiku_rule.name, "w") as file: ## type: ignore
|
73 |
+
json.dump(new_rules, file)
|
74 |
+
|
75 |
+
GuiJsonUtil.current_kijiku_rules = new_rules
|
76 |
+
|
77 |
+
except Exception as e:
|
78 |
+
|
79 |
+
## revert to old data
|
80 |
+
with open(FileEnsurer.config_kijiku_rules_path, "w") as file:
|
81 |
+
json.dump(old_rules, file)
|
82 |
+
|
83 |
+
with open(gradio_kijiku_rule.name, "w") as file: ## type: ignore
|
84 |
+
json.dump(old_rules, file)
|
85 |
+
|
86 |
+
GuiJsonUtil.current_kijiku_rules = old_rules
|
87 |
+
|
88 |
+
## throw error so webgui can tell user
|
89 |
+
raise e
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
deepl==1.16.1
|
2 |
+
openai==1.13.3
|
3 |
+
backoff==2.2.1
|
4 |
+
tiktoken==0.6.0
|
5 |
+
gradio==4.19.2
|
6 |
+
kairyou==1.4.0
|
7 |
+
google-generativeai==0.4.0
|
translation_services/deepl_service.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import typing
|
3 |
+
|
4 |
+
## third-party libraries
|
5 |
+
from deepl.translator import Translator
|
6 |
+
|
7 |
+
class DeepLService:
|
8 |
+
|
9 |
+
api_key:str
|
10 |
+
translator:Translator
|
11 |
+
|
12 |
+
##-------------------start-of-translate()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
13 |
+
|
14 |
+
@staticmethod
|
15 |
+
def translate(text:str, target_lang:str, source_lang:str) -> str:
|
16 |
+
|
17 |
+
"""
|
18 |
+
|
19 |
+
Translates the text to the target language.
|
20 |
+
|
21 |
+
Parameters:
|
22 |
+
text (string) : The text to translate.
|
23 |
+
target_lang (string) : The target language.
|
24 |
+
source_lang (string) : The source language.
|
25 |
+
|
26 |
+
Returns:
|
27 |
+
translation (string) : The translated text.
|
28 |
+
|
29 |
+
"""
|
30 |
+
|
31 |
+
try:
|
32 |
+
|
33 |
+
translation = DeepLService.translator.translate_text(text, target_lang=target_lang, source_lang=source_lang)
|
34 |
+
|
35 |
+
return str(translation)
|
36 |
+
|
37 |
+
except Exception as e:
|
38 |
+
raise e
|
39 |
+
|
40 |
+
##-------------------start-of-set_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
41 |
+
|
42 |
+
@staticmethod
|
43 |
+
def set_api_key(api_key:str) -> None:
|
44 |
+
|
45 |
+
"""
|
46 |
+
|
47 |
+
Sets the API key for the DeepL client.
|
48 |
+
|
49 |
+
Parameters:
|
50 |
+
api_key (string) : The API key to set.
|
51 |
+
|
52 |
+
"""
|
53 |
+
|
54 |
+
DeepLService.api_key = api_key
|
55 |
+
|
56 |
+
##-------------------start-of-test_api_key_validity()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
57 |
+
|
58 |
+
@staticmethod
|
59 |
+
def test_api_key_validity() -> typing.Tuple[bool, typing.Union[Exception, None]]:
|
60 |
+
|
61 |
+
"""
|
62 |
+
|
63 |
+
Tests the validity of the API key.
|
64 |
+
|
65 |
+
Returns:
|
66 |
+
validity (bool) : True if the API key is valid, False if it is not.
|
67 |
+
e (Exception) : The exception that was raised, if any.
|
68 |
+
|
69 |
+
"""
|
70 |
+
|
71 |
+
validity = False
|
72 |
+
|
73 |
+
try:
|
74 |
+
|
75 |
+
DeepLService.translator = Translator(DeepLService.api_key)
|
76 |
+
|
77 |
+
DeepLService.translator.translate_text("test", target_lang="JA")
|
78 |
+
|
79 |
+
validity = True
|
80 |
+
|
81 |
+
return validity, None
|
82 |
+
|
83 |
+
except Exception as e:
|
84 |
+
|
85 |
+
return validity, e
|
translation_services/gemini_service.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import typing
|
3 |
+
|
4 |
+
## third party libraries
|
5 |
+
from google.generativeai import GenerationConfig
|
6 |
+
import google.generativeai as genai
|
7 |
+
|
8 |
+
class GeminiService:
|
9 |
+
|
10 |
+
model:str = "gemini-pro"
|
11 |
+
prompt:str = ""
|
12 |
+
temperature:float = 0.5
|
13 |
+
top_p:float = 0.9
|
14 |
+
top_k:int = 40
|
15 |
+
candidate_count:int = 1
|
16 |
+
stream:bool = False
|
17 |
+
stop_sequences:typing.List[str] | None = None
|
18 |
+
max_output_tokens:int | None = None
|
19 |
+
|
20 |
+
client:genai.GenerativeModel
|
21 |
+
generation_config:GenerationConfig
|
22 |
+
|
23 |
+
decorator_to_use:typing.Union[typing.Callable, None] = None
|
24 |
+
|
25 |
+
safety_settings = [
|
26 |
+
{
|
27 |
+
"category": "HARM_CATEGORY_DANGEROUS",
|
28 |
+
"threshold": "BLOCK_NONE",
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"category": "HARM_CATEGORY_HARASSMENT",
|
32 |
+
"threshold": "BLOCK_NONE",
|
33 |
+
},
|
34 |
+
{
|
35 |
+
"category": "HARM_CATEGORY_HATE_SPEECH",
|
36 |
+
"threshold": "BLOCK_NONE",
|
37 |
+
},
|
38 |
+
{
|
39 |
+
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
40 |
+
"threshold": "BLOCK_NONE",
|
41 |
+
},
|
42 |
+
{
|
43 |
+
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
44 |
+
"threshold": "BLOCK_NONE",
|
45 |
+
},
|
46 |
+
]
|
47 |
+
|
48 |
+
##-------------------start-of-set_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
49 |
+
|
50 |
+
@staticmethod
|
51 |
+
def set_api_key(api_key:str) -> None:
|
52 |
+
|
53 |
+
"""
|
54 |
+
|
55 |
+
Sets the API key for the Gemini client.
|
56 |
+
|
57 |
+
Parameters:
|
58 |
+
api_key (string) : The API key to set.
|
59 |
+
|
60 |
+
"""
|
61 |
+
|
62 |
+
genai.configure(api_key=api_key)
|
63 |
+
|
64 |
+
##-------------------start-of-set_decorator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
65 |
+
|
66 |
+
@staticmethod
|
67 |
+
def set_decorator(decorator:typing.Callable) -> None:
|
68 |
+
|
69 |
+
"""
|
70 |
+
|
71 |
+
Sets the decorator to use for the Gemini service. Should be a callable that returns a decorator.
|
72 |
+
|
73 |
+
Parameters:
|
74 |
+
decorator (callable) : The decorator to use.
|
75 |
+
|
76 |
+
"""
|
77 |
+
|
78 |
+
GeminiService.decorator_to_use = decorator
|
79 |
+
|
80 |
+
##-------------------start-of-setup_client()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
81 |
+
|
82 |
+
@staticmethod
|
83 |
+
def redefine_client() -> None:
|
84 |
+
|
85 |
+
"""
|
86 |
+
|
87 |
+
Redefines the Gemini client and generation config. This should be called before making any requests to the Gemini service, or after changing any of the service's settings.
|
88 |
+
|
89 |
+
"""
|
90 |
+
|
91 |
+
GeminiService.client = genai.GenerativeModel(GeminiService.model)
|
92 |
+
GeminiService.generation_config = GenerationConfig(candidate_count=GeminiService.candidate_count,
|
93 |
+
max_output_tokens=GeminiService.max_output_tokens,
|
94 |
+
stop_sequences=GeminiService.stop_sequences,
|
95 |
+
temperature=GeminiService.temperature,
|
96 |
+
top_p=GeminiService.top_p,
|
97 |
+
top_k=GeminiService.top_k)
|
98 |
+
|
99 |
+
##-------------------start-of-count_tokens()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
100 |
+
|
101 |
+
@staticmethod
|
102 |
+
def count_tokens(prompt:str) -> int:
|
103 |
+
|
104 |
+
"""
|
105 |
+
|
106 |
+
Counts the number of tokens in a prompt.
|
107 |
+
|
108 |
+
Parameters:
|
109 |
+
prompt (string) : The prompt to count the tokens of.
|
110 |
+
|
111 |
+
Returns:
|
112 |
+
count (int) : The number of tokens in the prompt.
|
113 |
+
|
114 |
+
"""
|
115 |
+
|
116 |
+
return genai.GenerativeModel(GeminiService.model).count_tokens(prompt).total_tokens
|
117 |
+
|
118 |
+
##-------------------start-of-trans()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
119 |
+
|
120 |
+
@staticmethod
|
121 |
+
async def translate_message(translation_instructions:str, translation_prompt:str) -> str:
|
122 |
+
|
123 |
+
"""
|
124 |
+
|
125 |
+
Translates a prompt.
|
126 |
+
|
127 |
+
Parameters:
|
128 |
+
translation_prompt (object - ModelTranslationMessage) : The prompt to translate.
|
129 |
+
|
130 |
+
Returns:
|
131 |
+
output (string) : The translation.
|
132 |
+
|
133 |
+
"""
|
134 |
+
|
135 |
+
if(GeminiService.decorator_to_use is None):
|
136 |
+
return await GeminiService._translate_message(translation_instructions, translation_prompt)
|
137 |
+
|
138 |
+
decorated_function = GeminiService.decorator_to_use(GeminiService._translate_message)
|
139 |
+
return await decorated_function(translation_instructions, translation_prompt)
|
140 |
+
|
141 |
+
##-------------------start-of-_translate_message()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
142 |
+
|
143 |
+
@staticmethod
|
144 |
+
async def _translate_message(translation_instructions:str, translation_prompt:str) -> str:
|
145 |
+
|
146 |
+
"""
|
147 |
+
|
148 |
+
Translates a prompt.
|
149 |
+
|
150 |
+
Parameters:
|
151 |
+
translation_prompt (string) : The prompt to translate.
|
152 |
+
|
153 |
+
Returns:
|
154 |
+
output (string) a string that gpt gives to us also known as the translation.
|
155 |
+
|
156 |
+
"""
|
157 |
+
|
158 |
+
response = await GeminiService.client.generate_content_async(
|
159 |
+
contents=translation_instructions + "\n" + translation_prompt,
|
160 |
+
generation_config=GeminiService.generation_config,
|
161 |
+
safety_settings=GeminiService.safety_settings,
|
162 |
+
stream=GeminiService.stream
|
163 |
+
)
|
164 |
+
|
165 |
+
return response.text
|
166 |
+
|
167 |
+
##-------------------start-of-test_api_key_validity()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
168 |
+
|
169 |
+
@staticmethod
|
170 |
+
async def test_api_key_validity() -> typing.Tuple[bool, typing.Union[Exception, None]]:
|
171 |
+
|
172 |
+
"""
|
173 |
+
|
174 |
+
Tests the validity of the API key.
|
175 |
+
|
176 |
+
Returns:
|
177 |
+
validity (bool) : True if the API key is valid, False if it is not.
|
178 |
+
e (Exception) : The exception that was raised, if any.
|
179 |
+
|
180 |
+
"""
|
181 |
+
|
182 |
+
validity = False
|
183 |
+
|
184 |
+
try:
|
185 |
+
|
186 |
+
generation_config = GenerationConfig(candidate_count=1, max_output_tokens=1)
|
187 |
+
|
188 |
+
await GeminiService.client.generate_content_async(
|
189 |
+
"Respond to this prompt with 1",generation_config=generation_config
|
190 |
+
|
191 |
+
)
|
192 |
+
|
193 |
+
validity = True
|
194 |
+
|
195 |
+
return validity, None
|
196 |
+
|
197 |
+
except Exception as e:
|
198 |
+
|
199 |
+
return validity, e
|
200 |
+
|
201 |
+
##-------------------start-of-get_decorator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
202 |
+
|
203 |
+
@staticmethod
|
204 |
+
def get_decorator() -> typing.Union[typing.Callable, None]:
|
205 |
+
|
206 |
+
"""
|
207 |
+
|
208 |
+
Returns the decorator to use for the Gemini service.
|
209 |
+
|
210 |
+
Returns:
|
211 |
+
decorator (callable) : The decorator to use.
|
212 |
+
|
213 |
+
"""
|
214 |
+
|
215 |
+
return GeminiService.decorator_to_use
|
translation_services/openai_service.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
import typing
|
3 |
+
|
4 |
+
## third-party libraries
|
5 |
+
from openai import AsyncOpenAI
|
6 |
+
|
7 |
+
## custom modules
|
8 |
+
from modules.common.exceptions import InvalidAPIKeyException
|
9 |
+
from custom_classes.messages import SystemTranslationMessage, Message
|
10 |
+
|
11 |
+
class OpenAIService:
|
12 |
+
|
13 |
+
## async client session
|
14 |
+
client = AsyncOpenAI(max_retries=0, api_key="DummyKey")
|
15 |
+
|
16 |
+
model:str
|
17 |
+
system_message:typing.Optional[typing.Union[SystemTranslationMessage, str]] = None
|
18 |
+
temperature:float
|
19 |
+
top_p:float
|
20 |
+
n:int
|
21 |
+
stream:bool
|
22 |
+
stop:typing.List[str] | None
|
23 |
+
logit_bias:typing.Dict[str, float] | None
|
24 |
+
max_tokens:int | None
|
25 |
+
presence_penalty:float
|
26 |
+
frequency_penalty:float
|
27 |
+
|
28 |
+
decorator_to_use:typing.Union[typing.Callable, None] = None
|
29 |
+
|
30 |
+
##-------------------start-of-set_api_key()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
31 |
+
|
32 |
+
@staticmethod
|
33 |
+
def set_api_key(api_key:str) -> None:
|
34 |
+
|
35 |
+
"""
|
36 |
+
|
37 |
+
Sets the API key for the OpenAI client.
|
38 |
+
|
39 |
+
Parameters:
|
40 |
+
api_key (string) : The API key to set.
|
41 |
+
|
42 |
+
"""
|
43 |
+
|
44 |
+
OpenAIService.client.api_key = api_key
|
45 |
+
|
46 |
+
##-------------------start-of-set_decorator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
47 |
+
|
48 |
+
@staticmethod
|
49 |
+
def set_decorator(decorator:typing.Callable) -> None:
|
50 |
+
|
51 |
+
"""
|
52 |
+
|
53 |
+
Sets the decorator to use for the OpenAI service. Should be a callable that returns a decorator.
|
54 |
+
|
55 |
+
Parameters:
|
56 |
+
decorator (callable) : The decorator to use.
|
57 |
+
|
58 |
+
"""
|
59 |
+
|
60 |
+
OpenAIService.decorator_to_use = decorator
|
61 |
+
|
62 |
+
##-------------------start-of-trans()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
63 |
+
|
64 |
+
@staticmethod
|
65 |
+
async def translate_message(translation_instructions:Message, translation_prompt:Message) -> str:
|
66 |
+
|
67 |
+
"""
|
68 |
+
|
69 |
+
Translates a system and user message.
|
70 |
+
|
71 |
+
Parameters:
|
72 |
+
translation_instructions (object - SystemTranslationMessage | ModelTranslationMessage) : The system message also known as the instructions.
|
73 |
+
translation_prompt (object - ModelTranslationMessage) : The user message also known as the prompt.
|
74 |
+
|
75 |
+
Returns:
|
76 |
+
output (string) a string that gpt gives to us also known as the translation.
|
77 |
+
|
78 |
+
"""
|
79 |
+
|
80 |
+
if(OpenAIService.decorator_to_use == None):
|
81 |
+
return await OpenAIService._translate_message(translation_instructions, translation_prompt)
|
82 |
+
|
83 |
+
decorated_function = OpenAIService.decorator_to_use(OpenAIService._translate_message)
|
84 |
+
return await decorated_function(translation_instructions, translation_prompt)
|
85 |
+
|
86 |
+
##-------------------start-of-_translate_message()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
87 |
+
|
88 |
+
## backoff wrapper for retrying on errors, As of OpenAI > 1.0.0, it comes with a built in backoff system, but I've grown accustomed to this one so I'm keeping it.
|
89 |
+
@staticmethod
|
90 |
+
async def _translate_message(translation_instructions:Message, translation_prompt:Message) -> str:
|
91 |
+
|
92 |
+
"""
|
93 |
+
|
94 |
+
Translates a system and user message.
|
95 |
+
|
96 |
+
Parameters:
|
97 |
+
translation_instructions (object - SystemTranslationMessage | ModelTranslationMessage) : The system message also known as the instructions.
|
98 |
+
translation_prompt (object - ModelTranslationMessage) : The user message also known as the prompt.
|
99 |
+
|
100 |
+
Returns:
|
101 |
+
output (string) a string that gpt gives to us also known as the translation.
|
102 |
+
|
103 |
+
"""
|
104 |
+
|
105 |
+
if(OpenAIService.client.api_key == "DummyKey"):
|
106 |
+
raise InvalidAPIKeyException("OpenAI")
|
107 |
+
|
108 |
+
## logit bias is currently excluded due to a lack of need, and the fact that i am lazy
|
109 |
+
|
110 |
+
response = await OpenAIService.client.chat.completions.create(
|
111 |
+
model=OpenAIService.model,
|
112 |
+
messages=[
|
113 |
+
translation_instructions.to_dict(),
|
114 |
+
translation_prompt.to_dict()
|
115 |
+
], # type: ignore
|
116 |
+
|
117 |
+
temperature = OpenAIService.temperature,
|
118 |
+
top_p = OpenAIService.top_p,
|
119 |
+
n = OpenAIService.n,
|
120 |
+
stream = OpenAIService.stream,
|
121 |
+
stop = OpenAIService.stop,
|
122 |
+
presence_penalty = OpenAIService.presence_penalty,
|
123 |
+
frequency_penalty = OpenAIService.frequency_penalty,
|
124 |
+
max_tokens = OpenAIService.max_tokens
|
125 |
+
|
126 |
+
)
|
127 |
+
|
128 |
+
## if anyone knows how to type hint this please let me know
|
129 |
+
output = response.choices[0].message.content
|
130 |
+
|
131 |
+
return output
|
132 |
+
|
133 |
+
##-------------------start-of-test_api_key_validity()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
134 |
+
|
135 |
+
@staticmethod
|
136 |
+
async def test_api_key_validity() -> typing.Tuple[bool, typing.Union[Exception, None]]:
|
137 |
+
|
138 |
+
"""
|
139 |
+
|
140 |
+
Tests the validity of the API key.
|
141 |
+
|
142 |
+
Returns:
|
143 |
+
validity (bool) : True if the API key is valid, False if it is not.
|
144 |
+
e (Exception) : The exception that was raised, if any.
|
145 |
+
|
146 |
+
"""
|
147 |
+
|
148 |
+
validity = False
|
149 |
+
|
150 |
+
try:
|
151 |
+
|
152 |
+
await OpenAIService.client.chat.completions.create(
|
153 |
+
model="gpt-3.5-turbo",
|
154 |
+
messages=[{"role":"user","content":"This is a test."}],
|
155 |
+
max_tokens=1
|
156 |
+
)
|
157 |
+
|
158 |
+
validity = True
|
159 |
+
|
160 |
+
return validity, None
|
161 |
+
|
162 |
+
except Exception as e:
|
163 |
+
|
164 |
+
return validity, e
|
165 |
+
|
166 |
+
##-------------------start-of-get_decorator()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
167 |
+
|
168 |
+
@staticmethod
|
169 |
+
def get_decorator() -> typing.Union[typing.Callable, None]:
|
170 |
+
|
171 |
+
"""
|
172 |
+
|
173 |
+
Returns the decorator to use for the OpenAI service.
|
174 |
+
|
175 |
+
Returns:
|
176 |
+
decorator (callable) : The decorator to use.
|
177 |
+
|
178 |
+
"""
|
179 |
+
|
180 |
+
return OpenAIService.decorator_to_use
|
util/openai_model_info/openai_chat_model_info.csv
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
,Batch,Name,Price,Recommended Replacement,Depreciation Date,Shutdown Date (earliest)
|
2 |
+
,,,,,,
|
3 |
+
,First (depreciated I),gpt-3.5-turbo-0301,$0.0015 / 1K input tokens + $0.0020 / 1K output tokens,gpt-3.5-turbo-0613,"June 13, 2023","June 13, 2024"
|
4 |
+
,,gpt-4-0314,$0.03 / 1K input tokens + $0.06 / 1K output tokens,gpt-4-0613,"June 13, 2023","June 13, 2024"
|
5 |
+
,,gpt-4-32k-0314,$0.06 / 1K input tokens + $0.12 / 1K output tokens,gpt-4-32k-0613,"June 13, 2023","June 13, 2024"
|
6 |
+
,,,,,,
|
7 |
+
,Second (depreciated II),gpt-3.5-turbo-0613,$0.0015 / 1K input tokens + $0.0020 / 1K output tokens,gpt-3.5-turbo-1106,"November 6,2023","June 13, 2024"
|
8 |
+
,,gpt-3.5-turbo-16k-0613,$0.0030 / 1K input tokens + $0.0040 / 1K output tokens,gpt-3.5-turbo-1106,"November 6,2023","June 13, 2024"
|
9 |
+
,,,,,,
|
10 |
+
,Third (Outdated),gpt-3.5-turbo-1106,$0.0010 / 1K input tokens + $0.0020 / 1K output tokens,N/A,N/A,N/A
|
11 |
+
,,,,,,
|
12 |
+
,Fourth (Current),gpt-3.5-turbo-0125,$0.005 / 1K input tokens + $0.0015 / 1K output tokens,N/A,N/A,N/A
|
13 |
+
,,gpt-4-0613,$0.03 / 1K input tokens + $0.06 / 1K output tokens,N/A,N/A,N/A
|
14 |
+
,,gpt-4-32k-0613,$0.06 / 1K input tokens + $0.012 / 1K output tokens,N/A,N/A,N/A
|
15 |
+
,,,,,,
|
16 |
+
,Fifth (Future),gpt-4-1106-preview,$0.01 / 1K input tokens + $0.03 / 1K output tokens,N/A,N/A,N/A
|
17 |
+
,,gpt-4-0125-preview,$0.01 / 1K input tokens + $0.03 / 1K output tokens,N/A,N/A,N/A
|
util/openai_model_info/openai_chat_model_info.pdf
ADDED
Binary file (31.3 kB). View file
|
|
util/openai_model_info/openai_chat_model_info.xlsx
ADDED
Binary file (5.68 kB). View file
|
|
util/openai_model_info/webpage/openai_chat_model_info.html
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link type="text/css" rel="stylesheet" href="resources/sheet.css" >
|
2 |
+
<style type="text/css">.ritz .waffle a { color: inherit; }.ritz .waffle .s1{background-color:#ffffff;text-align:right;color:#000000;font-family:'Arial';font-size:10pt;vertical-align:bottom;white-space:nowrap;direction:ltr;padding:2px 3px 2px 3px;}.ritz .waffle .s0{background-color:#ffffff;text-align:left;color:#000000;font-family:'Arial';font-size:10pt;vertical-align:bottom;white-space:nowrap;direction:ltr;padding:2px 3px 2px 3px;}</style><div class="ritz grid-container" dir="ltr"><table class="waffle" cellspacing="0" cellpadding="0"><thead><tr><th class="row-header freezebar-origin-ltr"></th><th id="0C0" style="width:100px;" class="column-headers-background">A</th><th id="0C1" style="width:141px;" class="column-headers-background">B</th><th id="0C2" style="width:159px;" class="column-headers-background">C</th><th id="0C3" style="width:336px;" class="column-headers-background">D</th><th id="0C4" style="width:182px;" class="column-headers-background">E</th><th id="0C5" style="width:167px;" class="column-headers-background">F</th><th id="0C6" style="width:151px;" class="column-headers-background">G</th></tr></thead><tbody><tr style="height: 20px"><th id="0R0" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">1</div></th><td></td><td class="s0" dir="ltr">Batch</td><td class="s0" dir="ltr">Name</td><td class="s0" dir="ltr">Price</td><td class="s0" dir="ltr">Recommended Replacement</td><td class="s0" dir="ltr">Depreciation Date</td><td class="s0" dir="ltr">Shutdown Date (earliest)</td></tr><tr style="height: 20px"><th id="0R1" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">2</div></th><td></td><td></td><td></td><td></td><td></td><td class="s0" dir="ltr"></td><td class="s0" dir="ltr"></td></tr><tr style="height: 20px"><th id="0R2" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">3</div></th><td></td><td class="s0" dir="ltr">First (depreciated I)</td><td class="s0" dir="ltr">gpt-3.5-turbo-0301</td><td class="s0" dir="ltr">$0.0015 / 1K input tokens + $0.0020 / 1K output tokens</td><td class="s0" dir="ltr">gpt-3.5-turbo-0613</td><td class="s1" dir="ltr">June 13, 2023</td><td class="s1" dir="ltr">June 13, 2024</td></tr><tr style="height: 20px"><th id="0R3" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">4</div></th><td></td><td></td><td class="s0" dir="ltr">gpt-4-0314</td><td class="s0" dir="ltr">$0.03 / 1K input tokens + $0.06 / 1K output tokens</td><td class="s0" dir="ltr">gpt-4-0613</td><td class="s1" dir="ltr">June 13, 2023</td><td class="s1" dir="ltr">June 13, 2024</td></tr><tr style="height: 20px"><th id="0R4" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">5</div></th><td></td><td></td><td class="s0" dir="ltr">gpt-4-32k-0314</td><td class="s0" dir="ltr">$0.06 / 1K input tokens + $0.12 / 1K output tokens</td><td class="s0" dir="ltr">gpt-4-32k-0613</td><td class="s1" dir="ltr">June 13, 2023</td><td class="s1" dir="ltr">June 13, 2024</td></tr><tr style="height: 20px"><th id="0R5" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">6</div></th><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr style="height: 20px"><th id="0R6" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">7</div></th><td></td><td class="s0" dir="ltr">Second (depreciated II)</td><td class="s0" dir="ltr">gpt-3.5-turbo-0613</td><td class="s0" dir="ltr">$0.0015 / 1K input tokens + $0.0020 / 1K output tokens</td><td class="s0" dir="ltr">gpt-3.5-turbo-1106</td><td class="s1" dir="ltr">November 6,2023</td><td class="s1" dir="ltr">June 13, 2024</td></tr><tr style="height: 20px"><th id="0R7" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">8</div></th><td></td><td></td><td class="s0" dir="ltr">gpt-3.5-turbo-16k-0613</td><td class="s0" dir="ltr">$0.0030 / 1K input tokens + $0.0040 / 1K output tokens</td><td class="s0" dir="ltr">gpt-3.5-turbo-1106</td><td class="s1" dir="ltr">November 6,2023</td><td class="s1" dir="ltr">June 13, 2024</td></tr><tr style="height: 20px"><th id="0R8" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">9</div></th><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr style="height: 20px"><th id="0R9" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">10</div></th><td></td><td class="s0" dir="ltr">Third (Outdated)</td><td class="s0" dir="ltr">gpt-3.5-turbo-1106</td><td class="s0" dir="ltr">$0.0010 / 1K input tokens + $0.0020 / 1K output tokens</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td></tr><tr style="height: 20px"><th id="0R10" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">11</div></th><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr style="height: 20px"><th id="0R11" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">12</div></th><td></td><td class="s0" dir="ltr">Fourth (Current)</td><td class="s0" dir="ltr">gpt-3.5-turbo-0125</td><td class="s0" dir="ltr">$0.005 / 1K input tokens + $0.0015 / 1K output tokens</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td></tr><tr style="height: 20px"><th id="0R12" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">13</div></th><td></td><td></td><td class="s0" dir="ltr">gpt-4-0613</td><td class="s0" dir="ltr">$0.03 / 1K input tokens + $0.06 / 1K output tokens</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td></tr><tr style="height: 20px"><th id="0R13" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">14</div></th><td></td><td></td><td class="s0" dir="ltr">gpt-4-32k-0613</td><td class="s0" dir="ltr">$0.06 / 1K input tokens + $0.012 / 1K output tokens</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td><td class="s0" dir="ltr">N/A</td></tr><tr style="height: 20px"><th id="0R14" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">15</div></th><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr><tr style="height: 20px"><th id="0R15" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">16</div></th><td></td><td class="s0">Fifth (Future)</td><td class="s0">gpt-4-1106-preview</td><td class="s0">$0.01 / 1K input tokens + $0.03 / 1K output tokens</td><td class="s0">N/A</td><td class="s0">N/A</td><td class="s0">N/A</td></tr><tr style="height: 20px"><th id="0R16" style="height: 20px;" class="row-headers-background"><div class="row-header-wrapper" style="line-height: 20px">17</div></th><td></td><td class="s0"></td><td class="s0">gpt-4-0125-preview</td><td class="s0">$0.01 / 1K input tokens + $0.03 / 1K output tokens</td><td class="s0">N/A</td><td class="s0">N/A</td><td class="s0">N/A</td></tr></tbody></table></div>
|
util/openai_model_info/webpage/resources/sheet.css
ADDED
The diff for this file is too large to render.
See raw diff
|
|
util/token_counter.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## built-in libraries
|
2 |
+
from pathlib import Path
|
3 |
+
|
4 |
+
import sys
|
5 |
+
import os
|
6 |
+
|
7 |
+
## Calculates the path to the modules directory and add it to sys.path
|
8 |
+
current_dir = Path(__file__).resolve().parent
|
9 |
+
parent_dir = current_dir.parent
|
10 |
+
|
11 |
+
## Add the parent directory to sys.path so 'modules' can be found
|
12 |
+
sys.path.append(str(parent_dir))
|
13 |
+
|
14 |
+
## custom modules
|
15 |
+
from modules.common.toolkit import Toolkit
|
16 |
+
from models.kijiku import Kijiku
|
17 |
+
|
18 |
+
class TokenCounter:
|
19 |
+
|
20 |
+
"""
|
21 |
+
|
22 |
+
Util script for counting tokens, characters, and estimating cost of translating a text.
|
23 |
+
|
24 |
+
"""
|
25 |
+
|
26 |
+
##-------------------start-of-__init__()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
27 |
+
|
28 |
+
def __init__(self) -> None:
|
29 |
+
|
30 |
+
"""
|
31 |
+
|
32 |
+
Constructor for TokenCounter class.
|
33 |
+
|
34 |
+
"""
|
35 |
+
|
36 |
+
os.system("title " + "Token Counter")
|
37 |
+
|
38 |
+
self.MODEL:str = ""
|
39 |
+
|
40 |
+
##-------------------start-of-count_characters()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
41 |
+
|
42 |
+
def count_characters(self) -> int:
|
43 |
+
|
44 |
+
"""
|
45 |
+
|
46 |
+
Counts the number of characters in a string.
|
47 |
+
|
48 |
+
Parameters:
|
49 |
+
self (object - TokenCounter) : The TokenCounter object.
|
50 |
+
|
51 |
+
Returns:
|
52 |
+
num_characters (int) The number of characters in the text.
|
53 |
+
|
54 |
+
"""
|
55 |
+
|
56 |
+
Toolkit.clear_console()
|
57 |
+
|
58 |
+
num_characters = len(self.text)
|
59 |
+
|
60 |
+
return num_characters
|
61 |
+
|
62 |
+
##-------------------start-of-estimate_cost()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
63 |
+
|
64 |
+
def estimate_cost(self, text_file:str) -> None:
|
65 |
+
|
66 |
+
"""
|
67 |
+
|
68 |
+
Counts the number of tokens in a text file.
|
69 |
+
|
70 |
+
Parameters:
|
71 |
+
self (object - TokenCounter) : The TokenCounter object.
|
72 |
+
text_file (string) : The path to the text file.
|
73 |
+
|
74 |
+
"""
|
75 |
+
|
76 |
+
|
77 |
+
with open(text_file, 'r', encoding='utf-8') as file:
|
78 |
+
self.text = file.read()
|
79 |
+
|
80 |
+
self.MODEL = input("Please enter model : ")
|
81 |
+
|
82 |
+
## lazy workaround for now
|
83 |
+
Kijiku.text_to_translate = [line for line in self.text.splitlines()]
|
84 |
+
|
85 |
+
num_tokens, min_cost, self.MODEL = Kijiku.estimate_cost(self.MODEL)
|
86 |
+
num_characters = self.count_characters()
|
87 |
+
|
88 |
+
print("This is an estimate of the cost of translating a text using Kudasai. The actual cost may be higher or lower depending on the model used and the number of tokens in the text.\n")
|
89 |
+
print("Estimated Number of Tokens in Text : " + str(num_tokens))
|
90 |
+
print("Estimated Minimum Cost of Translation : " + str(min_cost))
|
91 |
+
print("Number of Characters in Text : " + str(num_characters) + "\n")
|
92 |
+
|
93 |
+
Toolkit.pause_console()
|
94 |
+
|
95 |
+
##-------------------start-of-sub_main()---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
96 |
+
|
97 |
+
client = TokenCounter()
|
98 |
+
|
99 |
+
## checks sys arguments and if less than 2 or called outside cmd prints usage statement
|
100 |
+
if(__name__ == '__main__'):
|
101 |
+
|
102 |
+
if(len(sys.argv) < 2):
|
103 |
+
|
104 |
+
print(f'\nUsage: {sys.argv[0]} input_txt_file\n')
|
105 |
+
|
106 |
+
Toolkit.pause_console()
|
107 |
+
exit()
|
108 |
+
|
109 |
+
Toolkit.clear_console()
|
110 |
+
|
111 |
+
client.estimate_cost(sys.argv[1])
|