light-ass 0.1.0__tar.gz
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.
- light_ass-0.1.0/LICENSE +21 -0
- light_ass-0.1.0/PKG-INFO +51 -0
- light_ass-0.1.0/README.md +31 -0
- light_ass-0.1.0/light_ass/__init__.py +8 -0
- light_ass-0.1.0/light_ass/constants.py +24 -0
- light_ass-0.1.0/light_ass/events.py +127 -0
- light_ass-0.1.0/light_ass/script_info.py +97 -0
- light_ass-0.1.0/light_ass/styles.py +191 -0
- light_ass-0.1.0/light_ass/subtitle.py +215 -0
- light_ass-0.1.0/light_ass/tag_parser.py +413 -0
- light_ass-0.1.0/light_ass/utils.py +139 -0
- light_ass-0.1.0/light_ass.egg-info/PKG-INFO +51 -0
- light_ass-0.1.0/light_ass.egg-info/SOURCES.txt +18 -0
- light_ass-0.1.0/light_ass.egg-info/dependency_links.txt +1 -0
- light_ass-0.1.0/light_ass.egg-info/top_level.txt +1 -0
- light_ass-0.1.0/pyproject.toml +31 -0
- light_ass-0.1.0/setup.cfg +4 -0
- light_ass-0.1.0/tests/test_parser.py +26 -0
- light_ass-0.1.0/tests/test_tag_parser.py +50 -0
- light_ass-0.1.0/tests/test_utils.py +56 -0
light_ass-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Ming
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
light_ass-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: light-ass
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight library for handling ASS subtitles
|
|
5
|
+
Author-email: Oborozuki <oborozuk1@qq.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
Project-URL: Homepage, https://github.com/oborozuk1/light-ass
|
|
8
|
+
Project-URL: Repository, https://github.com/oborozuk1/light-ass.git
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/oborozuk1/light-ass/issues
|
|
10
|
+
Keywords: subtitle,ass
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Multimedia :: Video
|
|
15
|
+
Classifier: Development Status :: 3 - Alpha
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Requires-Python: >=3.12
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
|
|
21
|
+
# light-ass
|
|
22
|
+
A lightweight library for handling Advanced SubStation Alpha (ASS) subtitles.
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
- Parse ASS subtitles effortlessly
|
|
26
|
+
- Check the validity of field types
|
|
27
|
+
- Parse ASS override tags (partial)
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
```
|
|
31
|
+
pip install light-ass
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
```python
|
|
36
|
+
import light_ass
|
|
37
|
+
|
|
38
|
+
document = light_ass.load("example.ass")
|
|
39
|
+
print(document.info)
|
|
40
|
+
print(document.styles)
|
|
41
|
+
print(document.events)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## TODO
|
|
45
|
+
- Support for more sections
|
|
46
|
+
- More methods for ASS shapes
|
|
47
|
+
- ASS minifier
|
|
48
|
+
- Support for VSFilterMod tags
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
MIT License
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# light-ass
|
|
2
|
+
A lightweight library for handling Advanced SubStation Alpha (ASS) subtitles.
|
|
3
|
+
|
|
4
|
+
## Features
|
|
5
|
+
- Parse ASS subtitles effortlessly
|
|
6
|
+
- Check the validity of field types
|
|
7
|
+
- Parse ASS override tags (partial)
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
```
|
|
11
|
+
pip install light-ass
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
```python
|
|
16
|
+
import light_ass
|
|
17
|
+
|
|
18
|
+
document = light_ass.load("example.ass")
|
|
19
|
+
print(document.info)
|
|
20
|
+
print(document.styles)
|
|
21
|
+
print(document.events)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## TODO
|
|
25
|
+
- Support for more sections
|
|
26
|
+
- More methods for ASS shapes
|
|
27
|
+
- ASS minifier
|
|
28
|
+
- Support for VSFilterMod tags
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
MIT License
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class AssSectionHeader:
|
|
5
|
+
SCRIPT_INFO = "Script Info"
|
|
6
|
+
ASS_STYLE = "V4+ Styles"
|
|
7
|
+
EVENTS = "Events"
|
|
8
|
+
# AEGISUB_PROJECT = "Aegisub Project Garbage"
|
|
9
|
+
# AEGISUB_EXTRADATA = "Aegisub Extradata"
|
|
10
|
+
# FONTS = "Fonts"
|
|
11
|
+
# GRAPHICS = "Graphics"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
DEFAULT_STYLES_FORMAT = (
|
|
15
|
+
"Name", "Fontname", "Fontsize", "PrimaryColour", "SecondaryColour", "OutlineColour", "BackColour",
|
|
16
|
+
"Bold", "Italic", "Underline", "StrikeOut", "ScaleX", "ScaleY", "Spacing", "Angle", "BorderStyle",
|
|
17
|
+
"Outline", "Shadow", "Alignment", "MarginL", "MarginR", "MarginV", "Encoding",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
DEFAULT_EVENTS_FORMAT = ("Layer", "Start", "End", "Style", "Name", "MarginL", "MarginR", "MarginV", "Effect", "Text")
|
|
21
|
+
|
|
22
|
+
SECTION_PATTERN = re.compile(r"^\s*\[([^]]+)]\s*")
|
|
23
|
+
|
|
24
|
+
OVERRIDE_BLOCK_PATTERN = re.compile(r"(?<!\\){([^}]*)}")
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
|
|
3
|
+
from .ass_types.ass_time import AssTime
|
|
4
|
+
from .constants import OVERRIDE_BLOCK_PATTERN
|
|
5
|
+
from .tag_parser import Tag, parse_tags
|
|
6
|
+
from .utils import validate_value
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Dialog(dict):
|
|
10
|
+
_formats = {
|
|
11
|
+
"comment": bool,
|
|
12
|
+
"layer": int,
|
|
13
|
+
"start": AssTime,
|
|
14
|
+
"end": AssTime,
|
|
15
|
+
"style": str,
|
|
16
|
+
"name": str,
|
|
17
|
+
"margin_l": int,
|
|
18
|
+
"margin_r": int,
|
|
19
|
+
"margin_v": int,
|
|
20
|
+
"effect": str,
|
|
21
|
+
"text": str,
|
|
22
|
+
}
|
|
23
|
+
_alias = {
|
|
24
|
+
"commented": "comment",
|
|
25
|
+
"start_time": "start",
|
|
26
|
+
"end_time": "end",
|
|
27
|
+
"actor": "name",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
comment: bool
|
|
31
|
+
layer: int
|
|
32
|
+
start: AssTime
|
|
33
|
+
end: AssTime
|
|
34
|
+
style: str
|
|
35
|
+
name: str
|
|
36
|
+
margin_l: int
|
|
37
|
+
margin_r: int
|
|
38
|
+
margin_v: int
|
|
39
|
+
effect: str
|
|
40
|
+
text: str
|
|
41
|
+
commented: bool
|
|
42
|
+
start_time: AssTime
|
|
43
|
+
end_time: AssTime
|
|
44
|
+
actor: str
|
|
45
|
+
|
|
46
|
+
def __init__(self, **kwargs) -> None:
|
|
47
|
+
if set(kwargs.keys()) != set(self._formats.keys()):
|
|
48
|
+
raise ValueError("Keys of kwargs must equal formats")
|
|
49
|
+
super().__init__()
|
|
50
|
+
for key, value in kwargs.items():
|
|
51
|
+
self[key] = self.validate_value(key, value)
|
|
52
|
+
|
|
53
|
+
def __getattr__(self, name: str):
|
|
54
|
+
if name in self._alias:
|
|
55
|
+
name = self._alias[name]
|
|
56
|
+
if name in self._formats:
|
|
57
|
+
return self[name]
|
|
58
|
+
else:
|
|
59
|
+
raise AttributeError(f"{name} is not a valid attribute")
|
|
60
|
+
|
|
61
|
+
def __setattr__(self, name: str, value):
|
|
62
|
+
if name in self._alias:
|
|
63
|
+
name = self._alias[name]
|
|
64
|
+
if name in self._formats:
|
|
65
|
+
self[name] = Dialog.validate_value(name, value)
|
|
66
|
+
else:
|
|
67
|
+
raise AttributeError(f"{name} is not a valid attribute")
|
|
68
|
+
|
|
69
|
+
def __repr__(self) -> str:
|
|
70
|
+
return "Dialog({})".format(
|
|
71
|
+
",".join(f"{key}={value}" for key, value in self.items())
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def __str__(self) -> str:
|
|
75
|
+
dialog_line = []
|
|
76
|
+
for key, value in self.items():
|
|
77
|
+
if key == "comment":
|
|
78
|
+
continue
|
|
79
|
+
if type(value) is float:
|
|
80
|
+
value = f"{value:g}"
|
|
81
|
+
dialog_line.append(str(value))
|
|
82
|
+
return "{}: {}".format("Comment" if self.comment else "Dialogue", ",".join(dialog_line))
|
|
83
|
+
|
|
84
|
+
def shift(self, ms: int) -> None:
|
|
85
|
+
self.start += ms
|
|
86
|
+
self.end += ms
|
|
87
|
+
|
|
88
|
+
def parse_tags(self) -> list[Tag]:
|
|
89
|
+
return parse_tags(self.text)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def text_stripped(self) -> str:
|
|
93
|
+
return OVERRIDE_BLOCK_PATTERN.sub("", self.text)
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def validate_value(key, value):
|
|
97
|
+
if key in Dialog._alias:
|
|
98
|
+
key = Dialog._alias[key]
|
|
99
|
+
try:
|
|
100
|
+
return validate_value(Dialog._formats[key], value)
|
|
101
|
+
except ValueError:
|
|
102
|
+
raise ValueError(f"Invalid value for {key}: {value}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class Events(list[Dialog]):
|
|
106
|
+
def pop(self, index: int | Sequence[int] = -1):
|
|
107
|
+
if isinstance(index, int):
|
|
108
|
+
index = (index,)
|
|
109
|
+
for i in sorted(index, reverse=True):
|
|
110
|
+
super().pop(i)
|
|
111
|
+
|
|
112
|
+
def shift(self, ms: int, range_: Sequence[int] | None = None):
|
|
113
|
+
"""
|
|
114
|
+
Shift the start and end time of events by milliseconds.
|
|
115
|
+
:param ms: The amount of milliseconds to shift the events by.
|
|
116
|
+
:param range_: The range of events to shift. If None, all events will be shifted.
|
|
117
|
+
:return: None
|
|
118
|
+
"""
|
|
119
|
+
if range_ is None:
|
|
120
|
+
range_ = range(0, len(self))
|
|
121
|
+
for i in range_:
|
|
122
|
+
self[i].shift(ms)
|
|
123
|
+
|
|
124
|
+
def sort(self, *, key = None, reverse = False):
|
|
125
|
+
if key is None:
|
|
126
|
+
key = lambda x: x.start
|
|
127
|
+
super().sort(key = key, reverse = reverse)
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
from typing import Any, Self, Literal
|
|
2
|
+
|
|
3
|
+
from .utils import validate_value
|
|
4
|
+
|
|
5
|
+
ScriptInfoKeys = Literal[
|
|
6
|
+
"Title",
|
|
7
|
+
"Original Script",
|
|
8
|
+
"Original Translation",
|
|
9
|
+
"Original Editing",
|
|
10
|
+
"Original Timing",
|
|
11
|
+
"Synch Point",
|
|
12
|
+
"Script Updated By",
|
|
13
|
+
"ScriptType",
|
|
14
|
+
"Update Details",
|
|
15
|
+
"PlayResX",
|
|
16
|
+
"PlayResY",
|
|
17
|
+
"PlayDepth",
|
|
18
|
+
"ScaledBorderAndShadow",
|
|
19
|
+
"WrapStyle",
|
|
20
|
+
"YCbCr Matrix",
|
|
21
|
+
"Collisions",
|
|
22
|
+
"Timer",
|
|
23
|
+
"LayoutResX",
|
|
24
|
+
"LayoutResY",
|
|
25
|
+
# libass extensions
|
|
26
|
+
"Kerning",
|
|
27
|
+
"Language",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ScriptInfo(dict):
|
|
32
|
+
_formats = {
|
|
33
|
+
"Title": str,
|
|
34
|
+
"Original Script": str,
|
|
35
|
+
"Original Translation": str,
|
|
36
|
+
"Original Editing": str,
|
|
37
|
+
"Original Timing": str,
|
|
38
|
+
"Synch Point": str,
|
|
39
|
+
"Script Updated By": str,
|
|
40
|
+
"ScriptType": str,
|
|
41
|
+
"Update Details": str,
|
|
42
|
+
"PlayResX": int,
|
|
43
|
+
"PlayResY": int,
|
|
44
|
+
"PlayDepth": int,
|
|
45
|
+
"ScaledBorderAndShadow": {"yes": True, "no": False},
|
|
46
|
+
"WrapStyle": (0, 1, 2, 3),
|
|
47
|
+
"YCbCr Matrix": ("None", "TV.601", "PC.601", "TV.709", "PC.709", "TV.FCC", "PC.FCC", "TV.240M", "PC.240M"),
|
|
48
|
+
"Collisions": ("Normal", "Reverse"),
|
|
49
|
+
"Timer": float,
|
|
50
|
+
"LayoutResX": int,
|
|
51
|
+
"LayoutResY": int,
|
|
52
|
+
# libass extensions
|
|
53
|
+
"Kerning": {"yes": True, "no": False},
|
|
54
|
+
"Language": str,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
def __init__(self, info: Self | dict[str, Any] | None = None):
|
|
58
|
+
super().__init__()
|
|
59
|
+
if isinstance(info, dict):
|
|
60
|
+
for key, value in info.items():
|
|
61
|
+
self[key] = value
|
|
62
|
+
|
|
63
|
+
def sort(self):
|
|
64
|
+
mapping = {key: i for i, key in enumerate(self._formats.keys())}
|
|
65
|
+
new = sorted(self.items(), key=lambda x: mapping.get(x[0], 99))
|
|
66
|
+
self.clear()
|
|
67
|
+
self.update(new)
|
|
68
|
+
|
|
69
|
+
def __getitem__(self, key: ScriptInfoKeys | str):
|
|
70
|
+
return super().__getitem__(key)
|
|
71
|
+
|
|
72
|
+
def __setitem__(self, key: ScriptInfoKeys | str, value):
|
|
73
|
+
if value is None:
|
|
74
|
+
self.pop(key)
|
|
75
|
+
else:
|
|
76
|
+
super().__setitem__(key, self.validate_value(key, value))
|
|
77
|
+
|
|
78
|
+
def __repr__(self) -> str:
|
|
79
|
+
return f"ScriptInfo({super().__repr__()})"
|
|
80
|
+
|
|
81
|
+
def __str__(self) -> str:
|
|
82
|
+
infos = []
|
|
83
|
+
for key, value in self.items():
|
|
84
|
+
if isinstance(self._formats[key], dict):
|
|
85
|
+
rev_dict = {v: k for k, v in self._formats[key].items()}
|
|
86
|
+
value = rev_dict[value]
|
|
87
|
+
infos.append(f"{key}: {value}")
|
|
88
|
+
return "\n".join(infos)
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def validate_value(key, value):
|
|
92
|
+
if key not in ScriptInfo._formats:
|
|
93
|
+
return value
|
|
94
|
+
try:
|
|
95
|
+
return validate_value(ScriptInfo._formats[key], value)
|
|
96
|
+
except ValueError:
|
|
97
|
+
raise ValueError(f"Invalid value for {key}: {value}")
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
from collections.abc import Iterable
|
|
2
|
+
from typing import Self, Literal
|
|
3
|
+
|
|
4
|
+
from .ass_types.ass_color import AssColor
|
|
5
|
+
from .utils import validate_value
|
|
6
|
+
|
|
7
|
+
StyleKeys = Literal[
|
|
8
|
+
"name",
|
|
9
|
+
"fontname",
|
|
10
|
+
"fontsize",
|
|
11
|
+
"primary_colour",
|
|
12
|
+
"secondary_colour",
|
|
13
|
+
"outline_colour",
|
|
14
|
+
"back_colour",
|
|
15
|
+
"bold",
|
|
16
|
+
"italic",
|
|
17
|
+
"underline",
|
|
18
|
+
"strike_out",
|
|
19
|
+
"scale_x",
|
|
20
|
+
"scale_y",
|
|
21
|
+
"spacing",
|
|
22
|
+
"angle",
|
|
23
|
+
"border_style",
|
|
24
|
+
"outline",
|
|
25
|
+
"shadow",
|
|
26
|
+
"alignment",
|
|
27
|
+
"margin_l",
|
|
28
|
+
"margin_r",
|
|
29
|
+
"margin_v",
|
|
30
|
+
"encoding",
|
|
31
|
+
"color1",
|
|
32
|
+
"color2",
|
|
33
|
+
"color3",
|
|
34
|
+
"color4",
|
|
35
|
+
"align",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Style(dict):
|
|
40
|
+
_formats = {
|
|
41
|
+
"name": str,
|
|
42
|
+
"fontname": str,
|
|
43
|
+
"fontsize": float,
|
|
44
|
+
"primary_colour": AssColor,
|
|
45
|
+
"secondary_colour": AssColor,
|
|
46
|
+
"outline_colour": AssColor,
|
|
47
|
+
"back_colour": AssColor,
|
|
48
|
+
"bold": {"0": False, "-1": True},
|
|
49
|
+
"italic": {"0": False, "-1": True},
|
|
50
|
+
"underline": {"0": False, "-1": True},
|
|
51
|
+
"strike_out": {"0": False, "-1": True},
|
|
52
|
+
"scale_x": float,
|
|
53
|
+
"scale_y": float,
|
|
54
|
+
"spacing": float,
|
|
55
|
+
"angle": float,
|
|
56
|
+
"border_style": (1, 3, 4), # 4 for libass
|
|
57
|
+
"outline": float,
|
|
58
|
+
"shadow": float,
|
|
59
|
+
"alignment": (1, 2, 3, 4, 5, 6, 7, 8, 9),
|
|
60
|
+
"margin_l": int,
|
|
61
|
+
"margin_r": int,
|
|
62
|
+
"margin_v": int,
|
|
63
|
+
"encoding": int,
|
|
64
|
+
}
|
|
65
|
+
_alias = {
|
|
66
|
+
"color1": "primary_colour",
|
|
67
|
+
"color2": "secondary_colour",
|
|
68
|
+
"color3": "outline_colour",
|
|
69
|
+
"color4": "back_colour",
|
|
70
|
+
"align": "alignment",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
name: str
|
|
74
|
+
fontname: str
|
|
75
|
+
fontsize: float
|
|
76
|
+
primary_colour: AssColor
|
|
77
|
+
secondary_colour: AssColor
|
|
78
|
+
outline_colour: AssColor
|
|
79
|
+
back_colour: AssColor
|
|
80
|
+
bold: bool
|
|
81
|
+
italic: bool
|
|
82
|
+
underline: bool
|
|
83
|
+
strike_out: bool
|
|
84
|
+
scale_x: float
|
|
85
|
+
scale_y: float
|
|
86
|
+
spacing: float
|
|
87
|
+
angle: float
|
|
88
|
+
border_style: int
|
|
89
|
+
outline: float
|
|
90
|
+
shadow: float
|
|
91
|
+
alignment: int
|
|
92
|
+
margin_l: int
|
|
93
|
+
margin_r: int
|
|
94
|
+
margin_v: int
|
|
95
|
+
encoding: int
|
|
96
|
+
|
|
97
|
+
color1: AssColor
|
|
98
|
+
color2: AssColor
|
|
99
|
+
color3: AssColor
|
|
100
|
+
color4: AssColor
|
|
101
|
+
align: int
|
|
102
|
+
|
|
103
|
+
def __init__(self, from_: dict | Iterable | None = None, **kwargs):
|
|
104
|
+
if from_ is not None:
|
|
105
|
+
kwargs = dict(from_)
|
|
106
|
+
if set(kwargs.keys()) != set(self._formats.keys()):
|
|
107
|
+
raise ValueError("Keys of kwargs must equal formats")
|
|
108
|
+
super().__init__({k: self.validate_value(k, v) for k, v in kwargs.items() if k != "name"})
|
|
109
|
+
self._name = kwargs["name"]
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def name(self):
|
|
113
|
+
return self._name
|
|
114
|
+
|
|
115
|
+
def __getitem__(self, key: StyleKeys | str):
|
|
116
|
+
if key in self._alias:
|
|
117
|
+
key = self._alias[key]
|
|
118
|
+
return super().__getitem__(key)
|
|
119
|
+
|
|
120
|
+
def __setitem__(self, key: StyleKeys | str, value):
|
|
121
|
+
if key in self._alias:
|
|
122
|
+
key = self._alias[key]
|
|
123
|
+
if key in self._formats:
|
|
124
|
+
super().__setitem__(key, self.validate_value(key, value))
|
|
125
|
+
else:
|
|
126
|
+
raise KeyError(f"{key} is not a valid key")
|
|
127
|
+
|
|
128
|
+
def __getattr__(self, key: str):
|
|
129
|
+
return self[key]
|
|
130
|
+
|
|
131
|
+
def __setattr__(self, key: str, value) -> None:
|
|
132
|
+
if key.startswith("_"):
|
|
133
|
+
super().__setattr__(key, value)
|
|
134
|
+
else:
|
|
135
|
+
self[key] = value
|
|
136
|
+
|
|
137
|
+
def __repr__(self) -> str:
|
|
138
|
+
return "Style({})".format(",".join(f"{key}={value}" for key, value in self.items()))
|
|
139
|
+
|
|
140
|
+
def __str__(self) -> str:
|
|
141
|
+
style_line = [self.name]
|
|
142
|
+
for key, value in self.items():
|
|
143
|
+
if isinstance(self._formats[key], dict):
|
|
144
|
+
rev_dict = {v: k for k, v in self._formats[key].items()}
|
|
145
|
+
value = rev_dict[value]
|
|
146
|
+
elif type(value) is float:
|
|
147
|
+
value = "{:g}".format(value)
|
|
148
|
+
style_line.append(str(value))
|
|
149
|
+
return f"Style: {','.join(style_line)}"
|
|
150
|
+
|
|
151
|
+
@staticmethod
|
|
152
|
+
def validate_value(key, value):
|
|
153
|
+
if key in Style._alias:
|
|
154
|
+
key = Style._alias[key]
|
|
155
|
+
try:
|
|
156
|
+
return validate_value(Style._formats[key], value)
|
|
157
|
+
except ValueError:
|
|
158
|
+
raise ValueError(f"Invalid value for {key}: {value}")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class Styles(dict[str, Style]):
|
|
162
|
+
def __init__(self, from_: Self | dict[str, Style] | None = None):
|
|
163
|
+
if from_ is None:
|
|
164
|
+
super().__init__()
|
|
165
|
+
else:
|
|
166
|
+
super().__init__(from_)
|
|
167
|
+
|
|
168
|
+
def __setitem__(self, key, value):
|
|
169
|
+
if isinstance(value, Style):
|
|
170
|
+
value._name = key
|
|
171
|
+
super().__setitem__(key, value)
|
|
172
|
+
else:
|
|
173
|
+
raise TypeError("value must be a Style")
|
|
174
|
+
|
|
175
|
+
def __repr__(self):
|
|
176
|
+
return f"Styles({", ".join(self.keys())})"
|
|
177
|
+
|
|
178
|
+
def __str__(self):
|
|
179
|
+
return "\n".join((str(style) for style in self.values()))
|
|
180
|
+
|
|
181
|
+
def set(self, style: Style):
|
|
182
|
+
self[style.name] = style
|
|
183
|
+
|
|
184
|
+
def rename(self, old_name: str, new_name: str):
|
|
185
|
+
if old_name not in self:
|
|
186
|
+
raise KeyError(f"{old_name} is not a valid style name")
|
|
187
|
+
if new_name in self:
|
|
188
|
+
raise KeyError(f"{new_name} is already a style name")
|
|
189
|
+
style = self.pop(old_name)
|
|
190
|
+
style._name = new_name
|
|
191
|
+
self[new_name] = style
|