pyCapCut

repository·main·Indexed 20 days ago

https://github.com/guanyixuan/pycapcut

A lightweight Python tool for generating and exporting CapCut drafts to build automated video editing and mashup pipelines. It supports adding video/audio assets, text, subtitles via SRT import, keyframes, masks, effects, filters, and transitions. It features a Template Mode for loading existing drafts to replace materials or text while preserving complex formatting, and a Batch Export feature to control CapCut's export settings. Note: Generated drafts must be opened and exported using the Windows version of CapCut.

Tokens
7.1K
Snippets
20
Records
23
Agent score
20%

What's inside pycapcut

  1. Overview of pyCapCut features

    main

    pyCapCut is a lightweight and flexible Python tool for generating and exporting CapCut drafts, designed to build automated video editing/mashup pipelines.

    Key feature areas include:

    • Template Mode: Loading unencrypted draft_content.json files, replacing assets by name, modifying text, importing specific tracks, and extracting metadata for stickers/bubbles.
    • Batch Export: Controlling CapCut to open specific drafts, exporting to designated locations, and adjusting resolution/frame rate.
    • Video & Images: Adding local assets, customizing duration/speed, audio fades, rotation/scaling/brightness, keyframes, entrance/exit animations, masks, effects, filters, and background filling.
    • Audio: Adding local audio, customizing duration/speed, volume/fade keyframes, and scene sound effects.
    • Tracks: Adding tracks, adding clips to specific tracks, and managing layer hierarchies for video/filters/effects.
    • Effects, Filters & Transitions: Applying effects/filters/animations to clips or independent tracks, and adding transitions with custom durations.
    • Text & Subtitles: Adding text with font/style/position/rotation, keyframes, animations, strokes, backgrounds, shadows, bubbles, and automatic line wrapping. Supports importing .srt files for batch subtitle generation.
  2. Handle time and duration using strings or microseconds

    main

    CapCut and pycapcut use microseconds (int) internally. For ease of use, the library supports string formats like "1.5s" or "1h3m12s".

    • Use tim("string") to convert a string to microseconds.
    • Use trange("start", "duration") to create a Timerange. Note: The second argument is the duration, not the end time.
    • SEC is a constant representing 1 second in microseconds.
    import pycapcut as cc
    from pycapcut import SEC, tim, trange
    
    # 1 second
    assert 1000000 == SEC == tim("1s")
    
    # 0 to 1 minute duration
    # trange(start, duration)
    assert cc.Timerange(0, 60*SEC) == trange("0s", "1m")
  3. Handle time and timeranges

    main

    CapCut uses microseconds internally. pycapcut provides a convenient string format for time input (e.g., "1.5s", "1h3m12s").

    • SEC: Constant representing 1 second in microseconds.
    • tim(string): Converts a time string to microseconds.
    • trange(start, duration_or_end): A convenience constructor for Timerange. Note: The second parameter is duration, not end time.

    Example usage:

    from pycapcut import SEC, tim, trange
    
    # 1 second
    val = tim("1s")
    
    # 0 to 1 minute
    tr = trange("0s", "1m")
  4. Quickstart with demo.py

    main

    The demo.py script provides a complete example of creating a CapCut draft containing audio/video assets, text, audio fades, video entrance animations, transitions, keyframes, and text bubbles/fancy text effects.

    To use the demo:

    1. Locate your CapCut drafts folder path (e.g., .../CapCut Drafts).
    2. Replace <你的草稿文件夹> in demo.py with your actual path.
    3. Run demo.py.
    4. Open CapCut and locate the newly created demo draft. (You may need to enter and exit an existing draft or restart CapCut to refresh the list).
    # Replace <your_draft_folder_path> in demo.py then run:
    python demo.py
  5. Quick Start with demo.py

    main

    The demo.py script provides a complete example of creating a CapCut draft. It demonstrates adding audio/video media, text, audio fade-in, video intro animations, transitions, keyframes, and text bubble effects.

    Steps to run the example:

    1. Locate your CapCut Drafts folder path (e.g., .../CapCut Drafts).
    2. Open demo.py and replace <your CapCut Drafts folder> with your actual path.
    3. Run the script: python demo.py.
    4. Open CapCut and find the newly created demo draft. (If it doesn't appear immediately, try entering/exiting an existing draft or restarting CapCut).
  6. Extract resource metadata from a template

    main

    If you want to use specific CapCut assets like stickers or fancy text in your automated scripts, you need their resource_id. You can extract these by calling inspect_material on a ScriptFile or via a DraftFolder.

    Example output format:

    贴纸素材:
            Resource id: 7405878923323641129 '秋日手绘-枫叶'
    文字气泡效果:
            Effect id: 763870 ,Resource id: 6838834573413978631 '标题59'

    Use the extracted resource_id in parameters like StickerSegment(resource_id=...).

    import pycapcut as cc
    
    draft_folder = cc.DraftFolder("<CapCut Drafts folder>")
    draft_folder.inspect_material("Draft Name")
    
    # Or via a loaded script
    script = draft_folder.load_template("Draft Name")
    script.inspect_material()
  7. Replace media in a template draft

    main

    There are two ways to replace media depending on whether you want to affect all segments or just one.

    Replace media by name

    Replaces the media file itself. This is best for images and affects every segment that references that material. It does not change the source range.

    new_material = cc.AudioMaterial("<path to new audio file>")
    script.replace_material_by_name("audio.mp3", new_material)

    Replace media by segment

    Replaces the media for a specific segment at a specific index. This allows you to reselect the source_timerange and control how the timeline reacts to changes in length using handle_shrink and handle_extend.

    Parameters:

    • handle_shrink: Controls behavior if the new media is shorter (e.g., ShrinkMode.cut_tail).
    • handle_extend: Controls behavior if the new media is longer (e.g., ExtendMode.push_tail).

    Default behavior (if not specified):

    • If shorter: Move segment end earlier to match new length.
    • If longer: Crop source range to keep segment duration unchanged.
    from pycapcut import trange, ShrinkMode, ExtendMode
    
    audio_track = script.get_imported_track(cc.TrackType.audio, index=0)
    
    script.replace_material_by_seg(
        audio_track, 0, new_material, 
        source_timerange=trange("0s", "10s"),
        handle_shrink=ShrinkMode.cut_tail, 
        handle_extend=ExtendMode.push_tail
    )
  8. Use Template Mode to generate new drafts

    main

    To preserve complex features like text effects or composite clips, you can load an existing CapCut draft as a template and either import its content into a new draft or replace specific parts of it.

    Loading a Template

    Use DraftFolder to manage your CapCut draft directory. You can duplicate a template draft to create a new editable ScriptFile.

    Replacement Strategies

    1. Replace material by name: Replaces the underlying material itself. This affects all clips referencing that material. It is highly recommended for image materials as it doesn't change time ranges.
    2. Replace material by segment: Replaces the material for a specific clip and allows you to redefine the source time range and how the clip handles duration changes (shrinking or extending).
    3. Replace text content: Replaces the text string of a specific text segment while preserving all existing formatting (font, style, etc.).

    Extracting Material Metadata

    If you need to use specific stickers or text effects from a template, use inspect_material() on a ScriptFile or DraftFolder to retrieve their resource_id or effect_id.

    import pycapcut as cc
    
    draft_folder = cc.DraftFolder("<CapCut草稿文件夹>")
    # Duplicate template and open for editing
    script = draft_folder.duplicate_as_template("模板草稿", "新草稿")
    
    # Example: Replace material by name
    new_material = cc.AudioMaterial("<新的音频素材路径>")
    script.replace_material_by_name("audio.mp3", new_material)
    
    script.save()
  9. Use Template Mode to generate drafts from existing CapCut drafts

    main

    To preserve complex features like text effects or compound clips, you can use an existing CapCut draft as a template. This allows you to load a draft, replace specific media or text, or import tracks from it into a new draft.

    Workflow

    1. Load Template: Use DraftFolder to manage and duplicate existing drafts.
    2. Replace Content: Use one of three methods:
      • Replace media by name: Replaces the media file itself (affects all segments using it).
      • Replace media by segment: Replaces media for a specific segment, allowing you to redefine the source_timerange and handle timeline stretching/shrinking.
      • Replace text content: Replaces text while preserving all formatting.
    3. Extract Metadata: Use inspect_material to find resource_ids for stickers or fancy text to use them in new segments.
    4. Import Tracks: Copy specific tracks (audio, video, or text) from a template draft into a new draft using import_track.
    import pycapcut as cc
    
    draft_folder = cc.DraftFolder("<CapCut Drafts folder>")
    script = draft_folder.duplicate_as_template("Template Draft", "New Draft")
    
    # Edit the script (replace media, add tracks, etc.)
    script.save()
  10. Install pyCapCut via pip

    main

    You can install the pycapcut package using pip. Note that the pip installation does not include the demo.py example file.

    Cross-platform compatibility: Linux and MacOS users can install and use the library, but please note that the generated drafts must still be opened and exported using the Windows version of CapCut.

    pip install pycapcut
  11. Create segments with trimming and speed

    main

    Segments (Video or Audio) can be created with specific source trimming and playback speed.

    Construction Styles:

    1. Convenience: Pass a file path string directly. The material is created automatically.
    2. Traditional: Create a Material instance first, then pass it to the Segment constructor. Use this if you need to set specific crop/clip properties on the material.

    Key Parameters:

    • target_timerange: The duration the segment occupies on the timeline.
    • source_timerange: The specific part of the media to play.
    • speed: The playback speed (e.g., 2.0 for 2x speed). If source_timerange and speed are both provided, the target_timerange is overridden by the speed calculation.
    import pycapcut as cc
    from pycapcut import trange
    
    # Method 1: Convenience (Trim first 4s, play at 1.25x speed)
    seg1 = cc.VideoSegment("video.mp4", trange("0s", "4s"), speed=1.25)
    
    # Method 2: Traditional (Play 5s of material at 2x speed, resulting in 2.5s on timeline)
    mat = cc.VideoMaterial("video.mp4")
    seg2 = cc.VideoSegment(mat, trange("1s", "66666h"), 
                            source_timerange=trange("0s", "5s"), 
                            speed=2.0)
  12. Add text and import subtitles

    main

    Adding Text

    Create a TextSegment and add it to a track. You can customize fonts, styles (size, color, underline, alignment), and position via ClipSettings.

    Auto-wrapping: Enable auto_wrapping=True in TextStyle and set max_line_width (as a proportion of screen width) to handle long text.

    Importing Subtitles (SRT)

    Use script.import_srt(file_path, track_name, ...) to automatically create text segments from an SRT file.

    Options:

    • time_offset: Shift all subtitles by a specific time (e.g., "1.5s").
    • text_style: Apply a specific TextStyle to all subtitles.
    • style_reference: Use an existing TextSegment as a template for style and clip_settings. If you want to adopt the reference's clip_settings, pass clip_settings=None.
    # Text with auto-wrapping
    seg = cc.TextSegment("Long text...", trange("0s", "10s"),
                         style=cc.TextStyle(auto_wrapping=True, max_line_width=0.7))
    
    # Import SRT
    script.import_srt("subtitle.srt", track_name="subtitle", time_offset="1.5s")