pysubs2

repository·master·Indexed 19 days ago

https://github.com/tkarabela/pysubs2

A Python library for editing and converting subtitle files. It supports various formats including SubStation Alpha (ASS/SSA), SRT, WebVTT, TTML, SAMI, MicroDVD, MPL2, TMP, and OpenAI Whisper captions. The library provides a programmatic API via the SSAFile class for complex manipulations and a CLI tool for batch tasks such as retiming, framerate transformation, and format conversion.

Tokens
12.1K
Snippets
51
Records
66
Agent score
65%

What's inside pysubs2

  1. Handle frame-based MicroDVD subtitles

    master
    MicroDVD uses .sub files (identifier: "microdvd") which describe start/end times using frames instead of timestamps. Because this format is dependent on the video framerate, pysubs2 will attempt to autodetect the framerate (often found in the first subtitle line) to perform proper retiming and conversion.
  2. Implement a custom subtitle format

    master

    If you need to support a subtitle format not currently implemented in pysubs2, you can create a custom format by subclassing pysubs2.formats.FormatBase.

    Note that some existing formats support additional keyword parameters in their from_file() or to_file() methods to customize parser/writer behavior.

  3. Use SubStation Alpha (ASS/SSA) as the native format

    master

    SubStation Alpha is the native format for pysubs2. It supports rich text formatting, animations, and vector graphics.

    • .ass files: Advanced SubStation Alpha v4.0+ (identifier: "ass")
    • .ssa files: SubStation Alpha v4.0 (identifier: "ssa")

    Since version 1.2.0, pysubs2 preserves embedded fonts (stored in opaque form) when loading and saving. Since version 1.6.0, it also supports embedded graphics.

  4. Import and export SubRip (SRT) subtitles

    master

    SubRip (SRT) is a widely used format using .srt files (identifier: "srt"). It uses HTML-style tags for formatting.

    Key Features:

    • Keep SubStation tags: Since version 1.4.0, you can use an option to keep SubStation override tags (like {\i1}) in the SRT output.
    • Keep all HTML tags: Since version 1.4.1, you can use an option to prevent the library from stripping unknown HTML tags during input.
  5. Force specific subtitle formats using format identifiers

    master

    Every supported format in pysubs2 has a unique format identifier string. While the library typically uses autodetection from file extensions and content, you can use these identifiers to force a specific input or output format in the API (e.g., in pysubs2.load() or SSAFile.save()).

    Supported Format Identifiers:

    • "ass": Advanced SubStation Alpha (v4.0+)
    • "ssa": SubStation Alpha (v4.0)
    • "srt": SubRip (SRT)
    • "mpl2": MPL2
    • "tmp": TMP (TMP Player format)
    • "vtt": WebVTT
    • "ttml": TTML (Timed Text Markup Language)
    • "sami": SAMI (Synchronized Accessible Media Interchange)
    • "whisper_jax": OpenAI Whisper JAX transcriptions
    • "microdvd": MicroDVD (.sub files)
    • "json": JSON-serialized internal representation (equivalent to ASS)
  6. Use the pysubs2 CLI for subtitle conversion and retiming

    master

    The pysubs2 CLI allows you to convert subtitle files between different formats or perform simple retiming operations. You can invoke it via the pysubs2 command or by using python -m pysubs2.

    Important Note on File Overwriting: By default, the CLI works in-place, meaning original files are overwritten. To avoid this, use the -o/--output-dir DIR option to specify a different directory, or use UNIX pipes (e.g., pysubs2 < infile > outfile).

    # Convert all .ass files to .srt
    pysubs2 --to srt *.ass
    
    # Shift subtitles forward by 0.3 seconds and save to a new file via pipe
    pysubs2 --shift 0.3s <my_file.srt >retimed_file.srt
    
    # Shift subtitles back by 0.3s and save to a specific directory
    pysubs2 --shift-back 0.3s --output-dir retimed *.srt
    
    # Transform framerate from 25 to 23.976
    pysubs2 --transform-framerate 25 23.976 *.srt
  7. Convert subtitle formats with pysubs2 CLI

    master

    You can convert files to specific formats using the --to flag. Supported formats include: srt, ass, ssa, microdvd, json, mpl2, tmp, and vtt.

    If you are converting to a format other than SubStation Alpha (ASS/SSA), comment and drawing lines will be skipped automatically. For more aggressive cleaning (skipping karaoke and duplicated lines), use the --clean flag.

    # Convert to SRT with aggressive cleaning
    pysubs2 --to srt --clean *.ass
    
    # Convert to MicroDVD with a specific framerate
    pysubs2 --to microdvd --fps 23.976 *.ass
  8. How to specify time durations in pysubs2

    master

    When using --shift or --shift-back, time is specified using a string format that includes units. Supported units are:

    • ms (milliseconds)
    • m (minutes)
    • s (seconds)
    • h (hours)

    Example formats: '1m30s', '0.5s', '500ms'.

    # Example usage in CLI
    python -m pysubs2 --shift 1m30s input.srt
  9. Manipulate subtitle events in SSAFile

    master

    An SSAFile instance behaves like a mutable sequence of SSAEvent objects. You can iterate over it, access items by index, insert new events, or delete existing ones.

    Key operations:

    • Iteration: for event in subs: ...
    • Indexing: event = subs[0] or subs[0:5]
    • Insertion: subs.insert(index, event)
    • Deletion: del subs[index]
    • Sorting: subs.sort() sorts events by time in-place.
    import pysubs2
    from .ssaevent import SSAEvent
    from .time import make_time
    
    subs = pysubs2.SSAFile.load("subtitles.srt")
    
    # Accessing events
    for line in subs:
        print(line.text)
    
    # Inserting a new event
    new_event = SSAEvent(start=0, end=make_time(s=2.5), text="New first subtitle")
    subs.insert(0, new_event)
    
    # Deleting an event
    del subs[0]
    
    # Sorting events by time
    subs.sort()
  10. Use the pysubs2 CLI to process subtitle files

    master

    The pysubs2 CLI allows you to convert, shift, and transform subtitle files (SubStation Alpha, SubRip, MicroDVD, etc.) via the command line. You can process multiple files at once or use it in a pipeline by reading from stdin and writing to stdout.

    # Convert all .ass files to .srt
    python -m pysubs2 --to srt *.ass
    
    # Shift subtitles forward by 0.3 seconds
    python -m pysubs2 --shift 0.3s *.srt
    
    # Transform framerate from 25 to 23.976
    python -m pysubs2 --transform-framerate 25 23.976 *.srt
    
    # Use as a pipe (stdin/stdout)
    python -m pysubs2 --to srt < input.ass > output.srt
  11. Example: Create bilingual top/bottom subtitles

    master

    This recipe demonstrates how to combine two different subtitle files (e.g., English and Italian) into a single ASS file where one language is positioned at the top and the other at the bottom with different colors.

    import pysubs2
    from pysubs2 import Alignment, Color, SSAFile, SSAStyle
    
    # Load input files
    subs_en = pysubs2.load("subs.en.srt")
    subs_it = pysubs2.load("subs.it.srt")
    
    # Create a new container
    subs = SSAFile()
    
    # Define styles for positioning and color
    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)),
    }
    
    # Add Italian subtitles to the bottom
    for e in subs_it:
        e.style = "bottom"
        subs.append(e)
    
    # Add English subtitles to the top
    for e in subs_en:
        e.style = "top"
        subs.append(e)
    
    # Save as ASS to support positioning
    subs.save("subs.ass")