Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
241 lines (203 loc) · 8.88 KB
/
Copy pathparser.py
File metadata and controls
241 lines (203 loc) · 8.88 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
from copy import deepcopy
from typing import Dict, List, TypedDict
from .constants import TRANSLATION_DIVIDER
from .line import LrcLine
from .scanner import scan_line, scan_word_segments
from .text import LrcText, LrcTextSegment
from .time import LrcTime
class LrcParser:
class ParseResult(TypedDict):
offset: int
lrc_lines: List[LrcLine]
attributes: Dict[str, str]
@classmethod
def parse(
cls,
s: str,
parse_translations: bool = False,
translation_divider: str = TRANSLATION_DIVIDER,
) -> ParseResult:
"""
Parse lyrics from a string.
Examples:
>>> s = '''[ti: TEST]
... [ar: 283375]
... [al: TEST ~AN EXAMPLE FOR YOU~]
... [by: 283375]
... [offset: 375]
...
... [00:05.26]Line 1 example
... [00:07.36]Line 2 example | 翻译示例
... [00:09.54]Line 3 divider example /// 分隔符示例'''
>>> LrcParser.parse(s) == {
... 'offset': 375,
... 'lrc_lines': [
... LrcLine(text="Line 1 example", start_time=LrcTime(0, 5, 260)),
... LrcLine(text="Line 2 example | 翻译示例", start_time=LrcTime(0, 7, 360)),
... LrcLine(text="Line 3 divider example /// 分隔符示例", start_time=LrcTime(0, 9, 540))
... ],
... 'attributes': {
... 'ti': 'TEST',
... 'ar': '283375',
... 'al': 'TEST ~AN EXAMPLE FOR YOU~',
... 'by': '283375',
... 'offset': '375',
... }
... }
True
>>> LrcParser.parse(s, parse_translations=True)['lrc_lines'] == [
... LrcLine(text="Line 1 example", start_time=LrcTime(0, 5, 260)),
... LrcLine(text="Line 2 example", translations=['翻译示例'], start_time=LrcTime(0, 7, 360)),
... LrcLine(text="Line 3 divider example /// 分隔符示例", start_time=LrcTime(0, 9, 540))
... ]
True
>>> LrcParser.parse(s, parse_translations=True, translation_divider=' /// ')['lrc_lines'] == [
... LrcLine(text="Line 1 example", start_time=LrcTime(0, 5, 260)),
... LrcLine(text="Line 2 example | 翻译示例", start_time=LrcTime(0, 7, 360)),
... LrcLine(text="Line 3 divider example", translations=['分隔符示例'], start_time=LrcTime(0, 9, 540))
... ]
True
"""
lines = s.splitlines()
lrc_lines: List[LrcLine] = []
attributes = {}
offset = 0
def __get_lrc_text_from_content(content: str, time: LrcTime):
text = LrcText()
segments = scan_word_segments(content)
if any(timestamp is not None for timestamp, _ in segments):
for timestamp, segment_text in segments:
segment_time = (
LrcTime(timestamp, microsecond=True)
if timestamp is not None
else time
)
text.append(LrcTextSegment(segment_time, segment_text))
else:
text.append(LrcTextSegment(time, content))
return text
for line in lines:
scanned = scan_line(line)
for name, value in scanned.attributes:
attr_name = name.lower()
if attr_name == "offset":
offset = int(value)
attributes[attr_name] = value
if not scanned.timestamps:
continue
content = scanned.content
for timestamp in scanned.timestamps:
time = LrcTime(timestamp, microsecond=True)
text = LrcText()
translations = []
if parse_translations:
splited_content = content.split(translation_divider)
for i, content in enumerate(splited_content):
_list = __get_lrc_text_from_content(content, time)
if i == 0:
text = _list
else:
translations.append(_list)
else:
text = __get_lrc_text_from_content(content, time)
lrc_lines.append(
LrcLine(
start_time=time,
text=text,
translations=translations or None,
)
)
if parse_translations:
duplicate_lines = cls.find_duplicate(lrc_lines)
combined_lines = cls.combine_translation(lrc_lines)
if combined_lines:
[lrc_lines.remove(line) for group in duplicate_lines for line in group]
lrc_lines += combined_lines
return {
"offset": offset,
"lrc_lines": sorted(lrc_lines),
"attributes": attributes,
}
@classmethod
def find_duplicate(cls, lrc_lines: List[LrcLine]) -> List[List[LrcLine]]:
"""
find_duplicate finds duplicate lyrics.
Args:
lrc_lines: A list of LrcLine.
Returns:
A list of duplicate groups, see example for details.
Examples:
>>> LrcParser.find_duplicate([
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 1'),
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 2'),
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 3'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 4'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 5'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 6'),
... ]) == [
... [
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 1'),
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 2'),
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 3'),
... ],
... [
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 4'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 5'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 6'),
... ]
... ]
True
"""
timedelta_dict: Dict[LrcTime, List[LrcLine]] = {}
for lrc_line in lrc_lines:
if timedelta_dict.get(lrc_line.start_time) is None:
timedelta_dict[lrc_line.start_time] = [lrc_line]
else:
timedelta_dict[lrc_line.start_time].append(lrc_line)
timedelta_dict = dict(filter(lambda x: len(x[1]) > 1, timedelta_dict.items()))
return list(dict(sorted(timedelta_dict.items(), key=lambda i: i[0])).values())
@classmethod
def combine_translation(cls, lrc_lines: List[LrcLine]) -> List[LrcLine]:
"""
combine_translation analyzes the translation of the lyric.
Args:
lrc_lines: A list of LrcLine.
Returns:
Processed list of LrcLine, see example for details.
Examples:
>>> LrcParser.combine_translation([
... LrcLine(start_time=LrcTime(0, 1, 589), text='Line 1'),
... LrcLine(start_time=LrcTime(0, 1, 589), text='翻译 1'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='Line 2'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='翻译 2'),
... LrcLine(start_time=LrcTime(0, 2, 589), text='これは2行目です'),
... ]) == [
... LrcLine(
... start_time=LrcTime(0, 1, 589),
... text='Line 1',
... translations=['翻译 1']),
... LrcLine(
... start_time=LrcTime(0, 2, 589),
... text='Line 2',
... translations=['翻译 2', 'これは2行目です'])
... ]
True
"""
duplicates = cls.find_duplicate(lrc_lines)
if len(duplicates) == 0:
return []
combined_lrcs = []
for duplicate in duplicates:
main_lrc_line = duplicate[0]
if main_lrc_line.translations:
translations = deepcopy(main_lrc_line.translations)
translations.extend([lrc_line.text for lrc_line in duplicate[1:]])
else:
translations = [lrc_line.text for lrc_line in duplicate[1:]]
lrc_line = LrcLine(
start_time=main_lrc_line.start_time,
text=main_lrc_line.text,
translations=translations,
)
combined_lrcs.append(lrc_line)
return combined_lrcs