light-ass 0.1.0__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.
- light_ass/__init__.py +8 -0
- light_ass/constants.py +24 -0
- light_ass/events.py +127 -0
- light_ass/script_info.py +97 -0
- light_ass/styles.py +191 -0
- light_ass/subtitle.py +215 -0
- light_ass/tag_parser.py +413 -0
- light_ass/utils.py +139 -0
- light_ass-0.1.0.dist-info/LICENSE +21 -0
- light_ass-0.1.0.dist-info/METADATA +51 -0
- light_ass-0.1.0.dist-info/RECORD +13 -0
- light_ass-0.1.0.dist-info/WHEEL +5 -0
- light_ass-0.1.0.dist-info/top_level.txt +1 -0
light_ass/__init__.py
ADDED
light_ass/constants.py
ADDED
|
@@ -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"(?<!\\){([^}]*)}")
|
light_ass/events.py
ADDED
|
@@ -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)
|
light_ass/script_info.py
ADDED
|
@@ -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}")
|
light_ass/styles.py
ADDED
|
@@ -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
|
light_ass/subtitle.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
import pathlib
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
|
|
5
|
+
from .constants import SECTION_PATTERN, AssSectionHeader, DEFAULT_STYLES_FORMAT, DEFAULT_EVENTS_FORMAT
|
|
6
|
+
from .events import Dialog, Events
|
|
7
|
+
from .script_info import ScriptInfo
|
|
8
|
+
from .styles import Styles, Style
|
|
9
|
+
from .utils import to_snake_case, detect_file_encoding
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"Subtitle",
|
|
13
|
+
"load",
|
|
14
|
+
"from_string",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Subtitle:
|
|
19
|
+
def __init__(self):
|
|
20
|
+
self.messages = []
|
|
21
|
+
self.info = ScriptInfo()
|
|
22
|
+
self.styles = Styles()
|
|
23
|
+
self.events = Events()
|
|
24
|
+
self.other_sections = defaultdict(list)
|
|
25
|
+
self.path: pathlib.Path | None = None
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def load(cls, path: pathlib.Path | str, encoding: str | None = None, strict: bool = True,
|
|
29
|
+
drop_unknown_sections: bool = True) -> "Subtitle":
|
|
30
|
+
"""
|
|
31
|
+
Load subtitle from file.
|
|
32
|
+
:param path: Where the subtitle file is located.
|
|
33
|
+
:param encoding: The encoding of the file. If None, the encoding will be detected.
|
|
34
|
+
:param strict: If false, ignore warnings.
|
|
35
|
+
:param drop_unknown_sections: If false, store unknown sections as is.
|
|
36
|
+
:return: A Subtitle object.
|
|
37
|
+
"""
|
|
38
|
+
if encoding is None:
|
|
39
|
+
encoding = detect_file_encoding(str(path)) or "utf-8-sig"
|
|
40
|
+
doc = cls()
|
|
41
|
+
doc.path = pathlib.Path(path)
|
|
42
|
+
with open(path, "r", encoding=encoding) as f:
|
|
43
|
+
doc._init_from_ass_text(f.read(), strict, drop_unknown_sections)
|
|
44
|
+
return doc
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_string(cls, ass_text: str, strict: bool = True, drop_unknown_sections: bool = True) -> "Subtitle":
|
|
48
|
+
"""
|
|
49
|
+
Load subtitle from an ASS string.
|
|
50
|
+
:param ass_text: An ASS formatted string.
|
|
51
|
+
:param strict: If false, ignore warnings.
|
|
52
|
+
:param drop_unknown_sections: If false, store unknown sections as is.
|
|
53
|
+
:return: A Subtitle object.
|
|
54
|
+
"""
|
|
55
|
+
doc = cls()
|
|
56
|
+
doc._init_from_ass_text(ass_text, strict, drop_unknown_sections)
|
|
57
|
+
return doc
|
|
58
|
+
|
|
59
|
+
def _init_from_ass_text(self, ass_text: str, strict: bool, drop_unknown_sections: bool) -> None:
|
|
60
|
+
def process_info_line(line: str):
|
|
61
|
+
if line.startswith((";", "!:")):
|
|
62
|
+
line = line.removeprefix(";").removeprefix("!:").strip()
|
|
63
|
+
self.messages.append(line)
|
|
64
|
+
else:
|
|
65
|
+
key, _, value = map(str.strip, line.partition(":"))
|
|
66
|
+
self.info[key] = value
|
|
67
|
+
|
|
68
|
+
def parse_format_line(line: str, default):
|
|
69
|
+
if strict and formats.get(section):
|
|
70
|
+
raise ValueError(f"{section} Format line already declared")
|
|
71
|
+
_, _, format_ = line.partition(":")
|
|
72
|
+
formats[section] = map(str.strip, format_.split(",", len(default)))
|
|
73
|
+
formats[section] = list(map(to_snake_case, formats[section]))
|
|
74
|
+
|
|
75
|
+
def check_format():
|
|
76
|
+
if not formats.get(section):
|
|
77
|
+
if strict:
|
|
78
|
+
raise ValueError(f"{section} Format line not declare")
|
|
79
|
+
else:
|
|
80
|
+
return False
|
|
81
|
+
return True
|
|
82
|
+
|
|
83
|
+
def process_styles_line(line: str):
|
|
84
|
+
if line.startswith("Format:"):
|
|
85
|
+
parse_format_line(line, DEFAULT_STYLES_FORMAT)
|
|
86
|
+
elif line.startswith("Style:"):
|
|
87
|
+
if not check_format():
|
|
88
|
+
formats[section] = DEFAULT_STYLES_FORMAT
|
|
89
|
+
_, _, value = map(str.strip, line.partition(":"))
|
|
90
|
+
self.styles.set(Style(zip(formats[section], value.split(",", len(formats[section]) - 1))))
|
|
91
|
+
elif strict:
|
|
92
|
+
raise ValueError(f"Invalid Style line: {line}")
|
|
93
|
+
|
|
94
|
+
def process_events_line(line: str):
|
|
95
|
+
if line.startswith("Format:"):
|
|
96
|
+
parse_format_line(line, DEFAULT_EVENTS_FORMAT)
|
|
97
|
+
if formats[section][-1] != "text":
|
|
98
|
+
raise ValueError("Text must be the last column in Event format.")
|
|
99
|
+
elif line.startswith(("Dialogue:", "Comment:")):
|
|
100
|
+
if not check_format():
|
|
101
|
+
formats[section] = DEFAULT_EVENTS_FORMAT
|
|
102
|
+
_, _, value = map(str.strip, line.partition(":"))
|
|
103
|
+
event_data = dict(zip(formats[section], value.split(",", len(formats[section]) - 1)))
|
|
104
|
+
self.events.append(Dialog(comment=line.startswith("Comment:"), **event_data))
|
|
105
|
+
elif strict:
|
|
106
|
+
raise ValueError(f"Invalid Event line: {line}")
|
|
107
|
+
|
|
108
|
+
def process_other_sections_line(line: str):
|
|
109
|
+
if not drop_unknown_sections:
|
|
110
|
+
self.other_sections[section].append(line)
|
|
111
|
+
|
|
112
|
+
handlers = {
|
|
113
|
+
AssSectionHeader.SCRIPT_INFO: process_info_line,
|
|
114
|
+
AssSectionHeader.ASS_STYLE: process_styles_line,
|
|
115
|
+
AssSectionHeader.EVENTS: process_events_line,
|
|
116
|
+
}
|
|
117
|
+
section = ""
|
|
118
|
+
formats = {}
|
|
119
|
+
for line in ass_text.splitlines():
|
|
120
|
+
line = line.lstrip(" ")
|
|
121
|
+
if not line:
|
|
122
|
+
continue
|
|
123
|
+
if match := SECTION_PATTERN.match(line):
|
|
124
|
+
section = match.group(1).title()
|
|
125
|
+
else:
|
|
126
|
+
handlers.get(section, process_other_sections_line)(line)
|
|
127
|
+
|
|
128
|
+
default_info = {
|
|
129
|
+
"ScaledBorderAndShadow": True,
|
|
130
|
+
"YCbCr Matrix": "TV.601",
|
|
131
|
+
"PlayResX": self.info.get("LayoutResX", None) or 1920,
|
|
132
|
+
"PlayResY": self.info.get("LayoutResY", None) or 1080,
|
|
133
|
+
"LayoutResX": self.info.get("PlayResX", None) or 1920,
|
|
134
|
+
"LayoutResY": self.info.get("PlayResY", None) or 1080,
|
|
135
|
+
}
|
|
136
|
+
self.info |= default_info | self.info
|
|
137
|
+
|
|
138
|
+
def rename_style(self, old_name: str, new_name: str):
|
|
139
|
+
self.styles.rename(old_name, new_name)
|
|
140
|
+
for event in self.events:
|
|
141
|
+
if event.style == old_name:
|
|
142
|
+
event.style = new_name
|
|
143
|
+
# tags = event.parse_tags()
|
|
144
|
+
# flag = False
|
|
145
|
+
# for tag in tags:
|
|
146
|
+
# if tag.name == "r" and tag.value == old_name:
|
|
147
|
+
# tag.value = new_name
|
|
148
|
+
# flag = True
|
|
149
|
+
# if flag:
|
|
150
|
+
# event.text = "".join(str(tag) for tag in tags)
|
|
151
|
+
|
|
152
|
+
def to_string(self) -> str:
|
|
153
|
+
"""
|
|
154
|
+
Convert the Subtitle object to an ASS formatted string.
|
|
155
|
+
:return: An ASS formatted string.
|
|
156
|
+
"""
|
|
157
|
+
lines = ["[Script Info]"]
|
|
158
|
+
if self.messages:
|
|
159
|
+
lines.append("\n".join(f"; {message}" for message in self.messages))
|
|
160
|
+
lines += [str(self.info), "\n[V4+ Styles]",
|
|
161
|
+
"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, "
|
|
162
|
+
"Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, "
|
|
163
|
+
"Shadow, Alignment, MarginL, MarginR, MarginV, Encoding", str(self.styles), "\n[Events]",
|
|
164
|
+
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"]
|
|
165
|
+
|
|
166
|
+
for event in self.events:
|
|
167
|
+
lines.append(str(event))
|
|
168
|
+
|
|
169
|
+
for name, content in self.other_sections.items():
|
|
170
|
+
lines.append(f"\n[{name}]")
|
|
171
|
+
lines.extend(content)
|
|
172
|
+
|
|
173
|
+
return "\n".join(lines)
|
|
174
|
+
|
|
175
|
+
def save(self, path: pathlib.Path | str, encoding: str = "utf-8-sig") -> None:
|
|
176
|
+
"""
|
|
177
|
+
Save the Subtitle object to the path with the given encoding.
|
|
178
|
+
:param path: The path to save the subtitle to.
|
|
179
|
+
:param encoding: The encoding to use when saving the file.
|
|
180
|
+
:return: None
|
|
181
|
+
"""
|
|
182
|
+
with open(path, "w", encoding=encoding) as f:
|
|
183
|
+
f.write(self.to_string())
|
|
184
|
+
|
|
185
|
+
def copy(self):
|
|
186
|
+
"""
|
|
187
|
+
Create a deep copy of the Subtitle object.
|
|
188
|
+
:return: A deep copy of the Subtitle object.
|
|
189
|
+
"""
|
|
190
|
+
return copy.deepcopy(self)
|
|
191
|
+
|
|
192
|
+
def __repr__(self) -> str:
|
|
193
|
+
return f"Subtitle(with {len(self.events)} events)"
|
|
194
|
+
|
|
195
|
+
def __setattr__(self, key, value):
|
|
196
|
+
if key == "info":
|
|
197
|
+
if isinstance(value, ScriptInfo):
|
|
198
|
+
super().__setattr__(key, value)
|
|
199
|
+
elif isinstance(value, dict):
|
|
200
|
+
super().__setattr__(key, ScriptInfo(value))
|
|
201
|
+
else:
|
|
202
|
+
raise TypeError(f"Invalid type for info: {type(value)}")
|
|
203
|
+
elif key == "styles":
|
|
204
|
+
if isinstance(value, Styles):
|
|
205
|
+
super().__setattr__(key, value)
|
|
206
|
+
elif isinstance(value, dict):
|
|
207
|
+
super().__setattr__(key, Styles(value))
|
|
208
|
+
else:
|
|
209
|
+
raise TypeError(f"Invalid type for styles: {type(value)}")
|
|
210
|
+
else:
|
|
211
|
+
super().__setattr__(key, value)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
load = Subtitle.load
|
|
215
|
+
from_string = Subtitle.from_string
|
light_ass/tag_parser.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
from itertools import takewhile, dropwhile
|
|
2
|
+
from typing import Sequence, Any
|
|
3
|
+
|
|
4
|
+
from .ass_types import AssColor, AssAlpha, AssDrawing
|
|
5
|
+
from .constants import OVERRIDE_BLOCK_PATTERN
|
|
6
|
+
from .utils import parse_int32, parse_positive_int32, parse_float, parse_positive_float, \
|
|
7
|
+
parse_ass_color, parse_ass_alpha
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Tag",
|
|
11
|
+
"parse_tags",
|
|
12
|
+
"join_tags",
|
|
13
|
+
"is_simple_tag",
|
|
14
|
+
"is_complex_tag",
|
|
15
|
+
"is_line_tag",
|
|
16
|
+
"is_unknown_tag"
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
_int = parse_int32
|
|
20
|
+
_positive_int = parse_positive_int32
|
|
21
|
+
_float = parse_float
|
|
22
|
+
_positive_float = parse_positive_float
|
|
23
|
+
_ass_color = parse_ass_color
|
|
24
|
+
_ass_alpha = parse_ass_alpha
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class FallbackError(Exception):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class InvalidArgError(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_simple_tag(name: str) -> bool:
|
|
36
|
+
simple_tags = (
|
|
37
|
+
"xbord", "ybord", "xshad", "yshad", "fax", "fay", "blur", "fscx", "fscy", "fsc", "fsp", "fs", "bord", "frx",
|
|
38
|
+
"fry", "frz", "fr", "fn", "alpha", "an", "a", "c", "1c", "2c", "3c", "4c", "1a", "2a", "3a", "4a", "r", "be",
|
|
39
|
+
"b", "i", "kt", "kf", "K", "ko", "k", "shad", "s", "u", "pbo", "p", "q", "fe"
|
|
40
|
+
)
|
|
41
|
+
return name in simple_tags
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def is_complex_tag(name: str) -> bool:
|
|
45
|
+
complex_tags = ("t", "clip", "iclip", "move", "fade", "fad", "pos", "org")
|
|
46
|
+
return name in complex_tags
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def is_line_tag(name: str) -> bool:
|
|
50
|
+
line_tags = ("clip", "iclip", "move", "fade", "fad", "pos", "org", "an", "a")
|
|
51
|
+
return name in line_tags
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def is_special_tag(name: str) -> bool:
|
|
55
|
+
special_tags = ("Comment", "Drawing", "Text")
|
|
56
|
+
return name in special_tags
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def is_unknown_tag(name: str) -> bool:
|
|
60
|
+
return not is_special_tag(name) and name not in tag_args
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def is_nestable_tag(name: str) -> bool:
|
|
64
|
+
nestable_tags = (
|
|
65
|
+
"xbord", "ybord", "xshad", "yshad", "fax", "fay", "blur", "fscx", "fscy", "fsp", "fs", "bord", "frx",
|
|
66
|
+
"fry", "frz", "fr", "alpha", "c", "1c", "2c", "3c", "4c", "1a", "2a", "3a", "4a", "be", "shad", "clip", "iclip"
|
|
67
|
+
)
|
|
68
|
+
return name in nestable_tags
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def format_arg(arg) -> str:
|
|
72
|
+
match arg:
|
|
73
|
+
case float():
|
|
74
|
+
arg = f"{arg:g}"
|
|
75
|
+
case list():
|
|
76
|
+
return "".join(map(lambda t: t.to_string(), arg))
|
|
77
|
+
case AssAlpha():
|
|
78
|
+
arg = arg.format()
|
|
79
|
+
case AssColor():
|
|
80
|
+
arg = arg.format("&H{B}{G}{R}&")
|
|
81
|
+
case _:
|
|
82
|
+
arg = str(arg).strip()
|
|
83
|
+
return arg
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class Tag:
|
|
87
|
+
def __init__(self, name: str, args, valid: bool | None = None):
|
|
88
|
+
self.name = name
|
|
89
|
+
self.args, self.valid = self.validate_args(name, args)
|
|
90
|
+
if valid is not None:
|
|
91
|
+
self.valid = valid
|
|
92
|
+
|
|
93
|
+
def __eq__(self, other):
|
|
94
|
+
return self.name == other.name and self.args == other.args
|
|
95
|
+
|
|
96
|
+
def __repr__(self):
|
|
97
|
+
return f"Tag(name={self.name}, with {len(self.args)} {"arg" if len(self.args) == 1 else "args"})"
|
|
98
|
+
|
|
99
|
+
def __str__(self):
|
|
100
|
+
return self.to_string()
|
|
101
|
+
|
|
102
|
+
def to_string(self):
|
|
103
|
+
if self.is_special_tag:
|
|
104
|
+
return self.args[0]
|
|
105
|
+
if len(self.args) == 0:
|
|
106
|
+
return f"\\{self.name}"
|
|
107
|
+
elif self.is_simple_tag and len(self.args) == 1:
|
|
108
|
+
return f"\\{self.name}{format_arg(self.args[0])}"
|
|
109
|
+
else:
|
|
110
|
+
return f"\\{self.name}({','.join(map(lambda s: format_arg(s), self.args))})"
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def is_simple_tag(self) -> bool:
|
|
114
|
+
return is_simple_tag(self.name)
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def is_complex_tag(self) -> bool:
|
|
118
|
+
return is_complex_tag(self.name)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def is_line_tag(self) -> bool:
|
|
122
|
+
return is_line_tag(self.name)
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def is_special_tag(self) -> bool:
|
|
126
|
+
return is_special_tag(self.name)
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def is_unknown_tag(self) -> bool:
|
|
130
|
+
return is_unknown_tag(self.name)
|
|
131
|
+
|
|
132
|
+
@staticmethod
|
|
133
|
+
def _validate_args(name: str, args: Sequence[str]) -> tuple[tuple, bool]:
|
|
134
|
+
args = tuple(args)
|
|
135
|
+
validators = None
|
|
136
|
+
for typ in tag_args[name]:
|
|
137
|
+
if len(args) == len(typ):
|
|
138
|
+
validators = typ
|
|
139
|
+
break
|
|
140
|
+
if validators is None:
|
|
141
|
+
return args, False
|
|
142
|
+
try:
|
|
143
|
+
args = tuple(func(arg.strip()) for arg, func in zip(args, validators))
|
|
144
|
+
return args, True
|
|
145
|
+
except FallbackError:
|
|
146
|
+
return tuple(), True
|
|
147
|
+
except InvalidArgError:
|
|
148
|
+
return tuple(), False
|
|
149
|
+
except ValueError:
|
|
150
|
+
return args, False
|
|
151
|
+
|
|
152
|
+
@staticmethod
|
|
153
|
+
def validate_args(name: str, args: Sequence[Any]) -> tuple[tuple, bool]:
|
|
154
|
+
if is_special_tag(name):
|
|
155
|
+
return tuple(args), True
|
|
156
|
+
valid = False
|
|
157
|
+
args = tuple(map(str, args))
|
|
158
|
+
if is_simple_tag(name) and len(args) > 1:
|
|
159
|
+
args = (args[0])
|
|
160
|
+
if name == "t":
|
|
161
|
+
if args:
|
|
162
|
+
last = split_tags(args[-1], True)
|
|
163
|
+
args, valid = Tag._validate_args(name, args[:-1])
|
|
164
|
+
args = list(args)
|
|
165
|
+
args.append(last)
|
|
166
|
+
elif name in tag_args:
|
|
167
|
+
args, valid = Tag._validate_args(name, args)
|
|
168
|
+
return tuple(args), valid
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def join_tags(tags: list[Tag], skip_comment: bool = False) -> str:
|
|
172
|
+
"""
|
|
173
|
+
Join tags into text.
|
|
174
|
+
:param tags: The tags to join.
|
|
175
|
+
:param skip_comment: Whether to skip comments.
|
|
176
|
+
:return: The joined text.
|
|
177
|
+
"""
|
|
178
|
+
if any(not isinstance(tag, Tag) for tag in tags):
|
|
179
|
+
raise TypeError("All elements must be of type Tag")
|
|
180
|
+
text = ""
|
|
181
|
+
in_tag = False
|
|
182
|
+
for tag in filter(lambda x: not skip_comment or x.name != "Comment", tags):
|
|
183
|
+
if tag.name in ("Drawing", "Text"):
|
|
184
|
+
if in_tag:
|
|
185
|
+
text += "}"
|
|
186
|
+
text += tag.args[0]
|
|
187
|
+
in_tag = False
|
|
188
|
+
else:
|
|
189
|
+
if not in_tag:
|
|
190
|
+
text += "{"
|
|
191
|
+
text += tag.to_string()
|
|
192
|
+
in_tag = True
|
|
193
|
+
if in_tag:
|
|
194
|
+
text += "}"
|
|
195
|
+
return text
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _parse_fs_arg(s: str) -> float | str:
|
|
199
|
+
if not s:
|
|
200
|
+
return 0
|
|
201
|
+
if s.startswith(("+", "-")):
|
|
202
|
+
return s
|
|
203
|
+
else:
|
|
204
|
+
return float(s)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _parse_fn_arg(s: str) -> str:
|
|
208
|
+
if s == "0":
|
|
209
|
+
raise FallbackError
|
|
210
|
+
return s
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _parse_an_arg(s: str) -> int:
|
|
214
|
+
try:
|
|
215
|
+
val = int(s)
|
|
216
|
+
if 1 <= val <= 9:
|
|
217
|
+
return val
|
|
218
|
+
raise InvalidArgError
|
|
219
|
+
except ValueError:
|
|
220
|
+
raise InvalidArgError
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _parse_a_arg(s: str) -> int:
|
|
224
|
+
try:
|
|
225
|
+
val = int(s)
|
|
226
|
+
if 1 <= val <= 11:
|
|
227
|
+
return val if (val & 3) != 0 else 5
|
|
228
|
+
raise InvalidArgError
|
|
229
|
+
except ValueError:
|
|
230
|
+
raise InvalidArgError
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _parse_be_arg(s: str) -> int:
|
|
234
|
+
return max(0, int(parse_float(s) + 0.5))
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _parse_b_arg(s: str) -> int:
|
|
238
|
+
val = parse_int32(s)
|
|
239
|
+
if val == 0 or val == 1 or val >= 100:
|
|
240
|
+
return val
|
|
241
|
+
raise FallbackError
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _parse_boolean_arg(s: str) -> int:
|
|
245
|
+
val = parse_int32(s)
|
|
246
|
+
if val == 0 or val == 1:
|
|
247
|
+
return val
|
|
248
|
+
raise FallbackError
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _parse_kx_arg(s: str) -> float:
|
|
252
|
+
val = parse_float(s)
|
|
253
|
+
return int(val * 10) / 10
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# def parse_k_arg(s: str) -> float:
|
|
257
|
+
# val = parse_float(s)
|
|
258
|
+
# if val == 100:
|
|
259
|
+
# raise FallbackError
|
|
260
|
+
# return int(val * 10) / 10
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _parse_q_arg(s: str) -> int:
|
|
264
|
+
val = parse_int32(s)
|
|
265
|
+
if 0 <= val <= 3:
|
|
266
|
+
return val
|
|
267
|
+
raise InvalidArgError
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
tag_args = {
|
|
271
|
+
"xbord": ((_positive_float,), ()),
|
|
272
|
+
"ybord": ((_positive_float,), ()),
|
|
273
|
+
"xshad": ((_float,), ()),
|
|
274
|
+
"yshad": ((_float,), ()),
|
|
275
|
+
"fax": ((_float,), ()),
|
|
276
|
+
"fay": ((_float,), ()),
|
|
277
|
+
"iclip": ((_int, _int, _int, _int), (AssDrawing,)),
|
|
278
|
+
"blur": ((_positive_float,), ()),
|
|
279
|
+
"fscx": ((_positive_float,), ()),
|
|
280
|
+
"fscy": ((_positive_float,), ()),
|
|
281
|
+
"fsc": ((),),
|
|
282
|
+
"fsp": ((_float,),),
|
|
283
|
+
"fs": ((_parse_fs_arg,), ()),
|
|
284
|
+
"bord": ((_float,), ()),
|
|
285
|
+
"move": ((_float, _float, _float, _float), (_float, _float, _float, _float, _int, _int)),
|
|
286
|
+
"frx": ((_float,), ()),
|
|
287
|
+
"fry": ((_float,), ()),
|
|
288
|
+
"frz": ((_float,), ()),
|
|
289
|
+
"fr": ((_float,), ()),
|
|
290
|
+
"fn": ((_parse_fn_arg,), ()),
|
|
291
|
+
"alpha": ((AssAlpha,), ()),
|
|
292
|
+
"an": ((_int,),),
|
|
293
|
+
"a": ((_int,),),
|
|
294
|
+
"pos": ((_float, _float),),
|
|
295
|
+
"fade": ((_int, _int), (AssAlpha, AssAlpha, AssAlpha, _int, _int, _int, _int)),
|
|
296
|
+
"fad": ((_int, _int), (AssAlpha, AssAlpha, AssAlpha, _int, _int, _int, _int)),
|
|
297
|
+
"org": ((_float, _float),),
|
|
298
|
+
"clip": ((_int, _int, _int, _int), (AssDrawing,)),
|
|
299
|
+
"c": ((_ass_color,), ()),
|
|
300
|
+
"1c": ((_ass_color,), ()),
|
|
301
|
+
"2c": ((_ass_color,), ()),
|
|
302
|
+
"3c": ((_ass_color,), ()),
|
|
303
|
+
"4c": ((_ass_color,), ()),
|
|
304
|
+
"1a": ((AssAlpha,), ()),
|
|
305
|
+
"2a": ((AssAlpha,), ()),
|
|
306
|
+
"3a": ((AssAlpha,), ()),
|
|
307
|
+
"4a": ((AssAlpha,), ()),
|
|
308
|
+
"r": ((str,), ()),
|
|
309
|
+
"be": ((_parse_be_arg,), ()),
|
|
310
|
+
"b": ((_parse_b_arg,), ()),
|
|
311
|
+
"i": ((_parse_boolean_arg,), ()),
|
|
312
|
+
"kt": ((_parse_kx_arg,),),
|
|
313
|
+
"kf": ((_parse_kx_arg,),),
|
|
314
|
+
"K": ((_parse_kx_arg,),),
|
|
315
|
+
"ko": ((_parse_kx_arg,),),
|
|
316
|
+
"k": ((_parse_kx_arg,),),
|
|
317
|
+
"shad": ((_positive_float,), ()),
|
|
318
|
+
"s": ((_parse_boolean_arg,), ()),
|
|
319
|
+
"u": ((_parse_boolean_arg,), ()),
|
|
320
|
+
"pbo": ((_float,),),
|
|
321
|
+
"p": ((_positive_int,), ()),
|
|
322
|
+
"q": ((_parse_q_arg,), ()),
|
|
323
|
+
"fe": ((_int,), ()),
|
|
324
|
+
|
|
325
|
+
"t": ((_float,), (_int, _int), (_int, _int, _float)),
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def split_tags(block, nested=False):
|
|
330
|
+
result = []
|
|
331
|
+
while block:
|
|
332
|
+
comment = "".join(takewhile(lambda x: x != "\\", block))
|
|
333
|
+
if comment:
|
|
334
|
+
result.append(Tag("Comment", [comment]))
|
|
335
|
+
block = block[len(comment):]
|
|
336
|
+
block = block.lstrip("\\")
|
|
337
|
+
if not block:
|
|
338
|
+
break
|
|
339
|
+
name = "".join(takewhile(lambda x: x not in "(\\", block))
|
|
340
|
+
if not name:
|
|
341
|
+
continue
|
|
342
|
+
block = block[len(name):]
|
|
343
|
+
args = []
|
|
344
|
+
if block.startswith("("):
|
|
345
|
+
block = block[1:]
|
|
346
|
+
while True:
|
|
347
|
+
block = "".join(dropwhile(lambda x: x in " \t", block))
|
|
348
|
+
arg = "".join(takewhile(lambda x: x not in ",)\\", block))
|
|
349
|
+
block = block[len(arg):]
|
|
350
|
+
if block.startswith(","):
|
|
351
|
+
if arg:
|
|
352
|
+
args.append(arg)
|
|
353
|
+
block = block[1:]
|
|
354
|
+
else:
|
|
355
|
+
if block.startswith("\\"):
|
|
356
|
+
arg = block[:block.find(")")] if block.find(")") != -1 else block
|
|
357
|
+
block = block[len(arg):]
|
|
358
|
+
if arg:
|
|
359
|
+
args.append(arg)
|
|
360
|
+
if block:
|
|
361
|
+
block = block[1:]
|
|
362
|
+
break
|
|
363
|
+
|
|
364
|
+
for tag in tag_args:
|
|
365
|
+
if name.startswith(tag):
|
|
366
|
+
if name != tag and is_simple_tag(tag):
|
|
367
|
+
args.append(name[len(tag):])
|
|
368
|
+
name = tag
|
|
369
|
+
break
|
|
370
|
+
if name not in tag_args and not args: # deals with unknown simple tags
|
|
371
|
+
flag = False
|
|
372
|
+
tag_name = ""
|
|
373
|
+
for ch in name:
|
|
374
|
+
if ch.isdigit() and not flag:
|
|
375
|
+
tag_name += ch
|
|
376
|
+
elif ch.islower():
|
|
377
|
+
flag = True
|
|
378
|
+
tag_name += ch
|
|
379
|
+
else:
|
|
380
|
+
break
|
|
381
|
+
if name != tag_name:
|
|
382
|
+
args.append(name[len(tag_name):])
|
|
383
|
+
name = tag_name
|
|
384
|
+
tag = Tag(name, args)
|
|
385
|
+
if nested and not is_nestable_tag(name):
|
|
386
|
+
tag.valid = False
|
|
387
|
+
result.append(tag)
|
|
388
|
+
|
|
389
|
+
return result
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def parse_tags(text: str) -> list[Tag]:
|
|
393
|
+
"""
|
|
394
|
+
Parse tags from text.
|
|
395
|
+
:param text: The text to parse.
|
|
396
|
+
:return: A list of Tag objects.
|
|
397
|
+
"""
|
|
398
|
+
result = []
|
|
399
|
+
splits = OVERRIDE_BLOCK_PATTERN.split(text)
|
|
400
|
+
drawing_mode = False
|
|
401
|
+
for i, block in enumerate(splits):
|
|
402
|
+
if i % 2 == 1:
|
|
403
|
+
tags = split_tags(block)
|
|
404
|
+
result.extend(tags)
|
|
405
|
+
for tag in tags:
|
|
406
|
+
if tag.name == "p" and tag.valid:
|
|
407
|
+
drawing_mode = tag.args and tag.args[0] > 0
|
|
408
|
+
elif block:
|
|
409
|
+
if drawing_mode:
|
|
410
|
+
result.append(Tag("Drawing", [AssDrawing(block)]))
|
|
411
|
+
else:
|
|
412
|
+
result.append(Tag("Text", [block]))
|
|
413
|
+
return result
|
light_ass/utils.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Callable
|
|
3
|
+
from itertools import takewhile
|
|
4
|
+
|
|
5
|
+
INT32_MIN = -2_147_483_648
|
|
6
|
+
INT32_MAX = 2_147_483_647
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def clamp(val: int, min_: int, max_: int) -> int:
|
|
10
|
+
return min(max(val, min_), max_)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def to_snake_case(text: str) -> str:
|
|
14
|
+
return re.sub(r"(?<!^)(?=[A-Z])", "_", text).lower()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def detect_file_encoding(file_path: str, sample_size: int = 1024) -> str | None:
|
|
18
|
+
import codecs
|
|
19
|
+
|
|
20
|
+
bom_map = {
|
|
21
|
+
codecs.BOM_UTF8: "utf-8-sig",
|
|
22
|
+
codecs.BOM_UTF16_LE: "utf-16-le",
|
|
23
|
+
codecs.BOM_UTF16_BE: "utf-16-be",
|
|
24
|
+
codecs.BOM_UTF32_LE: "utf-32-le",
|
|
25
|
+
codecs.BOM_UTF32_BE: "utf-32-be",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
with open(file_path, "rb") as f:
|
|
29
|
+
sample = f.read(sample_size)
|
|
30
|
+
|
|
31
|
+
for bom, encoding in bom_map.items():
|
|
32
|
+
if sample.startswith(bom):
|
|
33
|
+
return encoding
|
|
34
|
+
|
|
35
|
+
test_encodings = ["utf-8", "gb18030", "big5", "shift_jis", "euc-kr", "iso-8859-1", "cp1252"]
|
|
36
|
+
|
|
37
|
+
for encoding in test_encodings:
|
|
38
|
+
try:
|
|
39
|
+
sample.decode(encoding, errors="strict")
|
|
40
|
+
return encoding
|
|
41
|
+
except UnicodeDecodeError:
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def validate_value(validator: Callable | tuple | dict, value: str):
|
|
48
|
+
match validator:
|
|
49
|
+
case validator if callable(validator):
|
|
50
|
+
return validator(value)
|
|
51
|
+
case tuple():
|
|
52
|
+
typ_ = type(validator[0])
|
|
53
|
+
if typ_(value) in validator:
|
|
54
|
+
return typ_(value)
|
|
55
|
+
case dict():
|
|
56
|
+
if value in validator:
|
|
57
|
+
return validator[value]
|
|
58
|
+
if value in validator.values():
|
|
59
|
+
return value
|
|
60
|
+
case _:
|
|
61
|
+
pass
|
|
62
|
+
raise ValueError(f"Invalid value")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_int32(s: str) -> int:
|
|
66
|
+
s = s.lstrip(" \t")
|
|
67
|
+
if not s:
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
sgn = 1
|
|
71
|
+
if s[0] in "+-":
|
|
72
|
+
sgn = 1 if s[0] == "+" else -1
|
|
73
|
+
s = s[1:]
|
|
74
|
+
|
|
75
|
+
num_str = "".join(takewhile(lambda x: x.isdigit(), s))
|
|
76
|
+
num = sgn * int(num_str) if num_str else 0
|
|
77
|
+
return clamp(num, INT32_MIN, INT32_MAX)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parse_positive_int32(s: str) -> int:
|
|
81
|
+
num = parse_int32(s)
|
|
82
|
+
return num if num > 0 else 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def parse_float(s: str) -> float:
|
|
86
|
+
s = s.lstrip(" \t")
|
|
87
|
+
if not s:
|
|
88
|
+
return 0.0
|
|
89
|
+
|
|
90
|
+
sgn = 1
|
|
91
|
+
if s[0] in "+-":
|
|
92
|
+
sgn = 1 if s[0] == "+" else -1
|
|
93
|
+
s = s[1:]
|
|
94
|
+
|
|
95
|
+
num_str = ".".join(
|
|
96
|
+
map(
|
|
97
|
+
lambda x: "".join(takewhile(lambda ch: ch.isdigit(), x)),
|
|
98
|
+
s.split(".", 1)
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
if num_str.startswith("."):
|
|
103
|
+
num_str = "0" + num_str
|
|
104
|
+
|
|
105
|
+
return sgn * float(num_str) if num_str and num_str else 0.0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def parse_positive_float(s: str) -> float:
|
|
109
|
+
num = parse_float(s)
|
|
110
|
+
return num if num > 0 else 0.0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def parse_ass_color(s: str):
|
|
114
|
+
from .ass_types import AssColor
|
|
115
|
+
|
|
116
|
+
s = s.lstrip("&H").lstrip(" \t")
|
|
117
|
+
if s.startswith("+"):
|
|
118
|
+
s = s[1:]
|
|
119
|
+
if not tuple(takewhile(lambda x: x in "0123456789ABCDEF", s)):
|
|
120
|
+
return AssColor(0, 0, 0)
|
|
121
|
+
color = AssColor(s)
|
|
122
|
+
rev_value = (color.a << 24) | (color.b << 16) | (color.g << 8) | color.r
|
|
123
|
+
if rev_value >= INT32_MAX:
|
|
124
|
+
color = AssColor(255, 255, 255)
|
|
125
|
+
color.a = 0
|
|
126
|
+
return color
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def parse_ass_alpha(s: str):
|
|
130
|
+
from .ass_types import AssAlpha
|
|
131
|
+
|
|
132
|
+
s = s.lstrip("&H").lstrip(" \t")
|
|
133
|
+
if s.startswith("+"):
|
|
134
|
+
s = s[1:]
|
|
135
|
+
num_str = "".join(takewhile(lambda x: x in "0123456789ABCDEF", s))
|
|
136
|
+
if not num_str:
|
|
137
|
+
return AssAlpha(0)
|
|
138
|
+
val = int(num_str, 16) & 0xFF
|
|
139
|
+
return AssAlpha(val)
|
|
@@ -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.
|
|
@@ -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,13 @@
|
|
|
1
|
+
light_ass/__init__.py,sha256=PKjryp5HDXk_1LCTawdntnW_7A8ayHAtfNbpLANx-TY,150
|
|
2
|
+
light_ass/constants.py,sha256=mjwUZSHiLU7LZKSE1rj2HKpubCAdJ-zQ3fAkl0TathE,813
|
|
3
|
+
light_ass/events.py,sha256=bB3b0PMR3bdHtJdtNTf9oO2-uCSK2YFW5s3324x47h4,3668
|
|
4
|
+
light_ass/script_info.py,sha256=4RhNMStYPoDnhOsPGROTtaYNf3iKrjH16bvJ-YtWZlg,2794
|
|
5
|
+
light_ass/styles.py,sha256=8by8sk8t_TM1aJUS-SChQPIx0EpvkyK84zo65V_QSvU,5188
|
|
6
|
+
light_ass/subtitle.py,sha256=cj7txdmTZBXrEXrHX08dPA-i2_-Mc3KB5raJsxcA-Lg,8640
|
|
7
|
+
light_ass/tag_parser.py,sha256=dVDQFi8dRR8oqaS6vlfDBoRPE4suRkRrcuDYt4QcJ7E,12027
|
|
8
|
+
light_ass/utils.py,sha256=UqjPyWvHgKjOerR3nSPHnH2UxFb18Jom_4P1sK_5r14,3465
|
|
9
|
+
light_ass-0.1.0.dist-info/LICENSE,sha256=QF-xOWlFl6tTZv5kdXO-tSlyfPPpB7PjOrnvfrfAf1E,1061
|
|
10
|
+
light_ass-0.1.0.dist-info/METADATA,sha256=dCd2b7pDy5s_JHPJpy_eV1lWDWMcT4pexHgl6Z8PZCw,1335
|
|
11
|
+
light_ass-0.1.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
12
|
+
light_ass-0.1.0.dist-info/top_level.txt,sha256=h0CIOYC-ay25jfy-w68BC_vo0iIipbSROMiq9rdmZys,10
|
|
13
|
+
light_ass-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
light_ass
|