settingsclass 0.1.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- settingsclass/__init__.py +21 -0
- settingsclass/loc/settings.csv +36 -0
- settingsclass/localizer.py +216 -0
- settingsclass/settingsclass.py +1012 -0
- settingsclass-0.1.4.dist-info/LICENSE +21 -0
- settingsclass-0.1.4.dist-info/METADATA +539 -0
- settingsclass-0.1.4.dist-info/RECORD +9 -0
- settingsclass-0.1.4.dist-info/WHEEL +5 -0
- settingsclass-0.1.4.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from settingsclass.settingsclass import (
|
|
2
|
+
settingsclass,
|
|
3
|
+
RandomString,
|
|
4
|
+
RandomFloat,
|
|
5
|
+
RandomInt,
|
|
6
|
+
Encrypted,
|
|
7
|
+
Hidden,
|
|
8
|
+
available_languages,
|
|
9
|
+
set_language,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"settingsclass",
|
|
14
|
+
"RandomString",
|
|
15
|
+
"RandomInt",
|
|
16
|
+
"RandomFloat",
|
|
17
|
+
"Encrypted",
|
|
18
|
+
"Hidden",
|
|
19
|
+
"available_languages",
|
|
20
|
+
"set_language",
|
|
21
|
+
]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
id,ja,en
|
|
2
|
+
|
|
3
|
+
#ログメッセージ/logging messages
|
|
4
|
+
initing_settings_1,"設定ファイルが存在しないため、以下ファイルで初期化します。:{}","Settings file not found. Creating a config file with default values to {}"
|
|
5
|
+
loading_settings_from_1,"以下のファイルから設定を読み込みます。:{}","Loading settings from {}"
|
|
6
|
+
using_key_var_from_env_1,"以下の環境変数を適用します。:{}","The following environmental variable will be applied: {}"
|
|
7
|
+
unencrypted_data_found_1,"暗号化されていないデータ({})が見つかりました。ファイルを暗号化して上書きします。","Unencrypted data found ({}). Encrypting and overwriting the current file."
|
|
8
|
+
|
|
9
|
+
#エラーメッセージ/error messages
|
|
10
|
+
|
|
11
|
+
file_is_folder_1,"指定されたパスはファイルを指すことが期待されていましたが、フォルダを指しています。:{}。","The path was expected to point to a file, but points to a folder. Path: {}"
|
|
12
|
+
invalid_type_4,"【{0}】セクションのパラメータ【{1}】に対して、【{3}】をタイプ{2}に変換できませんでした。","Could not convert '{3}' to type {2} for parameter <{1}> in section <{0}>"
|
|
13
|
+
missing_config_section_1,"セクション【{}】が見つかりませんでした。","The config file is missing section <{}>"
|
|
14
|
+
config_param_missing_2,"セクションのパラメータ【{0}】に【{1}】が見つかりませんでした。","Config file is missing parameter <{1}> in section <{0}>"
|
|
15
|
+
extra_config_sections_1,"設定ファイルに予期しないセクションは使用できません。:{}","The following sections are not in the definition and will be ignored: {}"
|
|
16
|
+
extra_config_parameter_2,"設定ファイルの【{0}】セクションに予期されていない【{1}】のパラメーターが見つかりました。","Unexpected parameter {1} found in section {0} of the settings file"
|
|
17
|
+
param_type_is_string_but_looks_x_4,"設定ファイルの【{}】セクション【{}】の【{}】値を設定されているパラメーターは文字列ですが、{}に見えます。","The parameter <{}> in section <{}> with value {} of the settings file is a string but looks like a {}"
|
|
18
|
+
cannot_convert_to_bool_1,"【{}】の値をbooleanに変換できませんでした。","Could not convert the value of <{}> to a boolean."
|
|
19
|
+
unexpected_class_found_2,"予期されない型が見つかりました。:{}{}。GenericAliasを継承するクラスは_RandomTypeまたは_TypeWrapperも継承する必要があります。","Unexpected type found in: {}/{}. Classes inheriting GenericAlias should also inherit _RandomType or _TypeWrapper."
|
|
20
|
+
invalid_encryption_key_type_1,"暗号化キーの型が不正です:{}。使用可能なタイプは【None】・【str】・【tuple[Callable]】。Tupleの場合は【暗号化関数、複合化関数】の順番が必用","{} has been provided but only types str, None and tuple[Callable] can be used as encryption keys. In case of tuple, the first callable should handle encryption, with the second handling decrpytion"
|
|
21
|
+
could_not_decode_string_1,"ファイルのデコードに失敗しました。ファイルが壊れている可能性があります:{}","Failed to decode the file. The file may be corrupted: {}"
|
|
22
|
+
function_can_only_be_called_on_randomtype_1,"この関数は_RandomTypeのみで呼び出すことができます:{}","This function can only be called on _RandomType: {}"
|
|
23
|
+
keyfile_location_unaccessible_1,"キーファイルの場所にアクセスできません。代わりに文字列または呼び出し可能なキーで指定してください:{}","The keyfile location is unaccessable. Please provide a string or callable key instead: {}"
|
|
24
|
+
no_initial_value_3,"クラス{}.{}の<{}>の値は見つかりませんでした。ランダムの変数の場合でもプレースホルダーの値は必用です。","Missing value for variable <{2}> inside {0}.{1}. All keys need to be initialized, even random properties require a placeholder."
|
|
25
|
+
parameter_type_missing_1,"{}のパラメーターのタイプが見つかりません。デフォルト値から設定します。iniファイルのパラメータ順が守れない可能性があります。","Parameter type hint for {} was not found. Parameters without explicit type are not fully supported. The type will be inferred based on the default value. The parameter will be placed at the end in the config file"
|
|
26
|
+
|
|
27
|
+
#UT
|
|
28
|
+
##設定モジュール/Settings module
|
|
29
|
+
lower_third_not_reached,"RandomSettingTypeの設定生成のユニットテスト中に、下位の1割の値が生成されませんでした。","The lower third values have not been generated during the unit test of RandomType for setting generation"
|
|
30
|
+
higher_third_not_reached,"RandomSettingTypeの設定生成のユニットテスト中に、上位の1割の値が生成されませんでした。","The higher third values have not been generated during the unit test of RandomType for setting generation"
|
|
31
|
+
|
|
32
|
+
##翻訳モジュール/Translation module
|
|
33
|
+
param_count_mismatch_2,"パラメータの数がキーの期待値と一致しません。 ({}の{}行目から呼び出されました)","The number of parameters does not match the number at the end of the key (called from {} line {})"
|
|
34
|
+
pos_and_non_pos_brackets_mixed_2,"位置指定と非位置指定のブラケットが混在しています。 (<{}>キー値:{})","Positional and non-positional brackets are mixed. (key <{}> has value <{}>)"
|
|
35
|
+
translation_key_does_not_exist_3,"翻訳キーの「{}」が存在しません。箇所:{}の{}行目","The translation key '{}' does not exist in file {} line {}"
|
|
36
|
+
unused_key_found_1,"未使用の翻訳キーが見つかりました。:{}","Unused translation key found: {}"
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Created on Fri Apr 8 10:50:50 2022
|
|
4
|
+
|
|
5
|
+
@author: uid7067
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
# 翻訳に関する関数
|
|
9
|
+
from os import listdir
|
|
10
|
+
from os.path import join, exists, isdir, splitext, dirname
|
|
11
|
+
from collections import OrderedDict
|
|
12
|
+
import csv
|
|
13
|
+
import warnings
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
DEFAULT_EXTENSIONS = ["csv"]
|
|
17
|
+
DEFAULT_FOLDER = join(dirname(__file__), "loc")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _has_parameters(key):
|
|
21
|
+
"""翻訳キーがパラメータを望むかどうか"""
|
|
22
|
+
return key[-2] in ("_", "_") and key[-1].isdigit()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# 早い入力のためC0103(関数名が短い)をこの関数に未効果する
|
|
26
|
+
def tr(key: str, *params) -> str: # pylint: disable=C0103
|
|
27
|
+
"""ストリングを翻訳し、パラメーターを入れる。
|
|
28
|
+
フォーマットは<要約>_<任意:引数数>。
|
|
29
|
+
例:tr('webpage_title')
|
|
30
|
+
例:tr(invalid_path_1, '/usr/xyz')
|
|
31
|
+
例:tr(bad_request_3, request_type, request_id, request_content)
|
|
32
|
+
|
|
33
|
+
キーが存在しない場合はそのまま使用する。引数の数を指定する場合は自動で追加される
|
|
34
|
+
例:tr('does_not_exits_3',x,y,z) => 'does_not_exist_{}_{}_{}'
|
|
35
|
+
|
|
36
|
+
パラメーター数が一致していない場合はできる範囲で入れる:
|
|
37
|
+
例:tr('triplet_conf_invalid_3, 135) => 'Triplet configuration invalid: 135 - {} - {}'
|
|
38
|
+
例:tr('invalid_path_1', 'usr/loc', 'Username') => 'Invalid path supplied <usr/loc>'
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
key (str): loc.csvの文字列ID。
|
|
42
|
+
params: keyに差し替えるパラメータ
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
str: 翻訳された文字列
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
formatted_string = ""
|
|
49
|
+
|
|
50
|
+
# tr.active_words:現在の言語の{id: 翻訳された文字列}の辞書
|
|
51
|
+
if key in tr.active_words:
|
|
52
|
+
entry = tr.active_words[key]
|
|
53
|
+
else:
|
|
54
|
+
# 入っていない場合は[_count]の程の{}を追加する
|
|
55
|
+
# _は半角でも全角でもOK
|
|
56
|
+
if _has_parameters(key):
|
|
57
|
+
entry = key[:-1] + "_".join(["{}"] * int(key[-1]))
|
|
58
|
+
else:
|
|
59
|
+
entry = key
|
|
60
|
+
|
|
61
|
+
entry = entry.replace("\\n", "\n")
|
|
62
|
+
if not _has_parameters(key):
|
|
63
|
+
return entry
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
formatted_string = entry.format(*params)
|
|
67
|
+
except IndexError:
|
|
68
|
+
# 引数の数が一致していない場合は発生する
|
|
69
|
+
param_list = list(params)
|
|
70
|
+
# 「{{」等でエスケープされたとしても上限は【{】の数です
|
|
71
|
+
# 多すぎるの場合はエラーが発生しない
|
|
72
|
+
bracket_count = entry.count("{")
|
|
73
|
+
param_list += ["{}"] * (bracket_count - len(param_list))
|
|
74
|
+
formatted_string = entry.format(*param_list)
|
|
75
|
+
except ValueError:
|
|
76
|
+
# 団体テストを実行しなった場合の安全装置
|
|
77
|
+
# 例:value=="{1}の{0}=={}"
|
|
78
|
+
formatted_string = re.sub(r"\{\d+\}", "{}", entry)
|
|
79
|
+
formatted_string = formatted_string.format(*params)
|
|
80
|
+
|
|
81
|
+
return formatted_string
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def current_language() -> str:
|
|
85
|
+
"""現在の言語コードを返す"""
|
|
86
|
+
try:
|
|
87
|
+
return tr.current_lang
|
|
88
|
+
except AttributeError:
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def set_language(language: str) -> None:
|
|
93
|
+
"""言語を設定する。プロパティが精定期であるため、実行は初期化と言語変更のときのみ必要。
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
language (str): 国際化ファイルにある言語のコード("ja", "en"等)
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
AttributeError: _description_
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
# "ja" == "JA" == "Ja"
|
|
103
|
+
language = language.lower()
|
|
104
|
+
if language in tr.words:
|
|
105
|
+
tr.active_words = tr.words[language]
|
|
106
|
+
tr.current_lang = language
|
|
107
|
+
else:
|
|
108
|
+
raise AttributeError(
|
|
109
|
+
"指定された言語は存在しません。Requested language does not exist: "
|
|
110
|
+
+ f"{language} (可能/available: {'・'.join(list(tr.words.keys()))})"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _listup_files(
|
|
115
|
+
folder: str = DEFAULT_FOLDER, extensions: list[str] = None, recursive: bool = False
|
|
116
|
+
) -> list[str]:
|
|
117
|
+
"""
|
|
118
|
+
フォルダーのすべてのファイルをリストアップする。(utils.pyにもありますが循環参照回避のため自作)
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
folder (str): 対象フォルダー
|
|
122
|
+
extensions (list[str]): 拡張子のリスト。
|
|
123
|
+
Noneの場合はすべてのファイル対象
|
|
124
|
+
例:画像の場合['png','jpg','bmp']
|
|
125
|
+
例:Pythonファイルの場合:['py']
|
|
126
|
+
recursive (bool, optional): 大気的有無. Defaults to False.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
list[str]:ファイルパスのリスト
|
|
130
|
+
"""
|
|
131
|
+
if extensions is None:
|
|
132
|
+
extensions = DEFAULT_EXTENSIONS
|
|
133
|
+
if extensions:
|
|
134
|
+
extensions = [e.lower() for e in extensions]
|
|
135
|
+
files = listdir(folder)
|
|
136
|
+
collected_files = []
|
|
137
|
+
|
|
138
|
+
for fname in files:
|
|
139
|
+
_, ext = splitext(fname)
|
|
140
|
+
full_path = join(folder, fname)
|
|
141
|
+
ext = ext[1:]
|
|
142
|
+
if extensions is None or ext.lower() in extensions:
|
|
143
|
+
collected_files.append(full_path)
|
|
144
|
+
|
|
145
|
+
if recursive and isdir(join(folder, fname)):
|
|
146
|
+
collected_files += _listup_files(join(folder, fname), extensions, True)
|
|
147
|
+
return collected_files
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _load_translations(langfile_directory: list[str] = None):
|
|
151
|
+
if langfile_directory is None:
|
|
152
|
+
langfile_directory = _listup_files()
|
|
153
|
+
words = OrderedDict()
|
|
154
|
+
langs = []
|
|
155
|
+
for langfile_path in langfile_directory:
|
|
156
|
+
with open(langfile_path, encoding="utf-8") as lang_file:
|
|
157
|
+
lang_reader = csv.reader(lang_file, delimiter=",", quotechar='"')
|
|
158
|
+
for row in lang_reader:
|
|
159
|
+
if row and not (
|
|
160
|
+
len(row) >= 1 and len(row[0]) >= 1 and row[0][0] in ("#", "#")
|
|
161
|
+
):
|
|
162
|
+
# 最初の行は言語の定義
|
|
163
|
+
if not words:
|
|
164
|
+
assert (
|
|
165
|
+
len(row) > 1
|
|
166
|
+
), "翻訳ファイルに1つの言語も入っていません。Language file must have at least 1 language in it"
|
|
167
|
+
# "ja" == "JA" == "Ja"
|
|
168
|
+
langs = [lang.lower() for lang in row[1:]]
|
|
169
|
+
for lang in langs:
|
|
170
|
+
words[lang] = {}
|
|
171
|
+
else:
|
|
172
|
+
# 「,」等の数がずれたら全翻訳ファイルが読めなくなるかもしれせんのでこれがエラーとする
|
|
173
|
+
assert len(row) - 1 == len(langs), (
|
|
174
|
+
"言語と文書の数は一致していません。Number of languages and entries does not match for entry: "
|
|
175
|
+
+ f"{len(langs)}/{len(row)-1}:key={row[0]} in file {langfile_path}"
|
|
176
|
+
)
|
|
177
|
+
key = row[0]
|
|
178
|
+
for lang_id, entry in enumerate(row[1:]):
|
|
179
|
+
## 1行目の言語設定が重複するのでスキップする
|
|
180
|
+
if key != "id":
|
|
181
|
+
lang = langs[lang_id]
|
|
182
|
+
if key in words[lang]:
|
|
183
|
+
warnings.warn(
|
|
184
|
+
f"キーの重複を発見しました。Duplicate key found: {key}",
|
|
185
|
+
UserWarning,
|
|
186
|
+
)
|
|
187
|
+
words[lang][key] = entry
|
|
188
|
+
return words, langs
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def refresh_contents(file_path: list[str] = None):
|
|
192
|
+
"""格納されたファイルから内容を読み込む。インポートの時に一回実行される"""
|
|
193
|
+
## 指定がない場合はlocフォルダの.csvをすべて読み込む
|
|
194
|
+
if file_path is None:
|
|
195
|
+
file_path = _listup_files()
|
|
196
|
+
## 指定があった場合は指定のファイルを読み込む
|
|
197
|
+
## listで扱うのでlist担っていない場合は変換する。
|
|
198
|
+
if not isinstance(file_path, list):
|
|
199
|
+
file_path = [file_path]
|
|
200
|
+
# ディレクトリのファイルチェック
|
|
201
|
+
for langfile_path in file_path:
|
|
202
|
+
assert exists(
|
|
203
|
+
langfile_path
|
|
204
|
+
), f"翻訳ファイルは指定されたパスに存在しません。Localization not found at {langfile_path}"
|
|
205
|
+
tr.words, langs = _load_translations(file_path)
|
|
206
|
+
|
|
207
|
+
# 最初の言語はデフォルトとする
|
|
208
|
+
try:
|
|
209
|
+
selected_language = tr.current_lang
|
|
210
|
+
except AttributeError:
|
|
211
|
+
selected_language = langs[-1]
|
|
212
|
+
tr.current_lang = selected_language
|
|
213
|
+
set_language(selected_language)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
refresh_contents()
|