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 399 400 401 402 403
|
"""VTT format module."""
import re
import typing
from dataclasses import dataclass
from .errors import MalformedFileError
from .models import Caption, Style
from . import utils
@dataclass
class ParserOutput:
"""Output of parser."""
styles: typing.List[Style]
captions: typing.List[Caption]
header_comments: typing.List[str]
footer_comments: typing.List[str]
@classmethod
def from_data(
cls,
data: typing.Mapping[str, typing.Any]
) -> 'ParserOutput':
"""
Return a `ParserOutput` instance from the provided data.
:param data: data from the parser
:returns: an instance of `ParserOutput`
"""
items = data.get('items', [])
return cls(
captions=[it for it in items if isinstance(it, Caption)],
styles=[it for it in items if isinstance(it, Style)],
header_comments=data.get('header_comments', []),
footer_comments=data.get('footer_comments', [])
)
class WebVTTCueBlock:
"""Representation of a cue timing block."""
CUE_TIMINGS_PATTERN = re.compile(
r'\s*((?:\d+:)?\d{2}:\d{2}.\d{3})\s*-->\s*((?:\d+:)?\d{2}:\d{2}.\d{3})'
)
def __init__(
self,
identifier,
start,
end,
payload
):
"""
Initialize.
:param start: start time
:param end: end time
:param payload: caption text
"""
self.identifier = identifier
self.start = start
self.end = end
self.payload = payload
@classmethod
def is_valid(
cls,
lines: typing.Sequence[str]
) -> bool:
"""
Validate the lines for a match of a cue time block.
:param lines: the lines to be validated
:returns: true for a matching cue time block
"""
return bool(
(
len(lines) >= 2 and
re.match(cls.CUE_TIMINGS_PATTERN, lines[0]) and
"-->" not in lines[1]
) or
(
len(lines) >= 3 and
"-->" not in lines[0] and
re.match(cls.CUE_TIMINGS_PATTERN, lines[1]) and
"-->" not in lines[2]
)
)
@classmethod
def from_lines(
cls,
lines: typing.Iterable[str]
) -> 'WebVTTCueBlock':
"""
Create a `WebVTTCueBlock` from lines of text.
:param lines: the lines of text
:returns: `WebVTTCueBlock` instance
"""
identifier = None
start = None
end = None
payload = []
for line in lines:
timing_match = re.match(cls.CUE_TIMINGS_PATTERN, line)
if timing_match:
start = timing_match.group(1)
end = timing_match.group(2)
elif not start:
identifier = line
else:
payload.append(line)
return cls(identifier, start, end, payload)
@staticmethod
def format_lines(caption: Caption) -> typing.List[str]:
"""
Return the lines for a cue block.
:param caption: the `Caption` instance
:returns: list of lines for a cue block
"""
return [
'',
*(identifier for identifier in {caption.identifier} if identifier),
f'{caption.start} --> {caption.end}',
*caption.lines
]
class WebVTTCommentBlock:
"""Representation of a comment block."""
COMMENT_PATTERN = re.compile(r'NOTE\s(.*?)\Z', re.DOTALL)
def __init__(self, text: str):
"""
Initialize.
:param text: comment text
"""
self.text = text
@classmethod
def is_valid(
cls,
lines: typing.Sequence[str]
) -> bool:
"""
Validate the lines for a match of a comment block.
:param lines: the lines to be validated
:returns: true for a matching comment block
"""
return bool(lines and lines[0].startswith('NOTE'))
@classmethod
def from_lines(
cls,
lines: typing.Iterable[str]
) -> 'WebVTTCommentBlock':
"""
Create a `WebVTTCommentBlock` from lines of text.
:param lines: the lines of text
:returns: `WebVTTCommentBlock` instance
"""
match = cls.COMMENT_PATTERN.match('\n'.join(lines))
return cls(text=match.group(1).strip() if match else '')
@staticmethod
def format_lines(lines: str) -> typing.List[str]:
"""
Return the lines for a comment block.
:param lines: comment lines
:returns: list of lines for a comment block
"""
list_of_lines = lines.split('\n')
if len(list_of_lines) == 1:
return [f'NOTE {lines}']
return ['NOTE', *list_of_lines]
class WebVTTStyleBlock:
"""Representation of a style block."""
STYLE_PATTERN = re.compile(r'STYLE\s(.*?)\Z', re.DOTALL)
def __init__(self, text: str):
"""
Initialize.
:param text: style text
"""
self.text = text
@classmethod
def is_valid(
cls,
lines: typing.Sequence[str]
) -> bool:
"""
Validate the lines for a match of a style block.
:param lines: the lines to be validated
:returns: true for a matching style block
"""
return (len(lines) >= 2 and
lines[0] == 'STYLE' and
not any(line.strip() == '' or '-->' in line for line in lines)
)
@classmethod
def from_lines(
cls,
lines: typing.Iterable[str]
) -> 'WebVTTStyleBlock':
"""
Create a `WebVTTStyleBlock` from lines of text.
:param lines: the lines of text
:returns: `WebVTTStyleBlock` instance
"""
match = cls.STYLE_PATTERN.match('\n'.join(lines))
return cls(text=match.group(1).strip() if match else '')
@staticmethod
def format_lines(lines: typing.List[str]) -> typing.List[str]:
"""
Return the lines for a style block.
:param lines: style lines
:returns: list of lines for a style block
"""
return ['STYLE', *lines]
def parse(
lines: typing.Sequence[str]
) -> ParserOutput:
"""
Parse VTT captions from lines of text.
:param lines: lines of text
:returns: object `ParserOutput` with all parsed items
"""
if not is_valid_content(lines):
raise MalformedFileError('Invalid format')
return parse_items(lines)
def is_valid_content(lines: typing.Sequence[str]) -> bool:
"""
Validate lines of text for valid VTT content.
:param lines: lines of text
:returns: true for a valid VTT content
"""
return bool(lines and lines[0].startswith('WEBVTT'))
def parse_items(
lines: typing.Sequence[str]
) -> ParserOutput:
"""
Parse items from the text.
:param lines: lines of text
:returns: an object `ParserOutput` with all parsed items
"""
header_comments: typing.List[str] = []
items: typing.List[typing.Union[Caption, Style]] = []
comments: typing.List[WebVTTCommentBlock] = []
for block_lines in utils.iter_blocks_of_lines(lines):
item = parse_item(block_lines)
if item:
item.comments = [comment.text for comment in comments]
comments = []
items.append(item)
elif WebVTTCommentBlock.is_valid(block_lines):
comments.append(WebVTTCommentBlock.from_lines(block_lines))
if items:
header_comments, items[0].comments = items[0].comments, header_comments
return ParserOutput.from_data(
{'items': items,
'header_comments': header_comments,
'footer_comments': [comment.text for comment in comments]
}
)
def parse_item(
lines: typing.Sequence[str]
) -> typing.Union[Caption, Style, None]:
"""
Parse an item from lines of text.
:param lines: lines of text
:returns: An item (Caption or Style) if found, otherwise None
"""
if WebVTTCueBlock.is_valid(lines):
cue_block = WebVTTCueBlock.from_lines(lines)
return Caption(cue_block.start,
cue_block.end,
cue_block.payload,
cue_block.identifier
)
if WebVTTStyleBlock.is_valid(lines):
return Style(WebVTTStyleBlock.from_lines(lines).text)
return None
def write(
f: typing.IO[str],
captions: typing.Iterable[Caption],
styles: typing.Iterable[Style],
header_comments: typing.Iterable[str],
footer_comments: typing.Iterable[str]
):
"""
Write captions to an output.
:param f: file or file-like object
:param captions: Iterable of `Caption` objects
:param styles: Iterable of `Style` objects
:param header_comments: the comments for the header
:param footer_comments: the comments for the footer
"""
f.write(
to_str(captions,
styles,
header_comments,
footer_comments
)
)
def to_str(
captions: typing.Iterable[Caption],
styles: typing.Iterable[Style],
header_comments: typing.Iterable[str],
footer_comments: typing.Iterable[str]
) -> str:
"""
Convert captions to a string with webvtt format.
:param captions: the iterable of `Caption` objects
:param styles: the iterable of `Style` objects
:param header_comments: the comments for the header
:param footer_comments: the comments for the footer
:returns: String of the content in WebVTT format.
"""
output = ['WEBVTT']
for comment in header_comments:
output.extend([
'',
*WebVTTCommentBlock.format_lines(comment)
])
for style in styles:
for comment in style.comments:
output.extend([
'',
*WebVTTCommentBlock.format_lines(comment)
])
output.extend([
'',
*WebVTTStyleBlock.format_lines(style.lines)
])
for caption in captions:
for comment in caption.comments:
output.extend([
'',
*WebVTTCommentBlock.format_lines(comment)
])
output.extend(WebVTTCueBlock.format_lines(caption))
if not footer_comments:
output.append('')
for comment in footer_comments:
output.extend([
'',
*WebVTTCommentBlock.format_lines(comment)
])
return '\n'.join(output)
|