-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
398 lines (345 loc) · 13.4 KB
/
Copy pathmodel.py
File metadata and controls
398 lines (345 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# model.py
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional
import json
import logging
import os
import uuid
SECTION_CHOICES = [
"None",
"Intro",
"Verse",
"Chorus",
"Bridge",
"Pre-Chorus",
"Hook",
"Refrain",
"Break",
"Drop",
"Outro",
]
INSTRUMENTAL_SECTIONS: List[str] = [
"Post-Chorus",
"Break",
"Breakdown",
"Instrumental Break",
"Build",
"Build-up",
"Drop",
"Interlude",
"Transition",
]
BlockKind = Literal["lyrics", "instrumental"]
__all__ = [
"SECTION_CHOICES",
"INSTRUMENTAL_SECTIONS",
"BlockKind",
"InstructionTemplate",
"Block",
"Project",
"create_lyrics_block",
"create_instrumental_block",
"load_project",
"save_project",
"load_autosave",
"save_autosave",
"get_autosave_path",
"register_instruction_template",
"remove_instruction_template",
"list_instruction_templates",
]
_LOGGER = logging.getLogger(__name__)
CUSTOM_SUBDIR = "custom"
CUSTOM_INSTRUCTION_FILENAME = "instructions.json"
CUSTOM_INSTRUCTION_VERSION = 1
_TEMPLATE_CACHE_LOADED = False
_TEMPLATE_CACHE: List["InstructionTemplate"] = []
@dataclass
class InstructionTemplate:
command: str
description: str = ""
section: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
payload: Dict[str, Any] = {"command": self.command}
if self.description:
payload["description"] = self.description
if self.section:
payload["section"] = self.section
return payload
@staticmethod
def from_dict(data: Dict[str, Any]) -> Optional["InstructionTemplate"]:
command_raw = data.get("command") or data.get("command_raw")
command = str(command_raw).strip() if command_raw is not None else ""
if not command:
return None
description_raw = data.get("description")
description = str(description_raw) if description_raw is not None else ""
section_raw = data.get("section")
section = str(section_raw).strip() if isinstance(section_raw, str) else None
if section in ("", "None"):
section = None
return InstructionTemplate(command=command, description=description, section=section)
def _user_data_root(create_dirs: bool = False) -> Path:
# Используем директорию проекта вместо системной AppData, чтобы избежать проблем с правами доступа
target = Path(__file__).parent / "user_data"
if create_dirs:
target.mkdir(parents=True, exist_ok=True)
return target
def _custom_instruction_path(create_dirs: bool = False) -> Path:
base_dir = _user_data_root(create_dirs=create_dirs)
custom_dir = base_dir / CUSTOM_SUBDIR
if create_dirs:
custom_dir.mkdir(parents=True, exist_ok=True)
return custom_dir / CUSTOM_INSTRUCTION_FILENAME
def _load_instruction_templates() -> None:
global _TEMPLATE_CACHE_LOADED, _TEMPLATE_CACHE
if _TEMPLATE_CACHE_LOADED:
return
path = _custom_instruction_path(create_dirs=False)
templates: List[InstructionTemplate] = []
if path.exists():
try:
with path.open("r", encoding="utf-8") as handle:
payload = json.load(handle)
if isinstance(payload, dict):
items = payload.get("instructions", [])
elif isinstance(payload, list):
items = payload
else:
items = []
for item in items:
if not isinstance(item, dict):
continue
template = InstructionTemplate.from_dict(item)
if template is not None:
templates.append(template)
except Exception as exc: # noqa: BLE001
_LOGGER.warning("Failed to load instruction templates from %s: %s", path, exc)
_TEMPLATE_CACHE = templates
_TEMPLATE_CACHE_LOADED = True
def _write_instruction_templates() -> None:
if not _TEMPLATE_CACHE_LOADED:
return
path = _custom_instruction_path(create_dirs=True)
payload: Dict[str, Any] = {
"version": CUSTOM_INSTRUCTION_VERSION,
"instructions": [template.to_dict() for template in _TEMPLATE_CACHE],
}
try:
with path.open("w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False, indent=2)
except Exception as exc: # noqa: BLE001
_LOGGER.error("Failed to write instruction templates to %s: %s", path, exc)
def register_instruction_template(command: str, description: str, section: Optional[str]) -> None:
normalized_command = command.strip()
if not normalized_command:
return
normalized_description = description.strip()
normalized_section = section.strip() if isinstance(section, str) and section.strip() else None
_load_instruction_templates()
for template in _TEMPLATE_CACHE:
if (
template.command == normalized_command
and template.description == normalized_description
and template.section == normalized_section
):
return
_TEMPLATE_CACHE.append(
InstructionTemplate(
command=normalized_command,
description=normalized_description,
section=normalized_section,
)
)
_write_instruction_templates()
def remove_instruction_template(command: str, description: str, section: Optional[str]) -> bool:
normalized_command = command.strip()
if not normalized_command:
return False
normalized_description = description.strip()
normalized_section = section.strip() if isinstance(section, str) and section.strip() else None
_load_instruction_templates()
for index, template in enumerate(_TEMPLATE_CACHE):
if (
template.command == normalized_command
and template.description == normalized_description
and template.section == normalized_section
):
del _TEMPLATE_CACHE[index]
_write_instruction_templates()
return True
return False
def list_instruction_templates(section: Optional[str] = None) -> List[InstructionTemplate]:
_load_instruction_templates()
if section is None:
return list(_TEMPLATE_CACHE)
normalized_section = section.strip() if isinstance(section, str) and section.strip() else None
return [template for template in _TEMPLATE_CACHE if template.section == normalized_section]
def new_block_id() -> str:
return str(uuid.uuid4())
@dataclass
class Block:
id: str = field(default_factory=new_block_id)
kind: BlockKind = "lyrics"
section: Optional[str] = None
instrumental_type: Optional[str] = None
lines: List[str] = field(default_factory=list)
instruction_command: str = ""
instruction_description: str = ""
_legacy_instruction_id: Optional[str] = field(default=None, repr=False, compare=False)
def __post_init__(self) -> None:
if self.kind == "instrumental":
self.section = None
if not self.lines:
self.lines = [""]
else:
self.lines = [str(self.lines[0])]
if self.instrumental_type not in INSTRUMENTAL_SECTIONS:
self.instrumental_type = INSTRUMENTAL_SECTIONS[0]
self.instruction_command = ""
self.instruction_description = ""
else:
if self.instrumental_type is not None:
self.instrumental_type = None
if not self.lines:
self.lines = [""] * 4
else:
self.lines = [str(x) for x in self.lines]
if self.section not in SECTION_CHOICES:
self.section = None
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"kind": self.kind,
"section": self.section,
"instrumental_type": self.instrumental_type,
"lines": list(self.lines),
"instruction_command": self.instruction_command,
"instruction_description": self.instruction_description,
}
@staticmethod
def from_dict(data: Dict[str, Any]) -> "Block":
kind = str(data.get("kind", "lyrics") or "lyrics")
if kind not in ("lyrics", "instrumental"):
kind = "lyrics"
lines_data = data.get("lines")
if not isinstance(lines_data, list):
lines_data = []
return Block(
id=str(data.get("id") or new_block_id()),
kind=kind,
section=data.get("section"),
instrumental_type=data.get("instrumental_type"),
lines=list(lines_data),
instruction_command=str(data.get("instruction_command", "")),
instruction_description=str(data.get("instruction_description", "")),
_legacy_instruction_id=str(data.get("instruction_id") or "") or None,
)
def create_lyrics_block(section: Optional[str] = None, line_count: int = 4) -> Block:
count = max(1, int(line_count))
return Block(kind="lyrics", section=section, lines=[""] * count)
def create_instrumental_block(instrumental_type: Optional[str] = None) -> Block:
if instrumental_type not in INSTRUMENTAL_SECTIONS:
instrumental_type = INSTRUMENTAL_SECTIONS[0]
return Block(kind="instrumental", instrumental_type=instrumental_type, lines=[""])
@dataclass
class Project:
version: int = 4
target: int = 16
tol: int = 2
lang: str = "en"
blocks: List[Block] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
return {
"version": self.version,
"target": int(self.target),
"tol": int(self.tol),
"lang": str(self.lang),
"blocks": [block.to_dict() for block in self.blocks],
}
@staticmethod
def from_dict(data: Dict[str, Any]) -> "Project":
blocks = [Block.from_dict(item) for item in data.get("blocks", []) if isinstance(item, dict)]
project = Project()
project.version = int(data.get("version", 4) or 4)
project.target = int(data.get("target", 16) or 16)
project.tol = int(data.get("tol", 2) or 2)
project.lang = str(data.get("lang", "en") or "en")
project.blocks = blocks if blocks else [create_lyrics_block("Verse")]
project._apply_legacy_instructions(data)
return project
def _apply_legacy_instructions(self, raw_data: Dict[str, Any]) -> None:
raw_map = raw_data.get("instructions")
if not isinstance(raw_map, dict):
for block in self.blocks:
block._legacy_instruction_id = None
return
lookup: Dict[str, Dict[str, Any]] = {}
for items in raw_map.values():
if not isinstance(items, list):
continue
for item in items:
if not isinstance(item, dict):
continue
entry_id = str(item.get("id") or "")
if entry_id:
lookup[entry_id] = item
for block in self.blocks:
legacy_id = block._legacy_instruction_id
if not legacy_id:
continue
entry = lookup.get(legacy_id)
if entry is None:
block._legacy_instruction_id = None
continue
block.instruction_command = str(entry.get("command", ""))
description = entry.get("description")
if isinstance(description, str) and description:
block.instruction_description = description
else:
descriptions = entry.get("descriptions")
if isinstance(descriptions, dict) and descriptions:
block.instruction_description = str(next(iter(descriptions.values())))
block._legacy_instruction_id = None
def register_instruction_template(self, command: str, description: str, section: Optional[str]) -> None:
register_instruction_template(command, description, section)
def remove_instruction_template(self, command: str, description: str, section: Optional[str]) -> bool:
return remove_instruction_template(command, description, section)
@staticmethod
def new_default() -> "Project":
return Project(
version=4,
target=16,
tol=2,
lang="en",
blocks=[create_lyrics_block("Verse")],
)
def load_project(path: str) -> Project:
"""Load project from file (delegates to storage strategy)."""
from storage import detect_storage
storage = detect_storage(path)
return storage.load(path)
def get_autosave_path() -> Path:
return _user_data_root(create_dirs=True) / "autosave.rapnote"
def save_autosave(project: Project) -> None:
autosave_path = get_autosave_path()
try:
save_project(project, str(autosave_path))
except Exception as e:
_LOGGER.error("Failed to save autosave: %s", e)
def load_autosave() -> Optional[Project]:
autosave_path = get_autosave_path()
if not autosave_path.exists():
return None
try:
return load_project(str(autosave_path))
except Exception as e:
_LOGGER.error("Failed to load autosave: %s", e)
return None
def save_project(project: Project, path: str) -> None:
"""Save project to file (delegates to storage strategy)."""
from storage import detect_storage
storage = detect_storage(path)
storage.save(project, path)