-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabases.py
199 lines (160 loc) · 6.19 KB
/
databases.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
from __future__ import annotations
import json
import os
from pydantic import BaseModel
from logic import XNWPProfile
class Dataset(BaseModel):
"""Представляет набор данных, предоставляемых для генераторов"""
name: str
"""Внутреннее имя набора данных"""
description: str
"""Текстовое описание набора данных"""
content: list[str]
"""Содержимое набора данных"""
class Datalist(BaseModel):
"""Представляет файл, содержащий множество именованных наборов данных"""
filename: str
"""Имя файла"""
name: str
"""Имя списка данных"""
description: str
"""Описание списка данных"""
datasets: list[Dataset]
"""Наборы данных"""
class Database(BaseModel):
"""Представляет сериализуемый набор файлов как базу данных"""
files: list[Datalist]
"""Список файлов"""
def save(self, directory: str) -> None:
if not os.path.exists(directory):
os.makedirs(directory)
for file in self.files:
with open(
os.path.join(directory, file.filename), "w+", encoding="utf_8"
) as write_file:
json.dump(
file.dict(),
write_file,
sort_keys=True,
indent=4,
ensure_ascii=False,
)
@staticmethod
def get_files(path: str) -> list[str]:
from os import listdir
from os.path import isfile, join
return [f for f in listdir(path) if isfile(join(path, f))]
@staticmethod
def load(path: str) -> Database:
files: list[Datalist] = []
if not os.path.exists(path):
return Database(files=files)
for file in Database.get_files(path):
with open(os.path.join(path, file), "r", encoding="utf_8") as read_file:
files.append(Datalist.parse_obj(json.load(read_file)))
return Database(files=files)
default_dbfiles: Database
user_dbfiles: Database
user_profiles: dict[str, XNWPProfile]
last_profile: str
def create() -> None:
global default_dbfiles
global user_dbfiles
default_dbfiles = Database(
files=[
Datalist(
filename="names.json",
name="Имена",
description="Содержит наборы данных с именами",
datasets=[
Dataset(
name="rus_male_names",
description="Русские имена (мужские)",
content=["Александр", "Алексей", "Артём", "Андрей", "Борис"],
)
],
)
]
)
user_dbfiles = Database(files=[])
def get_all_datalists() -> list[Datalist]:
"""Скомпоновывает базы данных по умолчанию и пользовательские
в единый комплекс данных.
"""
global default_dbfiles
global user_dbfiles
ret: list[Datalist] = []
ret.extend(default_dbfiles.files)
ret.extend(user_dbfiles.files)
return ret
def save() -> None:
from kivy import platform
if platform == "android":
pass
elif platform == "win":
default_dbfiles.save(os.path.join("bin", "defaultdb"))
user_dbfiles.save(os.path.join("bin", "userdb"))
def load_profiles(path: str) -> dict[str, XNWPProfile]:
dct: dict[str, XNWPProfile] = {}
for file in Database.get_files(path):
dct[os.path.basename(file)] = XNWPProfile.loadfile(file)
return dct
def load() -> None:
from kivy import platform
global default_dbfiles
global user_dbfiles
global user_profiles
if platform == "android":
user_dbfiles = Database(files=[])
default_dbfiles = Database.load(os.path.join("bin", "defaultdb"))
if os.path.exists(os.path.join("bin", "profiles")):
user_profiles = load_profiles(os.path.join("bin", "profiles"))
else:
user_profiles = {
"last.json": XNWPProfile(
notes=[], persons=[], sample_persons=[], sample_properties=[]
)
}
# from android.storage import primary_external_storage_path
# эту часть кода получится написать только на линуксе. увы
elif platform == "win" or platform == "linux":
default_dbfiles = Database.load(os.path.join("bin", "defaultdb"))
user_dbfiles = Database.load(os.path.join("bin", "userdb"))
if os.path.exists(os.path.join("bin", "profiles")):
user_profiles = load_profiles(os.path.join("bin", "profiles"))
else:
user_profiles = {
"last.json": XNWPProfile(
notes=[], persons=[], sample_persons=[], sample_properties=[]
)
}
def get_content_by_name_at(db_name: str, db: Database) -> list[str]:
for file in db.files:
for data in file.datasets:
if data.name == db_name:
return data.content
return []
def get_content_by_name(db_name: str) -> list[str]:
global default_dbfiles
global user_dbfiles
default = get_content_by_name_at(db_name, default_dbfiles)
user = get_content_by_name_at(db_name, user_dbfiles)
if len(user) != 0:
return user
elif len(default) != 0:
return default
else:
return ["Data not found"]
def add_list_in_default(
filename: str, name: str, description: str, content: list[str]
) -> None:
for file in default_dbfiles.files:
if file == filename:
exist: Dataset | None = next(
(ds for ds in file.datasets if ds.name == name), None
)
if exist is not None:
file.datasets.remove(exist)
file.datasets.append(
Dataset(name=name, description=description, content=content)
)