### MPL2 example file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example content of an MPL2 subtitle file.
```text
[789][1234] Example subtitle
```
--------------------------------
### WebVTT example file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example content of a .vtt WebVTT subtitle file.
```text
WEBVTT
1
00:00:00.000 --> 00:01:00.000
Example subtitle
```
--------------------------------
### TMP example file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example content of a TMP subtitle file.
```text
00:00:12:Example subtitle
00:00:14:Another subtitle
```
--------------------------------
### SAMI format example
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example of a SAMI subtitle file structure.
```xml
...
Example subtitle
```
--------------------------------
### SubStation Alpha example file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example content of an .ass or .ssa SubStation Alpha subtitle file.
```text
[Script Info]
...
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:01:00.00,Default,,0,0,0,,Example subtitle.
```
--------------------------------
### TTML example file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example content of a TTML XML-based subtitle file.
```xml
...
```
--------------------------------
### Bash: Install pysubs2 and use CLI for batch conversion and retiming
Source: https://pysubs2.readthedocs.io/en/latest/_sources/index.rst.txt
Shows how to install pysubs2 via pip and use the command-line tool to shift all SRT files by 0.3 seconds and convert all ASS files to SRT format.
```bash
pip install pysubs2
pysubs2 --shift 0.3s *.srt
pysubs2 --to srt *.ass
```
--------------------------------
### SubRip (SRT) example file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example content of a .srt SubRip subtitle file.
```text
1
00:00:00,000 --> 00:01:00,000
Example subtitle
```
--------------------------------
### MicroDVD format example
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example of a MicroDVD subtitle file using frame-based timing.
```text
{1}{1}23.976
{10}{20}Example subtitle
```
--------------------------------
### pysubs2 CLI usage examples
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Examples of common pysubs2 CLI commands for format conversion, cleaning, retiming, and framerate transformation. Note that by default the script works in-place and overwrites original files; use -o/--output-dir or pipe mode to avoid this.
```bash
pysubs2 --to srt *.ass
```
```bash
pysubs2 --to srt --clean *.ass
```
```bash
pysubs2 --to microdvd --fps 23.976 *.ass
```
```bash
pysubs2 --shift 0.3s *.srt
```
```bash
pysubs2 --shift 0.3s retimed_file.srt
```
```bash
pysubs2 --shift-back 0.3s --output-dir retimed *.srt
```
```bash
pysubs2 --transform-framerate 25 23.976 *.srt
```
--------------------------------
### pysubs2 CLI Usage Examples
Source: https://pysubs2.readthedocs.io/en/latest/cli.html
Common command-line patterns for converting, cleaning, retiming, and adjusting framerates of subtitle files.
```bash
python -m pysubs2 --to srt *.ass
python -m pysubs2 --to srt --clean *.ass
python -m pysubs2 --to microdvd --fps 23.976 *.ass
python -m pysubs2 --shift 0.3s *.srt
python -m pysubs2 --shift 0.3s retimed_file.srt
python -m pysubs2 --shift-back 0.3s --output-dir retimed *.srt
python -m pysubs2 --transform-framerate 25 23.976 *.srt
```
--------------------------------
### OpenAI Whisper JAX format example
Source: https://pysubs2.readthedocs.io/en/latest/_sources/supported-formats.rst.txt
Example of a Whisper JAX transcription file format.
```text
[01:14.500 -> 01:15.500] Example subtitle
```
--------------------------------
### Load, style, and save subtitles with pysubs2
Source: https://pysubs2.readthedocs.io/en/latest/_sources/tutorial.rst.txt
This example shows how to load two subtitle files, define custom styles for them, merge them into a single SSAFile, and save the output as an ASS file.
```python
subs_en = pysubs2.load("subs.en.srt") # read input subtitles in SRT format
subs_it = pysubs2.load("subs.it.srt")
subs = SSAFile()
subs.styles = {
"bottom": SSAStyle(alignment=Alignment.BOTTOM_CENTER, primarycolor=Color(255, 255, 0)),
"top": SSAStyle(alignment=Alignment.TOP_CENTER, primarycolor=pysubs2.Color(0, 128, 128)),
}
for e in subs_it:
e.style = "bottom"
subs.append(e)
for e in subs_en:
e.style = "top"
subs.append(e)
subs.save("subs.ass") # write subtitles in ASS format (supports formatting)
```
--------------------------------
### SSAFile.sort
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Sorts the events in the file by start time.
```APIDOC
## SSAFile.sort
### Description
Sorts the events in the file by start time.
### Method
Instance Method
### Signature
`SSAFile.sort()`
### Parameters
None
### Returns
- **None** - This method modifies the file in place.
### Example
```python
subs.sort()
```
```
--------------------------------
### Create an SSAEvent instance
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Initializes a new subtitle event using the make_time helper to define start and end timestamps in milliseconds.
```python
>>> ev = SSAEvent(start=make_time(s=1), end=make_time(s=2.5), text="Hello World!")
```
--------------------------------
### pysubs2.formats.get_format_identifier(ext: str) -> str
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Maps a file extension to its corresponding format identifier. For example, '.srt' returns 'srt'.
```APIDOC
## pysubs2.formats.get_format_identifier(ext: str) -> str
### Description
File extension -> format identifier.
### Method
Function call
### Parameters
- **ext** (str) - Required - The file extension including the dot (e.g., '.srt').
### Returns
- **str** - The format identifier (e.g., 'srt').
```
--------------------------------
### Handle character encoding errors
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Shows an example of a UnicodeDecodeError that occurs when reading a file with an incompatible encoding.
```python
>>> import pysubs2
>>> subs = pysubs2.load("subtitles.srt")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf8 in position 110: invalid start byte
```
--------------------------------
### Python: Load, shift, and edit subtitles with pysubs2
Source: https://pysubs2.readthedocs.io/en/latest/_sources/index.rst.txt
Shows the core usage of the pysubs2 library: load a subtitle file, shift it by 2.5 seconds, prepend the \\be1 override tag to each line's text, and save the result. Requires Python 3.12 or newer and the pysubs2 package installed.
```python
import pysubs2
subs = pysubs2.load("my_subtitles.ass", encoding="utf-8")
subs.shift(s=2.5)
for line in subs:
line.text = "{\\be1}" + line.text
subs.save("my_subtitles_edited.ass")
```
--------------------------------
### pysubs2.formats.get_file_extension(format: str) -> str
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Maps a format identifier to its corresponding file extension. For example, 'srt' returns '.srt'.
```APIDOC
## pysubs2.formats.get_file_extension(format: str) -> str
### Description
Format identifier -> file extension.
### Method
Function call
### Parameters
- **format** (str) - Required - The format identifier (e.g., 'srt', 'ass').
### Returns
- **str** - The file extension including the dot (e.g., '.srt').
```
--------------------------------
### Save subtitles as ASS file
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Saves the subtitle object to an ASS file to preserve style information. The example includes reading the file content to verify the generated header and style definitions.
```python
>>> subs.save("modified_subtitles.ass")
>>> with open("modified_subtitles.ass") as fp:
... print(fp.read())
[Script Info]
; Script generated by pysubs2
; https://pypi.python.org/pypi/pysubs2
WrapStyle: 0
ScaledBorderAndShadow: yes
Collisions: Normal
ScriptType: v4.00+
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20.0,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100.0,100.0,0.0,0.0,1,2.0,2.0,2,10,10,10,1
Style: MyStyle,Arial,20.0,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,-1,0,0,100.0,100.0,0.0,0.0,1,2.0,2.0,2,10,10,10,1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:01:00.00,Default,,0,0,0,,Once upon a time,
Dialogue: 0,0:01:00.00,0:02:00.00,MyStyle,,0,0,0,,there was a SubRip file\Nwith two subtitles.
```
--------------------------------
### Create a sample subtitle file
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Initializes a simple SubRip file on the local filesystem for demonstration purposes.
```python
>>> SIMPLE_FILE = """\
... 1
... 00:00:00,000 --> 00:01:00,000
... Once upon a time,
...
... 2
... 00:01:00,000 --> 00:02:00,000
... there was a SubRip file
... with two subtitles.
... """
>>> with open("subtitles.srt", "w") as fp:
... fp.write(SIMPLE_FILE)
```
--------------------------------
### SubstationFormat.from_file()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Loads a SubStation Alpha (ASS/SSA) subtitle file into an SSAFile. Inherits from FormatBase and supports additional reader arguments.
```APIDOC
## SubstationFormat.from_file()
### Description
Loads a SubStation Alpha (ASS/SSA) subtitle file into an SSAFile. See FormatBase.from_file() for details.
### Method
classmethod
### Signature
from_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Unpack[ReaderArgs]) -> None
### Parameters
- **subs** (SSAFile) - Required - An empty SSAFile.
- **fp** (file object) - Required - Text file object, the subtitle file.
- **format** (str) - Required - Format identifier.
- **kwargs** - Optional - Extra options, per ReaderArgs TypedDict.
### ReaderArgs
- **header_notice** (NotRequired[str]) - Optional - Additional header notice.
### Returns
None
```
--------------------------------
### SSAEvent.shift()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Shifts the event's start and end times by a given offset.
```APIDOC
## SSAEvent.shift()
### Description
Shifts the event's start and end times by a given offset.
### Method
Method call
### Endpoint
SSAEvent.shift()
### Parameters
- **h** (int) - Optional - Hours to shift.
- **m** (int) - Optional - Minutes to shift.
- **s** (int) - Optional - Seconds to shift.
- **ms** (int) - Optional - Milliseconds to shift.
- **frames** (int) - Optional - Frames to shift (requires fps).
- **fps** (float) - Optional - Framerate for frames conversion.
### Returns
- None
### Example
```python
event.shift(s=1)
```
```
--------------------------------
### Load Subtitle File from String
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Demonstrates how to parse a SubRip formatted string into an SSAFile object.
```python
>>> text = '''
... 1
... 00:00:00,000 --> 00:00:05,000
... An example SubRip file.
... '''
>>> subs = SSAFile.from_string(text)
```
--------------------------------
### SSAEvent.shift(h, m, s, ms, frames, fps)
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Shifts the start and end times of the subtitle by the specified amounts.
```APIDOC
## SSAEvent.shift(h=0, m=0, s=0, ms=0, frames=None, fps=None)
### Description
Shift start and end times. See SSAFile.shift() for full description.
### Parameters
- **h** (int | float) - Optional - Hours to shift.
- **m** (int | float) - Optional - Minutes to shift.
- **s** (int | float) - Optional - Seconds to shift.
- **ms** (int | float) - Optional - Milliseconds to shift.
- **frames** (int | None) - Optional - Number of frames to shift.
- **fps** (float | None) - Optional - Frames per second, required if frames is used.
### Returns
- **None**
```
--------------------------------
### pysubs2 CLI help output
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
The full usage message and option descriptions as shown by pysubs2 --help. It lists all positional and optional arguments, including format conversion, encoding, framerate, and retiming options.
```text
usage: pysubs2 [-h] [-v] [-f {srt,ass,ssa,microdvd,json,mpl2,tmp,vtt}] [-t {srt,ass,ssa,microdvd,json,mpl2,tmp,vtt}] [--input-enc ENCODING] [--output-enc ENCODING] [--enc-error-handling {strict,surrogateescape}] [--fps FPS] [-o DIR] [--clean] [--verbose]
[--shift TIME | --shift-back TIME | --transform-framerate FPS1 FPS2] [--srt-keep-unknown-html-tags] [--srt-keep-html-tags] [--srt-keep-ssa-tags] [--sub-no-write-fps-declaration]
[FILE ...]
The pysubs2 CLI for processing subtitle files.
https://github.com/tkarabela/pysubs2
positional arguments:
FILE Input subtitle files. Can be in SubStation Alpha (*.ass, *.ssa), SubRip (*.srt), MicroDVD (*.sub) or other supported format. When no files are specified, pysubs2 will work as a pipe, reading from standard input and writing to standard output.
options:
-h, --help show this help message and exit
-v, --version show program's version number and exit
-f {srt,ass,ssa,microdvd,json,mpl2,tmp,vtt}, --from {srt,ass,ssa,microdvd,json,mpl2,tmp,vtt}
By default, subtitle format is detected from the file. This option can be used to skip autodetection and force specific format. Generally, it should never be needed.
-t {srt,ass,ssa,microdvd,json,mpl2,tmp,vtt}, --to {srt,ass,ssa,microdvd,json,mpl2,tmp,vtt}
Convert subtitle files to given format. By default, each file is saved in its original format.
--input-enc ENCODING Character encoding for input files. By default, UTF-8 is used for both input and output.
--output-enc ENCODING
Character encoding for output files. By default, it is the same as input encoding. If you wish to convert between encodings, make sure --input-enc is set correctly! Otherwise, your output files will probably be corrupted. It's a good idea to back up your files or use the -o
option.
--enc-error-handling {strict,surrogateescape}
Character encoding error handling for input and output. Defaults to 'surrogateescape' which passes through unrecognized characters to output unchanged. Use 'strict' if you want the command to fail when encountering a character incompatible with selected input/output encoding.
--fps FPS This argument specifies framerate for MicroDVD files. By default, framerate is detected from the file. Use this when framerate specification is missing or to force different framerate.
-o DIR, --output-dir DIR
Use this to save all files to given directory. By default, every file is saved to its parent directory, ie. unless it's being saved in different subtitle format (and thus with different file extension), it overwrites the original file.
--clean Attempt to remove non-essential subtitles (eg. karaoke, SSA drawing tags), strip styling information when saving to non-SSA formats
--verbose Print misc logging
--shift TIME Delay all subtitles by given time amount. Time is specified like this: '1m30s', '0.5s', ...
--shift-back TIME The opposite of --shift (subtitles will appear sooner).
--transform-framerate FPS1 FPS2
Multiply all timestamps by FPS1/FPS2 ratio.
```
--------------------------------
### SSAFile.to_string
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Get subtitle file as a string. This method serializes the SSAFile object to a string in the specified format.
```APIDOC
## SSAFile.to_string
### Description
Get subtitle file as a string. See SSAFile.save() for full description.
### Method
method
### Signature
SSAFile.to_string(format: str, **kwargs: Any) -> str
### Parameters
- **format** (str) - Required - The format to output the subtitle file in (e.g., "srt", "ass").
- **kwargs** (Any) - Optional - Additional writer arguments.
### Returns
str
```
--------------------------------
### SubstationFormat.to_file()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Writes an SSAFile to a file in SubStation Alpha format. Inherits from FormatBase and supports additional writer arguments.
```APIDOC
## SubstationFormat.to_file()
### Description
Writes an SSAFile to a file in SubStation Alpha format. See FormatBase.to_file() for details.
### Method
classmethod
### Signature
to_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Unpack[WriterArgs]) -> None
### Parameters
- **subs** (SSAFile) - Required - Subtitle file to write.
- **fp** (file object) - Required - Text file object used as output.
- **format** (str) - Required - Format identifier.
- **kwargs** - Optional - Extra options, per WriterArgs TypedDict.
### WriterArgs
- **header_notice** (NotRequired[str]) - Optional - Additional header notice.
### Returns
None
```
--------------------------------
### Load a subtitle file
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Imports the library and loads a subtitle file into an SSAFile object.
```python
>>> import pysubs2
>>> subs = pysubs2.load("subtitles.srt")
>>> subs
```
--------------------------------
### FormatBase.from_file()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Loads a subtitle file into an empty SSAFile. This classmethod is part of the FormatBase class and is used to parse subtitle content from a text file object.
```APIDOC
## FormatBase.from_file()
### Description
Loads a subtitle file into an empty SSAFile. If the parser autodetects framerate, it sets it as subs.fps.
### Method
classmethod
### Signature
from_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Any) -> None
### Parameters
- **subs** (SSAFile) - Required - An empty SSAFile.
- **fp** (file object) - Required - Text file object, the subtitle file.
- **format** (str) - Required - Format identifier. Used when one format class implements multiple formats.
- **kwargs** - Optional - Extra options, eg. fps (per ReaderArgs TypedDict in given subclass).
### Returns
None
### Raises
- **pysubs2.exceptions.UnknownFPSError** - Framerate was not provided and cannot be detected.
```
--------------------------------
### Custom function to shift all timestamps
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Defines a function shift(subs, ms) that adds ms to start and end of each line, then calls it with 500.
```python
>>> def shift(subs, ms):
... for line in subs:
... line.start += ms
... line.end += ms
shift(subs, 500)
```
--------------------------------
### pysubs2.exceptions.UnknownFormatIdentifierError
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Exception raised when an unknown subtitle format identifier (e.g., a string like "srt") is used. It is used when interpreting the format_ parameter fails, for example in SSAFile.save().
```APIDOC
## UnknownFormatIdentifierError
### Description
Unknown subtitle format identifier (ie. string like "srt"). This exception is used when interpreting format_ parameter fails, eg. in SSAFile.save().
### Constructor
- **format_** (str) - Format identifier
### Attributes
- **format_** (str) - Format identifier
### Base Class
Pysubs2Error
```
--------------------------------
### Load subtitle files with pysubs2.load
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Demonstrates loading subtitles from files, including specifying framerate for frame-based formats and preserving unknown HTML tags.
```python
>>> subs1 = pysubs2.load("subrip-subtitles.srt")
>>> subs2 = pysubs2.load("microdvd-subtitles.sub", fps=23.976)
>>> subs3 = pysubs2.load("subrip-subtitles-with-fancy-tags.srt", keep_unknown_html_tags=True)
```
--------------------------------
### SSAFile.import_styles
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Imports styles from another SSAFile.
```APIDOC
## SSAFile.import_styles
### Description
Imports styles from another SSAFile.
### Method
Instance Method
### Signature
`SSAFile.import_styles(other)`
### Parameters
- **other** (SSAFile) - Required - The SSAFile from which to import styles.
### Returns
- **None** - This method modifies the file in place.
### Example
```python
subs.import_styles(other_subs)
```
```
--------------------------------
### SSAFile.from_file
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Creates an SSAFile from a file object.
```APIDOC
## SSAFile.from_file
### Description
Creates an SSAFile from a file object.
### Method
Class Method
### Signature
`SSAFile.from_file(file, format_=None, **kwargs)`
### Parameters
- **file** (file object) - Required - A file-like object containing subtitle data.
- **format_** (str) - Optional - The format of the subtitle data. If not specified, it is guessed from the content.
- **kwargs** - Optional - Additional keyword arguments passed to the format's from_file method.
### Returns
- **SSAFile** - The parsed subtitle file.
### Example
```python
with open("subtitles.srt", "r") as f:
subs = SSAFile.from_file(f)
```
```
--------------------------------
### Manipulate SSAFile events
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Demonstrates loading a subtitle file, iterating through its events, inserting a new subtitle, and deleting an existing one using the list-like interface.
```python
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]
```
--------------------------------
### Create a new style directly with SSAStyle
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Creates a style 'Top' with fontsize=10 and alignment TOP_CENTER, then assigns it to subs[1]. Note: the code assigns my_style instead of top_style, which may be a typo in the source.
```python
>>> top_style = pysubs2.SSAStyle(fontsize=10, alignment=pysubs2.Alignment.TOP_CENTER)
>>> subs.styles["Top"] = my_style
>>> subs[1].style = "Top"
```
--------------------------------
### SubripFormat.from_file()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Loads a SubRip Text (SRT) subtitle file into an SSAFile. Inherits from FormatBase and supports additional reader arguments.
```APIDOC
## SubripFormat.from_file()
### Description
Loads a SubRip Text (SRT) subtitle file into an SSAFile. See FormatBase.from_file() for details.
### Method
classmethod
### Signature
from_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Unpack[ReaderArgs]) -> None
### Parameters
- **subs** (SSAFile) - Required - An empty SSAFile.
- **fp** (file object) - Required - Text file object, the subtitle file.
- **format** (str) - Required - Format identifier.
- **kwargs** - Optional - Extra options, per ReaderArgs TypedDict.
### ReaderArgs
- **keep_html_tags** (NotRequired[bool]) - Optional - Whether to keep HTML tags.
- **keep_unknown_html_tags** (NotRequired[bool]) - Optional - Whether to keep unknown HTML tags.
### Supported Tags
-
-
-
-
### Returns
None
```
--------------------------------
### SSAFile.load
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Loads a subtitle file from a path. This is a class method that returns an SSAFile instance.
```APIDOC
## SSAFile.load
### Description
Loads a subtitle file from a path. This is a class method that returns an SSAFile instance.
### Method
Class Method
### Signature
`SSAFile.load(path, encoding=None, format_=None, **kwargs)`
### Parameters
- **path** (str) - Required - The path to the subtitle file.
- **encoding** (str) - Optional - The encoding of the file.
- **format_** (str) - Optional - The format of the subtitle file. If not specified, it is guessed from the file extension.
- **kwargs** - Optional - Additional keyword arguments passed to the format's from_file method.
### Returns
- **SSAFile** - The loaded subtitle file.
### Example
```python
subs = SSAFile.load("subtitles.srt")
```
```
--------------------------------
### SubripFormat.to_file()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Writes an SSAFile to a file in SubRip Text (SRT) format. Inherits from FormatBase and supports additional writer arguments.
```APIDOC
## SubripFormat.to_file()
### Description
Writes an SSAFile to a file in SubRip Text (SRT) format. See FormatBase.to_file() for details.
### Method
classmethod
### Signature
to_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Unpack[WriterArgs]) -> None
### Parameters
- **subs** (SSAFile) - Required - Subtitle file to write.
- **fp** (file object) - Required - Text file object used as output.
- **format** (str) - Required - Format identifier.
- **kwargs** - Optional - Extra options, per WriterArgs TypedDict.
### WriterArgs
- **apply_styles** (NotRequired[bool]) - Optional - Whether to apply styles.
- **keep_ssa_tags** (NotRequired[bool]) - Optional - Whether to keep SSA tags.
### Returns
None
```
--------------------------------
### Access and copy styles
Source: https://pysubs2.readthedocs.io/en/latest/_sources/tutorial.rst.txt
Retrieve an existing style from the styles dictionary and create a copy for modification.
```python
>>> subs.styles["Default"]
>>> my_style = subs.styles["Default"].copy()
>>> my_style.italic = True
>>> subs.styles["MyStyle"] = my_style
>>> subs[1].style = "MyStyle"
```
--------------------------------
### FormatBase.to_file()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Writes an SSAFile into a text file object. This classmethod is used for saving subtitle content in a specific format.
```APIDOC
## FormatBase.to_file()
### Description
Writes SSAFile into a file. If framerate is needed and not passed in keyword arguments, uses subs.fps.
### Method
classmethod
### Signature
to_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Any) -> None
### Parameters
- **subs** (SSAFile) - Required - Subtitle file to write.
- **fp** (file object) - Required - Text file object used as output.
- **format** (str) - Required - Format identifier of desired output format. Used when one format class implements multiple formats.
- **kwargs** - Optional - Extra options, eg. fps (per WriterArgs TypedDict in given subclass).
### Returns
None
### Raises
- **pysubs2.exceptions.UnknownFPSError** - Framerate was not provided and subs.fps is None.
```
--------------------------------
### SSAFile.to_file(fp, format, **kwargs)
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Writes a subtitle file to a file object. This is a low-level method; usually SSAFile.save() or SSAFile.to_string() is preferable. The format must be specified.
```APIDOC
## SSAFile.to_file(fp, format, **kwargs)
### Description
Write subtitle file to file object. See SSAFile.save() for full description. This is a low-level method; usually SSAFile.save() or SSAFile.to_string() is preferable.
### Method
Instance method
### Signature
SSAFile.to_file(fp: TextIO, format: str, **kwargs) -> None
### Parameters
- **fp** (file object) - Required - A file object, ie. TextIO instance. Note that the file must be opened in text mode (as opposed to binary).
- **format** (str) - Required - The format to write the subtitle file in (e.g., "srt", "ass").
### Returns
None
```
--------------------------------
### Use pysubs2.make_time() to specify times in seconds or frames
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Demonstrates that make_time(s=2) equals 60000 ms and make_time(frames=50, fps=25) also equals 60000 ms.
```python
>>> subs[1].start == pysubs2.make_time(s=2)
True
>>> subs[1].start == pysubs2.make_time(frames=50, fps=25)
True
```
--------------------------------
### Convert ASS to SRT
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Converts all .ass files in the current directory to SRT format.
```bash
python -m pysubs2 --to srt *.ass
```
--------------------------------
### Convert ASS to SRT with cleaning
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Converts .ass files to SRT and cleans the subtitles (e.g., removes formatting tags).
```bash
python -m pysubs2 --to srt --clean *.ass
```
--------------------------------
### Create top/bottom bilingual subtitles
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
This script loads English and Italian subtitles, assigns them to distinct top and bottom styles, and saves the result as an ASS file. Ensure the output format supports positioning, such as SubStation Alpha.
```python
import pysubs2
from pysubs2 import Alignment, Color, SSAFile, SSAStyle
subs_en = pysubs2.load("subs.en.srt") # read input subtitles in SRT format
subs_it = pysubs2.load("subs.it.srt")
subs = SSAFile()
subs.styles = {
"bottom": SSAStyle(alignment=Alignment.BOTTOM_CENTER, primarycolor=Color(255, 255, 0)),
"top": SSAStyle(alignment=Alignment.TOP_CENTER, primarycolor=pysubs2.Color(0, 128, 128)),
}
for e in subs_it:
e.style = "bottom"
subs.append(e)
for e in subs_en:
e.style = "top"
subs.append(e)
subs.save("subs.ass") # write subtitles in ASS format (supports formatting)
```
--------------------------------
### SSAFile.from_string
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Creates an SSAFile from a string containing subtitle data.
```APIDOC
## SSAFile.from_string
### Description
Creates an SSAFile from a string containing subtitle data.
### Method
Class Method
### Signature
`SSAFile.from_string(string, format_=None, **kwargs)`
### Parameters
- **string** (str) - Required - The subtitle data as a string.
- **format_** (str) - Optional - The format of the subtitle data. If not specified, it is guessed from the content.
- **kwargs** - Optional - Additional keyword arguments passed to the format's from_string method.
### Returns
- **SSAFile** - The parsed subtitle file.
### Example
```python
subs = SSAFile.from_string("1\n00:00:01,000 --> 00:00:02,000\nHello")
```
```
--------------------------------
### SSAEvent.copy()
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Returns a copy of the SSAEvent.
```APIDOC
## SSAEvent.copy()
### Description
Returns a copy of the SSAEvent.
### Method
Method call
### Endpoint
SSAEvent.copy()
### Parameters
- None
### Returns
- **SSAEvent** - A copy of the event.
### Example
```python
event_copy = event.copy()
```
```
--------------------------------
### pysubs2.time module
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Time-related utilities for subtitle timing.
```APIDOC
## pysubs2.time module
### Description
Time-related utilities for subtitle timing.
### Functions
- **make_time** - Creates a timestamp in milliseconds.
- **ms_to_times** - Converts milliseconds to a tuple of (h, m, s, ms).
- **times_to_ms** - Converts a tuple of (h, m, s, ms) to milliseconds.
- **timestamp_to_ms** - Converts a timestamp string to milliseconds.
- **ms_to_timestamp** - Converts milliseconds to a timestamp string.
### Example
```python
from pysubs2.time import make_time, ms_to_timestamp
```
```
--------------------------------
### Convert ASS to MicroDVD with FPS
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Converts .ass files to MicroDVD format, specifying a frame rate of 23.976 fps.
```bash
python -m pysubs2 --to microdvd --fps 23.976 *.ass
```
--------------------------------
### Access subtitle events
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Demonstrates how to iterate over subtitle events and access their text content.
```python
>>> subs[0].text
"Once upon a time,"
>>> for line in subs:
... print(line.text)
Once upon a time,
there was a SubRip file\Nwith two subtitles.
```
--------------------------------
### SSAFile.from_file(fp, format=None, **kwargs)
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Reads a subtitle file from a file object. This is a low-level method; usually SSAFile.load() or SSAFile.from_string() is preferable. The format can be specified or auto-detected from file contents.
```APIDOC
## SSAFile.from_file(fp, format=None, **kwargs)
### Description
Read subtitle file from file object. See SSAFile.load() for full description. This is a low-level method; usually SSAFile.load() or SSAFile.from_string() is preferable.
### Method
Class method
### Signature
SSAFile.from_file(fp: TextIO, format: str | None = None, **kwargs) -> SSAFile
### Parameters
- **fp** (file object) - Required - A file object, ie. TextIO instance. Note that the file must be opened in text mode (as opposed to binary).
- **format** (str) - Optional - Forces use of specific parser (eg. "srt", "ass"). Otherwise, format is detected automatically from file contents. This argument should be rarely needed.
- **fps** (float) - Optional - Framerate for frame-based formats (MicroDVD), for other formats this argument is ignored. Framerate might be detected from the file, in which case you don't need to specify it here (when given, this argument overrides autodetection).
### Returns
SSAFile
```
--------------------------------
### Load SRT and inspect text
Source: https://pysubs2.readthedocs.io/en/latest/_sources/tutorial.rst.txt
Loading an SRT file converts style information into inline tags.
```python
>>> modified_subs = pysubs2.SSAFile.from_string(modified_srt)
>>> modified_subs[1].text
"{\\i1}there was a SubRip file\\Nwith two subtitles.{\\i0}"
>>> modified_subs[1].style
"Default"
```
--------------------------------
### Shift subtitles backward and output to directory
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Shifts all .srt files backward by 0.3 seconds and writes the results to the 'retimed' directory.
```bash
python -m pysubs2 --shift-back 0.3s --output-dir retimed *.srt
```
--------------------------------
### Transform framerate from 25 to 23.976
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Transforms the framerate of all .srt files from 25 fps to 23.976 fps.
```bash
python -m pysubs2 --transform-framerate 25 23.976 *.srt
```
--------------------------------
### SSAFile.sort
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Sorts subtitles time-wise, in-place.
```APIDOC
## SSAFile.sort
### Description
Sort subtitles time-wise, in-place.
### Method
SSAFile.sort
### Signature
SSAFile.sort() -> None
### Return Value
None
```
--------------------------------
### ms_to_str(ms: int | float, fractions: bool = False) -> str
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Prettyprints milliseconds to [-]H:MM:SS[.mmm]. Handles huge and/or negative times.
```APIDOC
## ms_to_str(ms: int | float, fractions: bool = False) -> str
### Description
Prettyprint milliseconds to [-]H:MM:SS[.mmm]. Handles huge and/or negative times. Non-negative times with fractions=True are matched by TIMESTAMP.
### Parameters
- **ms** (int | float) - Required - Number of milliseconds.
- **fractions** (bool) - Optional - Whether to print up to millisecond precision.
### Returns
str
```
--------------------------------
### SSAStyle
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Represents a subtitle style.
```APIDOC
## SSAStyle
### Description
Represents a subtitle style.
### Method
Class
### Attributes
- **name** (str) - The style name.
- **fontname** (str) - The font name.
- **fontsize** (float) - The font size.
- **primarycolor** (Color) - The primary color.
- **secondarycolor** (Color) - The secondary color.
- **outlinecolor** (Color) - The outline color.
- **backcolor** (Color) - The background color.
- **bold** (bool) - Whether the text is bold.
- **italic** (bool) - Whether the text is italic.
- **underline** (bool) - Whether the text is underlined.
- **strikeout** (bool) - Whether the text is struck out.
- **scalex** (float) - Horizontal scale.
- **scaley** (float) - Vertical scale.
- **spacing** (float) - Letter spacing.
- **angle** (float) - Rotation angle.
- **borderstyle** (int) - Border style.
- **outline** (float) - Outline width.
- **shadow** (float) - Shadow depth.
- **alignment** (Alignment) - Text alignment.
- **marginl** (int) - Left margin.
- **marginr** (int) - Right margin.
- **marginv** (int) - Vertical margin.
- **alphalevel** (int) - Alpha level.
- **encoding** (int) - Character encoding.
### Example
```python
style = SSAStyle(fontname="Arial", fontsize=24)
```
```
--------------------------------
### MPL2Format.to_file
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Writes subtitles to a file in MPL2 format. No styling is supported at the moment.
```APIDOC
## MPL2Format.to_file
### Description
Writes subtitles to a file in MPL2 format. No styling is supported at the moment.
### Method
classmethod to_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Unpack[WriterArgs]) -> None
### Parameters
No additional parameters documented.
### Description
See pysubs2.formats.FormatBase.to_file()
```
--------------------------------
### Shift subtitles forward by 0.3 seconds
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Shifts all .srt files forward by 0.3 seconds.
```bash
python -m pysubs2 --shift 0.3s *.srt
```
--------------------------------
### pysubs2.VERSION
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
The version string of the pysubs2 library.
```APIDOC
## pysubs2.VERSION
### Description
The version string of the pysubs2 library.
### Method
Constant
### Value
- **str** - The version number, e.g., "1.6.1".
### Example
```python
print(pysubs2.VERSION)
```
```
--------------------------------
### Load subtitles from OpenAI Whisper transcript
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Demonstrates how to transcribe an audio file using the whisper library and convert the resulting transcript into a pysubs2 SSAFile object for saving.
```python
>>> import whisper
>>> import pysubs2
>>> model = whisper.load_model("base")
>>> result = model.transcribe("audio.mp3")
>>> subs = pysubs2.load_from_whisper(result)
>>> subs.save("audio.ass")
```
--------------------------------
### Load SRT string and inspect style loss
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Demonstrates that loading an exported SRT file back into pysubs2 results in the loss of custom style names, reverting to the 'Default' style.
```python
>>> modified_subs = pysubs2.SSAFile.from_string(modified_srt)
>>> modified_subs[1].text
"{\\i1}there was a SubRip file\\Nwith two subtitles.{\\i0}"
>>> modified_subs[1].style
"Default"
```
--------------------------------
### SSAFile.shift
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Shifts all events in the file by a given time offset.
```APIDOC
## SSAFile.shift
### Description
Shifts all events in the file by a given time offset.
### Method
Instance Method
### Signature
`SSAFile.shift(ms=None, h=None, m=None, s=None, fps=None)`
### Parameters
- **ms** (int) - Optional - Milliseconds to shift.
- **h** (int) - Optional - Hours to shift.
- **m** (int) - Optional - Minutes to shift.
- **s** (int) - Optional - Seconds to shift.
- **fps** (float) - Optional - Frames per second, used if shifting by frames.
### Returns
- **None** - This method modifies the file in place.
### Example
```python
subs.shift(s=1) # shift by 1 second
```
```
--------------------------------
### Use SSAFile.shift() to shift subtitles
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Shifts all subtitles by -0.5 seconds using the built-in shift method, which accepts the same arguments as make_time().
```python
>>> subs.shift(s=-0.5)
```
--------------------------------
### pysubs2.load
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Loads a subtitle file from a path, file object, or string. This is a convenience function that returns an SSAFile object.
```APIDOC
## pysubs2.load
### Description
Loads a subtitle file from a path, file object, or string. This is a convenience function that returns an SSAFile object.
### Method
Function
### Signature
`pysubs2.load(path, encoding=None, format_=None, **kwargs)`
### Parameters
- **path** (str or file object) - Required - The path to the subtitle file or a file-like object.
- **encoding** (str) - Optional - The encoding of the file.
- **format_** (str) - Optional - The format of the subtitle file. If not specified, it is guessed from the file extension.
- **kwargs** - Optional - Additional keyword arguments passed to the format's from_file method.
### Returns
- **SSAFile** - The loaded subtitle file.
### Example
```python
subs = pysubs2.load("subtitles.srt")
```
```
--------------------------------
### Inspect timestamp of a subtitle
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Shows that subs[1].start is an integer representing milliseconds (60000 ms = 1 minute).
```python
>>> subs[1].start
60000
```
--------------------------------
### Subtitle format implementations
Source: https://pysubs2.readthedocs.io/en/latest/_sources/api-reference.rst.txt
Specific subtitle format implementations.
```APIDOC
## Subtitle format implementations
### Description
Specific subtitle format implementations.
### Formats
- **SubstationFormat** - Advanced SubStation Alpha (ASS) format.
- **SubripFormat** - SubRip (SRT) format.
- **MPL2Format** - MPL2 format.
- **TmpFormat** - TMP format.
- **WebVTTFormat** - WebVTT format.
- **TTMLFormat** - TTML format.
- **SAMIFormat** - SAMI format.
- **MicroDVDFormat** - MicroDVD format.
- **JSONFormat** - JSON format.
### Example
```python
from pysubs2.formats.substation import SubstationFormat
```
```
--------------------------------
### MPL2Format.from_file
Source: https://pysubs2.readthedocs.io/en/latest/api-reference.html
Reads subtitles from a file in MPL2 format.
```APIDOC
## MPL2Format.from_file
### Description
Reads subtitles from a file in MPL2 format.
### Method
classmethod from_file(subs: SSAFile, fp: TextIO, format: str, **kwargs: Unpack[ReaderArgs]) -> None
### Parameters
No additional parameters documented.
### Description
See pysubs2.formats.FormatBase.from_file()
```
--------------------------------
### Copy and modify a style, then assign to an event
Source: https://pysubs2.readthedocs.io/en/latest/tutorial.html
Creates a new style 'MyStyle' by copying the default style, sets italic to True, adds it to the styles dictionary, and assigns it to subs[1].
```python
>>> my_style = subs.styles["Default"].copy()
>>> my_style.italic = True
>>> subs.styles["MyStyle"] = my_style
>>> subs[1].style = "MyStyle"
```
--------------------------------
### Shift subtitles forward using stdin/stdout
Source: https://pysubs2.readthedocs.io/en/latest/_sources/cli.rst.txt
Shifts a single SRT file forward by 0.3 seconds, reading from stdin and writing to stdout.
```bash
python -m pysubs2 --shift 0.3s retimed_file.srt
```