Note
The documentation is written from Python 3 point of view; a “string” means Unicode string.
pysubs2 is built around SubStation Alpha, the native subtitle format of Aegisub.
SubStation Alpha — supported in two versions:
SubRip — .srt files, format identifier is "srt".
MicroDVD — .sub files, format identifier is "microdvd".
JSON-serialized internal representation, which amounts to ASS. Format identifier is "json".
Alias for SSAFile.load().
Alias for pysubs2.time.make_time().
(r, g, b, a) namedtuple for 8-bit RGB color with alpha channel.
All values are ints from 0 to 255.
Subtitle file in SubStation Alpha format.
This class has a list-like interface which exposes SSAFile.events, list of subtitles in the file:
subs = SSAFile.load("subtitles.srt")
for line in subs:
print(line.text)
subs.insert(0, SSAEvent(start=0, end=make_time(s=2.5), text="New first subtitle"))
del subs[0]
Dict with Aegisub project, ie. [Aegisub Project Garbage].
Format of source subtitle file, if applicable, eg. "srt".
Framerate used when reading the file, if applicable.
Dict with script metadata, ie. [Script Info].
Load subtitle file from given path.
Parameters: |
|
---|---|
Returns: | SSAFile |
Raises: |
Note
pysubs2 may autodetect subtitle format and/or framerate. These values are set as SSAFile.format and SSAFile.fps attributes.
Example
>>> subs1 = pysubs2.load("subrip-subtitles.srt")
>>> subs2 = pysubs2.load("microdvd-subtitles.sub", fps=23.976)
Save subtitle file to given path.
Parameters: |
|
---|---|
Raises: |
Load subtitle file from string.
See SSAFile.load() for full description.
Parameters: | string (str) – Subtitle file in a string. Note that the string must be Unicode (in Python 2). |
---|---|
Returns: | SSAFile |
Example
>>> text = '''
... 1
... 00:00:00,000 --> 00:00:05,000
... An example SubRip file.
... '''
>>> subs = SSAFile.from_string(text)
Get subtitle file as a string.
See SSAFile.save() for full description.
Returns: | str |
---|
Read subtitle file from file object.
See SSAFile.load() for full description.
Note
This is a low-level method. Usually, one of SSAFile.load() or SSAFile.from_string() is preferable.
Parameters: | fp (file object) – A file object, ie. io.TextIOBase instance. Note that the file must be opened in text mode (as opposed to binary). |
---|---|
Returns: | SSAFile |
Write subtitle file to file object.
See SSAFile.save() for full description.
Note
This is a low-level method. Usually, one of SSAFile.save() or SSAFile.to_string() is preferable.
Parameters: | fp (file object) – A file object, ie. io.TextIOBase instance. Note that the file must be opened in text mode (as opposed to binary). |
---|
Shift all subtitles by constant time amount.
Shift may be time-based (the default) or frame-based. In the latter case, specify both frames and fps. h, m, s, ms will be ignored.
Parameters: |
|
---|---|
Raises: | ValueError – Invalid fps or missing number of frames. |
Rescale all timestamps by ratio of in_fps/out_fps.
Can be used to fix files converted from frame-based to time-based with wrongly assumed framerate.
Parameters: |
|
---|---|
Raises: | ValueError – Non-positive framerate given. |
Rename a style, including references to it.
Parameters: |
|
---|---|
Raises: |
|
Merge in styles from other SSAFile.
Parameters: |
|
---|
Equality of two SSAFiles.
Compares SSAFile.info, SSAFile.styles and SSAFile.events. Order of entries in OrderedDicts does not matter. “ScriptType” key in info is considered an implementation detail and thus ignored.
Useful mostly in unit tests. Differences are logged at DEBUG level.
Sort subtitles time-wise, in-place.
A SubStation Event, ie. one subtitle.
In SubStation, each subtitle consists of multiple “fields” like Start, End and Text. These are exposed as attributes (note that they are lowercase; see SSAEvent.FIELDS for a list). Additionaly, there are some convenience properties like SSAEvent.plaintext or SSAEvent.duration.
This class defines an ordering with respect to (start, end) timestamps.
Tip
Use pysubs2.make_time() to get times in milliseconds.
Example:
>>> ev = SSAEvent(start=make_time(s=1), end=make_time(s=2.5), text="Hello World!")
All fields in SSAEvent.
Return a copy of the SSAEvent.
Subtitle duration in milliseconds (read/write property).
Writing to this property adjusts SSAEvent.end. Setting negative durations raises ValueError.
Line effect
Subtitle end time (in milliseconds)
Field-based equality for SSAEvents.
When true, the subtitle is a comment, ie. not visible (read/write property).
Setting this property is equivalent to changing SSAEvent.type to "Dialogue" or "Comment".
Layer number, 0 is the lowest layer (ASS only)
Left margin
Right margin
Vertical margin
(SSA only)
Actor name
Subtitle text as multi-line string with no tags (read/write property).
Writing to this property replaces SSAEvent.text with given plain text. Newlines are converted to \N tags.
Shift start and end times.
See SSAFile.shift() for full description.
Subtitle start time (in milliseconds)
Style name
Text of subtitle (with SubStation override tags)
Line type (Dialogue/Comment)
A SubStation Style.
In SubStation, each subtitle (SSAEvent) is associated with a style which defines its font, color, etc. Like a subtitle event, a style also consists of “fields”; see SSAStyle.FIELDS for a list (note the spelling, which is different from SubStation proper).
Subtitles and styles are connected via an SSAFile they belong to. SSAEvent.style is a string which is (or should be) a key in the SSAFile.styles dict. Note that style name is stored separately; a given SSAStyle instance has no particular name itself.
This class defines equality (equality of all fields).
All fields in SSAStyle.
Numpad-style alignment, eg. 7 is “top left” (that is, ASS alignment semantics)
Old, unused SSA-only field
Rotation (ASS only)
Back, ie. shadow color (pysubs2.Color instance)
Bold
Border style
Charset
Font name
Font size (in pixels)
Italic
Left margin (in pixels)
Right margin (in pixels)
Vertical margin (in pixels)
Outline width (in pixels)
Outline color (pysubs2.Color instance)
Primary color (pysubs2.Color instance)
Horizontal scaling (ASS only)
Vertical scaling (ASS only)
Secondary color (pysubs2.Color instance)
Shadow depth (in pixels)
Letter spacing (ASS only)
Strikeout (ASS only)
Tertiary color (pysubs2.Color instance)
Underline (ASS only)
Pattern that matches both SubStation and SubRip timestamps.
Convert frame-based duration to milliseconds.
Parameters: |
|
---|---|
Returns: | Number of milliseconds (rounded to int). |
Raises: | ValueError – fps was negative or zero. |
Convert time to milliseconds.
See pysubs2.time.times_to_ms(). When both frames and fps are specified, pysubs2.time.frames_to_ms() is called instead.
Raises: | ValueError – Invalid fps, or one of frames/fps is missing. |
---|
Example
>>> make_time(s=1.5)
1500
>>> make_time(frames=50, fps=25)
2000
Convert milliseconds to number of frames.
Parameters: |
|
---|---|
Returns: | Number of frames (int). |
Raises: | ValueError – fps was negative or zero. |
Prettyprint milliseconds to [-]H:MM:SS[.mmm]
Handles huge and/or negative times. Non-negative times with fractions=True are matched by pysubs2.time.TIMESTAMP.
Parameters: |
|
---|---|
Returns: | str |
Convert milliseconds to normalized tuple (h, m, s, ms).
Parameters: | ms – Number of milliseconds (may be int, float or other numeric class). Should be non-negative. |
---|---|
Returns: | Named tuple (h, m, s, ms) of ints. Invariants: ms in range(1000) and s in range(60) and m in range(60) |
Convert hours, minutes, seconds to milliseconds.
Arguments may be positive or negative, int or float, need not be normalized (s=120 is okay).
Returns: | Number of milliseconds (rounded to int). |
---|
Convert groups from pysubs2.time.TIMESTAMP match to milliseconds.
Example
>>> timestamp_to_ms(TIMESTAMP.match("0:00:00.42").groups())
420
Subtitle format is ambiguous or unknown.
Base class for pysubs2 exceptions.
Framerate was not specified and couldn’t be inferred otherwise.
File extension does not pertain to any known subtitle format.
Unknown subtitle format identifier (ie. string like "srt").
Note
This submodule contains pysubs2 internals. It’s mostly of interest if you’re looking to implement a subtitle format not supported by the library. In that case, have a look at pysubs2.formats.FormatBase.
Dict mapping file extensions to format identifiers.
Dict mapping format identifiers to implementations (FormatBase subclasses).
Return format identifier for given fragment or raise FormatAutodetectionError.
Format identifier -> file extension
Format identifier -> format class (ie. subclass of FormatBase)
File extension -> format identifier
Base class for subtitle format implementations.
How to implement a new subtitle format:
After finishing these steps, you can call SSAFile.load() and SSAFile.save() with your format, including autodetection from content and file extension (if you provided these).
Load subtitle file into an empty SSAFile.
If the parser autodetects framerate, set it as subs.fps.
Parameters: |
|
---|---|
Returns: | None |
Raises: | pysubs2.exceptions.UnknownFPSError – Framerate was not provided and cannot be detected. |
Return format identifier of recognized format, or None.
Parameters: | text (str) – Content of subtitle file. When the file is long, this may be only its first few thousand characters. |
---|---|
Returns: | format identifier (eg. "srt") or None (unknown format) |
Write SSAFile into a file.
If you need framerate and it is not passed in keyword arguments, use subs.fps.
Parameters: |
|
---|---|
Returns: | None |
Raises: | pysubs2.exceptions.UnknownFPSError – Framerate was not provided and subs.fps is None. |