webvtt-py package reference

webvtt.webvtt

WebVTT module.

class webvtt.webvtt.WebVTT(*args: NoReturn, file: str | None = None, captions: List[Caption] | None = None, styles: List[Style] | None = None, header_comments: List[str] | None = None, footer_comments: List[str] | None = None, header_text: str | None = None, metadata: List[str] | None = None, regions: List[Region] | None = None)

Parse captions in WebVTT format and also from other formats like SRT.

To read WebVTT:

WebVTT.read(‘captions.vtt’)

For other formats:

WebVTT.from_srt(‘captions.srt’) WebVTT.from_sbv(‘captions.sbv’)

change_framerate(from_fps: float | Fraction, to_fps: float | Fraction)

Change the timing of the captions from one frame rate to another.

Useful when the captions were timed for a video with a different frame rate, e.g. change_framerate(25, 23.976) for captions of a 25 fps video played with a 23.976 fps one. Times are multiplied by from_fps / to_fps and rounded to the nearest millisecond, halves away from zero. Frame rates are read as written, and exact rates such as Fraction(24000, 1001) for NTSC can be given as a fractions.Fraction.

Parameters:
  • from_fps – the frame rate the captions are timed for, a number or a fractions.Fraction

  • to_fps – the frame rate of the video, a number or a fractions.Fraction

Raises:
  • TypeError – if a frame rate is not a number

  • ValueError – if a frame rate is not finite or not above zero, or a caption would be moved after the largest timestamp, leaving the captions unchanged

property content: str

Return the webvtt captions as string.

This property is useful in cases where the webvtt content is needed but no file-like destination is required. Storage in DB for instance.

Raises:

ValueError – if the header text or metadata are not valid, or the text of a caption, style or comment could not be read back

classmethod from_buffer(buffer: Iterable[str] | BinaryIO, format: str = 'vtt', strict: bool = False, encoding: str | None = None) → WebVTT

Read WebVTT captions from a file-like object.

Such file-like object may be the return of an io.open call, in text or binary mode, io.StringIO or io.BytesIO object, tempfile.TemporaryFile object, etc. Binary data is decoded with the encoding of its Byte Order Mark, if any, or else with encoding.

The name of the file-like object is kept as the file to save to when it is a path, so a file-like object without one, such as standard input, a file opened from a file descriptor or an io.BytesIO object, gives captions without a file, as when they are not read from a file.

Parameters:
  • buffer – the file-like object to read captions from, or an iterable of lines

  • format – the format of the data (vtt, srt or sbv)

  • strict – raise an error on blocks that are not valid WebVTT instead of ignoring them, only for the vtt format, as SRT and SBV have no strict parsing

  • encoding – encoding of binary data without a Byte Order Mark, UTF-8 by default. For the srt format, save_as_srt saves in the same encoding

Returns:

a WebVTT instance

Raises:
  • MalformedFileError – if the data is not in the right format

  • MalformedCaptionError – if a caption has an invalid timestamp, or if strict and a block is not valid WebVTT

  • ValueError – if the format is not supported, or strict is given for the srt or sbv format

  • UnicodeDecodeError – if binary data cannot be decoded

  • TypeError – if the buffer is a string or bytes, use from_string to read a string or io.BytesIO to read bytes

classmethod from_sbv(file: str, encoding: str | None = None) → WebVTT

Read captions from a file in YouTube SBV format.

Parameters:
  • file – the file path

  • encoding – encoding of a file without a Byte Order Mark, UTF-8 by default. It is only used for reading, as WebVTT files are saved in UTF-8 unless another encoding is given

Returns:

a WebVTT instance

Raises:
classmethod from_srt(file: str, encoding: str | None = None) → WebVTT

Read captions from a file in SubRip format.

Parameters:
  • file – the file path

  • encoding – encoding of a file without a Byte Order Mark, UTF-8 by default. save_as_srt saves in the same encoding, while save saves WebVTT in UTF-8 unless another encoding is given

Returns:

a WebVTT instance

Raises:
classmethod from_string(string: str, strict: bool = False) → WebVTT

Read captions from a string.

Parameters:
  • string – the captions in a string

  • strict – raise an error on blocks that are not valid WebVTT instead of ignoring them

Returns:

a WebVTT instance

Raises:
iter_slice(start: str | None = None, end: str | None = None) → Generator[Caption, None, None]

Iterate a slice of the captions based on a time range.

Only the captions within the range are returned: a caption that starts before start or ends after end is left out.

Parameters:
  • start – start timestamp of the range

  • end – end timestamp of the range

Returns:

generator of Captions

classmethod read(file: str, encoding: str | None = None, strict: bool = False) → WebVTT

Read a WebVTT captions file.

Parameters:
  • file – the file path

  • encoding – encoding of a file without a Byte Order Mark, UTF-8 by default. It is only used for reading, as WebVTT files are saved in UTF-8 unless another encoding is given

  • strict – raise an error on blocks that are not valid WebVTT instead of ignoring them

Returns:

a WebVTT instance

Raises:
classmethod read_buffer(buffer: Iterator[str]) → WebVTT

Read WebVTT captions from a file-like object.

This method is DEPRECATED. Use from_buffer instead.

Such file-like object may be the return of an io.open call, io.StringIO object, tempfile.TemporaryFile object, etc.

Parameters:

buffer – the file-like object to read captions from

Returns:

a WebVTT instance

save(output: str | None = None, encoding: str | None = None, add_bom: bool | None = None)

Save the WebVTT captions to a file.

The content is encoded before the file is opened, so an error while encoding, such as a character the encoding cannot write, leaves an existing file unchanged.

Parameters:
  • output – destination path of the file, with .vtt added when it has no extension, or a folder to save the file there with the name of the file that was read. Without it, the file is saved to the file attribute, with its extension replaced by .vtt unless it is .vtt or .webvtt

  • encoding – encoding of the file, by default the encoding attribute: the encoding of the Byte Order Mark of the file that was read, or UTF-8

  • add_bom – save the file with Byte Order Mark, or without it if false. By default, the Byte Order Mark of the file that was read is kept

Raises:
  • MissingFilenameError – if output cannot be determined

  • LookupError – if the encoding is not known

  • ValueError – if the header text or metadata are not valid, or the text of a caption, style or comment could not be read back, or add_bom is true and the encoding has no Byte Order Mark, or false and the encoding always writes one, such as utf-16, leaving an existing file unchanged

save_as_srt(output: str | None = None, encoding: str | None = None, keep_formatting: bool = False)

Save the WebVTT captions to a file in SubRip format.

The content is encoded before the file is opened, so an error while encoding, such as a character the encoding cannot write, leaves an existing file unchanged.

Parameters:
  • output – destination path of the file, with .srt added when it has no extension, or a folder to save the file there with the name of the file that was read. Without it, the file is saved to the file attribute, with its extension replaced by .srt unless it is .srt

  • encoding – encoding of the file, by default the encoding given to read the captions from SRT, or UTF-8

  • keep_formatting – keep bold, italic, underline and the colours of the cue classes in the styles, instead of removing the cue tags

Raises:

MissingFilenameError – if output cannot be determined

shift(offset: float | timedelta, start: str | None = None)

Shift the start and end time of the captions.

The offset is rounded to the nearest millisecond, halves away from zero, and a timestamp that would fall before zero is set to 00:00:00.000.

Parameters:
  • offset – a number of seconds or a timedelta, negative values move the captions earlier

  • start – only shift the captions starting at or after this timestamp

Raises:
  • TypeError – if the offset is not a number or a timedelta

  • ValueError – if the offset is not finite, or would move a time after the largest timestamp, leaving the captions unchanged

  • MalformedCaptionError – if the start timestamp is not valid

sync(*points: Sequence[str | Timestamp | float | timedelta])

Synchronize the captions to two or more points.

Each point is a (from, to) pair: the time from in the captions is moved to to. Times between two points are moved along the line between them, which fixes captions that drift out of sync, and times before the first or after the last point along the line of the outermost points. Start and end times are rounded to the nearest millisecond, halves away from zero, and a time that would fall before zero is set to 00:00:00.000.

Parameters:

points – (from, to) pairs, each time a timestamp string, a Timestamp, a number of seconds or a timedelta

Raises:
  • MalformedCaptionError – if a timestamp string is not valid

  • TypeError – if a point is not a pair of supported values

  • ValueError – if there are fewer than two points, two points have the same from time, the to times are not in the same order as the from times, a time is not finite, is before zero or is after the largest timestamp, or a caption would be moved after the largest timestamp, leaving the captions unchanged

property total_length

Return the total length of the captions in seconds.

It is the time from the start of the first caption to the end of the last one, in whole seconds as the milliseconds of both are left out, so the captions are expected in order of time.

write(f: IO[str], format: str = 'vtt', keep_formatting: bool = False)

Save the WebVTT captions to a file-like object.

Parameters:
  • f – destination file-like object

  • format – the format to use (vtt or srt)

  • keep_formatting – when writing SRT, keep bold, italic, underline and the colours of the cue classes in the styles, instead of removing the cue tags

Raises:

ValueError – if the format is not supported, or when writing WebVTT, the header text or metadata are not valid or the text of a caption, style or comment could not be read back

webvtt.models

Models module.

class webvtt.models.Caption(start: str | None = None, end: str | None = None, text: str | Sequence[str] | None = None, identifier: str | None = None, settings: str | CueSettings | None = None)

Representation of a caption.

property end

Return the end time of the caption.

property end_in_seconds

Return the end time of the caption in seconds.

property raw_text: str

Return the text of the caption (including cue tags).

property settings: CueSettings

Return the cue settings of the caption.

shift(offset: float | timedelta)

Shift the start and end time of the caption.

The offset is rounded to the nearest millisecond, halves away from zero, and a timestamp that would fall before zero is set to 00:00:00.000.

Parameters:

offset – a number of seconds or a timedelta, negative values move the caption earlier

Raises:
  • TypeError – if the offset is not a number or a timedelta

  • ValueError – if the offset is not finite, or would move a time after the largest timestamp, leaving the caption unchanged

property start

Return the start time of the caption.

property start_in_seconds: int

Return the start time of the caption in seconds.

property text: str

Return the text of the caption (without cue tags).

property voice: str | None

Return the voice span if present.

class webvtt.models.CueSettings(*, vertical: str | None = None, line: str | None = None, position: str | None = None, size: str | None = None, align: str | None = None, region: str | None = None)

Representation of the cue settings of a caption.

The settings are kept as written and in their original order, so they are written back the same, including those that are not valid or not known. A property returns the value of its setting when it is valid, the last valid one when it is repeated, and validates a new value.

property align

Text alignment, start, center, end, left or right.

classmethod from_string(value: str, strict: bool = False) → CueSettings

Return a CueSettings instance from the settings of a cue.

Parameters:
  • value – the cue settings, e.g. line:0 align:start

  • strict – raise an error on settings that are not known, not valid or repeated instead of keeping them

Returns:

a CueSettings instance

Raises:

MalformedCaptionError – if the value is not a string, or if strict and a setting is not known, not valid or repeated

property line

Line position, as a line number or a percentage with an optional alignment.

property position

Position as a percentage with an optional alignment.

property region

Identifier of a region.

property size

Size as a percentage.

property vertical

Writing direction, rl or lr.

class webvtt.models.Region(*, id: str | None = None, width: str | None = None, lines: str | None = None, regionanchor: str | None = None, viewportanchor: str | None = None, scroll: str | None = None)

Representation of a region.

A region is an area of the video where captions are rendered, defined in a REGION block of the header and referred to by its identifier in the region cue setting of the captions.

The settings are kept as written and in their original order, so they are written back the same, including those that are not valid or not known. A property returns the value of its setting when it is valid, the last valid one when it is repeated, and validates a new value.

classmethod from_string(value: str, strict: bool = False) → Region

Return a Region instance from the settings of a region block.

Parameters:
  • value – the region settings separated by spaces or line breaks, e.g. id:fred width:40%

  • strict – raise an error on settings that are not known, not valid or repeated instead of keeping them

Returns:

a Region instance

Raises:

MalformedRegionError – if the value is not a string or contains -->, which cannot be in a region block, or if strict and a setting is not known, not valid or repeated

property id

Identifier of the region.

property lines

Number of lines of text.

property regionanchor

Point of the region anchored to the video, as two percentages.

property scroll

up if the lines scroll up.

property viewportanchor

Point of the video the region is anchored to, as two percentages.

property width

Width as a percentage of the video.

class webvtt.models.Style(text: str | List[str])

Representation of a style.

property text

Return the text of the style.

class webvtt.models.Timestamp(hours: int = 0, minutes: int = 0, seconds: int = 0, milliseconds: int = 0)

Representation of a timestamp.

classmethod from_seconds(value: float) → Timestamp

Return a Timestamp instance from a number of seconds.

The value is rounded to the nearest millisecond as written, with halves rounded up, so 1.9996 and 1.9995 are read as 00:00:02.000.

Parameters:

value – the timestamp in seconds

Returns:

a Timestamp instance

Raises:

MalformedCaptionError – if the value is not a finite number of seconds greater than or equal to zero, or is after the largest timestamp

classmethod from_string(value: str) → Timestamp

Return a Timestamp instance from a string value.

The fields can be shorter than the WebVTT format requires, as in 0:1:5.2, and the fraction of a second is padded on the right so .2 is read as 200 milliseconds. The hours can have up to 10 digits.

Parameters:

value – the timestamp in [hh:]mm:ss.mmm format

Returns:

a Timestamp instance

Raises:

MalformedCaptionError – if the timestamp is not valid

in_milliseconds() → int

Return the timestamp in milliseconds.

in_seconds() → int

Return the timestamp in seconds.

The milliseconds are left out, use in_milliseconds for the exact value.

to_tuple() → Tuple[int, int, int, int]

Return the timestamp in tuple form.

webvtt.segmenter

Segmenter module.

webvtt.segmenter.segment(webvtt_path: str | WebVTT, output: str, seconds: int = 10, mpegts: int = 900000, *, overwrite: bool = False, duration: str | Timestamp | float | timedelta | None = None)

Segment a WebVTT captions file, or captions already read.

Each segment has the styles and regions of the file and the captions shown during the segment, with their identifiers and cue settings. Comments are not written to the segments.

Parameters:
  • webvtt_path – the path to the file, or a WebVTT instance, such as captions edited or read from another format, which is not changed

  • output – the path to the destination folder

  • seconds – the number of seconds for each segment, a whole number above zero

  • mpegts – value for the MPEG-TS, from 0 to 2**33 - 1

  • overwrite – replace the playlist and segments of an earlier run in the destination folder, deleting the segments the new playlist does not have. Other files in the folder are left alone.

  • duration – the length of the media, as a timestamp, a number of seconds or a timedelta, so the playlist covers all of it and its last segment ends with it. Without it, the playlist ends with the segment of the last caption, and every segment lasts the number of seconds.

Raises:
  • TypeError – if seconds or mpegts is not an integer, or duration is not of a supported type

  • ValueError – if seconds is not above zero, mpegts is out of range, duration is not above zero or a caption does not start before it

  • FileExistsError – if the destination folder has the playlist or segments of an earlier run and overwrite is false

webvtt.segmenter.slice_segments(captions: Sequence[Caption], seconds: int, *, duration: str | Timestamp | float | timedelta | None = None) → List[List[Caption]]

Slice segments of captions based on seconds per segment.

Parameters:
  • captions – the captions

  • seconds – seconds per segment, a whole number above zero

  • duration – the length of the media, as a timestamp, a number of seconds or a timedelta, so the segments cover all of it, with a caption ending after it in the last segment. Without it, the segments end with the segment of the last caption.

Returns:

list of lists of Caption objects

Raises:
  • TypeError – if seconds is not an integer, or duration is not of a supported type

  • ValueError – if seconds is not above zero, duration is not above zero or a caption does not start before it

webvtt.segmenter.write_manifest(output_folder: Path, segments: Iterable[Iterable[Caption]], seconds: int, *, duration: str | Timestamp | float | timedelta | None = None)

Write the manifest in the output folder.

Parameters:
  • output_folder – folder where the manifest will be stored

  • segments – the segments of Caption objects

  • seconds – the seconds per segment, a whole number above zero

  • duration – the length of the media, as a timestamp, a number of seconds or a timedelta, for the duration of the last segment, which ends with it. Without it, every segment lasts the number of seconds.

Raises:
  • TypeError – if seconds is not an integer, or duration is not of a supported type

  • ValueError – if seconds is not above zero, or duration is not above zero or does not end in the last segment

webvtt.segmenter.write_segments(output_folder: Path, segments: Iterable[Iterable[Caption]], mpegts: int, styles: Iterable[Style] = (), regions: Iterable[Region] = ())

Write the segments to the output folder.

Every segment is built before any is written, so a caption or style that cannot be written leaves the files of the folder unchanged.

Parameters:
  • output_folder – folder where the segment files will be stored

  • segments – the segments of Caption objects

  • mpegts – value for the MPEG-TS, from 0 to 2**33 - 1

  • styles – the styles written to every segment

  • regions – the regions written to every segment, which the region cue setting of the captions refers to

Raises:
  • TypeError – if mpegts is not an integer

  • ValueError – if mpegts is out of range, or the text of a caption or style could not be read back

webvtt.cli

CLI module.

webvtt.cli.main(argv: Sequence | None = None)

Segment, shift or sync a WebVTT file from command line.

Parameters:

argv – command line arguments

Formats

Each supported format has its own module that takes care of parsing and, when supported, writing captions.

webvtt.vtt

VTT format module.

class webvtt.vtt.ParserOutput(styles: ~typing.List[~webvtt.models.Style], captions: ~typing.List[~webvtt.models.Caption], header_comments: ~typing.List[str], footer_comments: ~typing.List[str], header_text: str = '', metadata: ~typing.List[str] = <factory>, regions: ~typing.List[~webvtt.models.Region] = <factory>)

Output of parser.

classmethod from_data(data: Mapping[str, Any]) → ParserOutput

Return a ParserOutput instance from the provided data.

Parameters:

data – data from the parser

Returns:

an instance of ParserOutput

class webvtt.vtt.WebVTTCommentBlock(text: str)

Representation of a comment block.

static format_lines(lines: str) → List[str]

Return the lines for a comment block.

Parameters:

lines – comment lines

Returns:

list of lines for a comment block

classmethod from_lines(lines: Iterable[str]) → WebVTTCommentBlock

Create a WebVTTCommentBlock from lines of text.

Parameters:

lines – the lines of text

Returns:

WebVTTCommentBlock instance

classmethod is_valid(lines: Sequence[str]) → bool

Validate the lines for a match of a comment block.

A comment starts with NOTE followed by a space, a tab or the end of the line, and no line contains -->, as WebVTT reads a line with --> as cue timings.

Parameters:

lines – the lines to be validated

Returns:

true for a matching comment block

class webvtt.vtt.WebVTTCueBlock(identifier, start, end, payload, settings='')

Representation of a cue timing block.

static format_lines(caption: Caption) → List[str]

Return the lines for a cue block.

Parameters:

caption – the Caption instance

Returns:

list of lines for a cue block

classmethod from_lines(lines: Iterable[str]) → WebVTTCueBlock

Create a WebVTTCueBlock from lines of text.

Parameters:

lines – the lines of text

Returns:

WebVTTCueBlock instance

classmethod is_valid(lines: Sequence[str], strict: bool = False) → bool

Validate the lines for a match of a cue time block.

Timestamps with fields shorter than the WebVTT format requires, as in 0:0:13.540, are accepted unless strict.

Parameters:
  • lines – the lines to be validated

  • strict – only accept timestamps in the WebVTT format

Returns:

true for a matching cue time block

class webvtt.vtt.WebVTTRegionBlock

Representation of a region block.

static format_lines(region: Region) → List[str]

Return the lines for a region block.

Parameters:

region – the Region instance

Returns:

list of lines for a region block, with a setting per line

static is_valid(lines: Sequence[str]) → bool

Validate the lines for a match of a region block.

The first line is REGION, optionally followed by whitespace, and the settings of the region follow in the next lines.

Parameters:

lines – the lines to be validated

Returns:

true for a matching region block

class webvtt.vtt.WebVTTStyleBlock(text: str)

Representation of a style block.

static format_lines(lines: List[str]) → List[str]

Return the lines for a style block.

Parameters:

lines – style lines

Returns:

list of lines for a style block

classmethod from_lines(lines: Iterable[str]) → WebVTTStyleBlock

Create a WebVTTStyleBlock from lines of text.

Parameters:

lines – the lines of text

Returns:

WebVTTStyleBlock instance

classmethod is_valid(lines: Sequence[str]) → bool

Validate the lines for a match of a style block.

The first line is STYLE, optionally followed by whitespace, and the style sheet follows in the next lines.

Parameters:

lines – the lines to be validated

Returns:

true for a matching style block

webvtt.vtt.is_valid_content(lines: Sequence[str]) → bool

Validate lines of text for valid VTT content.

Parameters:

lines – lines of text

Returns:

true for a valid VTT content

webvtt.vtt.parse(lines: Sequence[str], strict: bool = False) → ParserOutput

Parse VTT captions from lines of text.

Parameters:
  • lines – lines of text

  • strict – raise an error on blocks that are not valid WebVTT instead of ignoring them

Returns:

object ParserOutput with all parsed items

Raises:
  • MalformedFileError – if the content is not in WebVTT format, or if strict and “WEBVTT” is not followed by a space, a tab or the end of the first line

  • MalformedCaptionError – if strict and a block is not valid WebVTT

webvtt.vtt.parse_item(lines: Sequence[str], strict: bool = False, seen_cue: bool = False) → Caption | Style | Region | None

Parse an item from lines of text.

Parameters:
  • lines – lines of text

  • strict – only accept cue timestamps in the WebVTT format and raise an error for cues with an invalid timestamp or cue setting, or an end time that is not after the start time, for regions with an invalid region setting, and for regions and styles after a cue

  • seen_cue – true if a cue came before, so the lines cannot be a region or a style, as they are only defined before the first cue

Returns:

An item (Caption, Style or Region) if found, otherwise None

Raises:
  • MalformedCaptionError – if strict and a cue has an invalid timestamp or a cue setting that is not known, not valid or repeated, or an end time that is not after the start time, or a style comes after a cue

  • MalformedRegionError – if strict and a region has a region setting that is not known, not valid or repeated, or comes after a cue

webvtt.vtt.parse_items(lines: Sequence[str], strict: bool = False) → ParserOutput

Parse items from the text.

The lines can start with the header block, which is not an item.

Parameters:
  • lines – lines of text

  • strict – raise an error on blocks that are not valid WebVTT instead of ignoring them

Returns:

an object ParserOutput with all parsed items

Raises:

MalformedCaptionError – if strict and the header contains “–>”, or another block is not a valid cue, comment, style or region

webvtt.vtt.to_str(captions: Iterable[Caption], styles: Iterable[Style], header_comments: Iterable[str], footer_comments: Iterable[str], header_text: str = '', metadata: Iterable[str] = (), regions: Iterable[Region] = ()) → str

Convert captions to a string with webvtt format.

Parameters:
  • captions – the iterable of Caption objects

  • styles – the iterable of Style objects

  • header_comments – the comments for the header

  • footer_comments – the comments for the footer

  • header_text – the text following “WEBVTT” in the first line

  • metadata – the metadata lines of the header

  • regions – the iterable of Region objects

Returns:

String of the content in WebVTT format.

Raises:

ValueError – if the header text or metadata are not valid, or the text of a caption, style or comment could not be read back

webvtt.vtt.write(f: IO[str], captions: Iterable[Caption], styles: Iterable[Style], header_comments: Iterable[str], footer_comments: Iterable[str], header_text: str = '', metadata: Iterable[str] = (), regions: Iterable[Region] = ())

Write captions to an output.

Parameters:
  • f – file or file-like object

  • captions – Iterable of Caption objects

  • styles – Iterable of Style objects

  • header_comments – the comments for the header

  • footer_comments – the comments for the footer

  • header_text – the text following “WEBVTT” in the first line

  • metadata – the metadata lines of the header

  • regions – Iterable of Region objects

Raises:

ValueError – if the header text or metadata are not valid, or the text of a caption, style or comment could not be read back

webvtt.srt

SRT format module.

class webvtt.srt.SRTCueBlock(index: str | None, start: str, end: str, payload: Sequence[str])

Representation of a cue timing block.

classmethod from_lines(lines: Sequence[str]) → SRTCueBlock

Create a SRTCueBlock from lines of text.

Parameters:

lines – the lines of text

Returns:

SRTCueBlock instance

classmethod is_valid(lines: Sequence[str]) → bool

Validate the lines for a match of a cue time block.

The cue index is optional, as most SRT players read cues without one.

Parameters:

lines – the lines to be validated

Returns:

true for a matching cue time block

webvtt.srt.is_valid_content(lines: Sequence[str]) → bool

Validate lines of text for valid SRT content.

The content is valid when it starts with a cue index and the cue timings, after any blank lines. The first cue can have no text.

Parameters:

lines – lines of text

Returns:

true for a valid SRT content

webvtt.srt.parse(lines: Sequence[str]) → List[Caption]

Parse SRT captions from lines of text.

Parameters:

lines – lines of text

Returns:

list of Caption objects

Raises:

MalformedFileError – if the content is not in SRT format

webvtt.srt.parse_captions(lines: Sequence[str]) → List[Caption]

Parse captions from the text.

Blocks of text that do not start a cue are taken as part of the text of the previous cue, as some files have empty lines in the caption text.

Parameters:

lines – lines of text

Returns:

list of Caption objects

webvtt.srt.write(f: IO[str], captions: Iterable[Caption], styles: Iterable[Style] | None = None)

Write captions to an output.

Captions without text, such as text of blank lines or only of cue tags, are left out, as a cue without text cannot be read back from SRT, and the others are numbered consecutively.

Parameters:
  • f – file or file-like object

  • captions – Iterable of Caption objects

  • styles – Iterable of Style objects to keep the formatting of the cue text, or None to write the text without cue tags

webvtt.sbv

SBV format module.

class webvtt.sbv.SBVCueBlock(start: str, end: str, payload: Sequence[str])

Representation of a cue timing block.

classmethod from_lines(lines: Sequence[str]) → SBVCueBlock

Create a SBVCueBlock from lines of text.

Parameters:

lines – the lines of text

Returns:

SBVCueBlock instance

classmethod is_valid(lines: Sequence[str]) → bool

Validate the lines for a match of a cue time block.

Parameters:

lines – the lines to be validated

Returns:

true for a matching cue time block

webvtt.sbv.parse(lines: Sequence[str]) → List[Caption]

Parse SBV captions from lines of text.

Parameters:

lines – lines of text

Returns:

list of Caption objects

Raises:

MalformedFileError – if the content is not in SBV format

webvtt.utils

Utils module.

class webvtt.utils.FileWrapper(file_path: str, mode: str | None = None, encoding: str | None = None)

File handling functionality with built-in support for Byte OrderMark.

static detect_bom_encoding(file_path: str) → str | None

Detect the encoding of a file based on the presence of the BOM.

Parameters:

file_path – path to the file

Returns:

the encoding if BOM is found or None.

classmethod open(file_path: str, mode: str | None = None, encoding: str | None = None) → FileWrapper

Open a file.

Parameters:
  • file_path – path to the file

  • mode – mode in which the file is opened

  • encoding – name of the encoding used to decode the file

webvtt.utils.iter_blocks_of_lines(lines: Iterable[str]) → Generator[List[str], None, None]

Iterate blocks of text.

Parameters:

lines – lines of text.

webvtt.errors

Errors module.

exception webvtt.errors.MalformedCaptionError

Bases: WebVTTError, ValueError

Caption not in the right format.

Raised when a timestamp is not valid, e.g. when creating a Caption, setting its start or end or reading a file that contains a cue with an invalid timestamp. Also raised when a cue setting is not valid, e.g. when setting one of CueSettings.

exception webvtt.errors.MalformedFileError

Bases: WebVTTError, ValueError

File is not in the right format.

Raised when reading captions whose content is not valid for the expected format (WebVTT, SRT or SBV), e.g. a WebVTT file missing the WEBVTT header.

exception webvtt.errors.MalformedRegionError

Bases: MalformedCaptionError

Region not in the right format.

Raised when a region setting is not valid, e.g. when creating a Region or setting one of its settings, or when reading a file with strict parsing that contains a region with a setting that is not valid or a region after the first cue. It is a subclass of MalformedCaptionError, so catching that error also catches it.

exception webvtt.errors.MissingFilenameError

Bases: WebVTTError

Missing a filename when saving to disk.

Raised when saving captions without an output path and the WebVTT instance was not read from a file.

exception webvtt.errors.WebVTTError

Bases: Exception

Base class of the errors of webvtt-py.

Catching it catches every error defined in this module.