You need to enable JavaScript to run this app.
Lake AI Service

Lake AI Service

Copy page
Download PDF
Video processing
Video adaptive keyframe extraction
Copy page
Download PDF
Video adaptive keyframe extraction

Operator ID: daft.las.functions.video.video_adaptive_keyframes_sampling.VideoAdaptiveKeyframesSampling

Operator introduction

Description

The video adaptive keyframe extraction processor uses CLIP and adaptive algorithms for intelligent frame selection.

Key features:

  • Semantic understanding: Calculates the similarity between video frames and text descriptions based on the CLIP model, intelligently selecting representative keyframes.
  • Multi-format support: Compatible with local paths/URLs, base64 encoding, and binary stream input.
  • Efficient processing: Supports batch inference and distributed computing, significantly improving processing speed.
  • Flexible configuration: Allows customization of the CLIP model and inference precision to meet different scenario requirements.

Application scenarios:

  • Video content summarization, video retrieval, video analysis, and multimedia content management.

Caution and prerequisites

Details

Caution and prerequisites

Costs

Before calling an operator, you need to understand the model invocation costs associated with using the operator. For details, see Large model invocation billing.

Authentication (API Key)

Before calling an operator, you need to generate an API Key for operator invocation. It is recommended to configure the API Key as an environment variable to ensure safer operator calls. For details, see Obtain and configure API Key.

BaseURL

Before calling an operator, you need to determine the BaseURL for operator invocation based on the region where your current LAS service is deployed. This is used to configure the path parameter values for operator calls.
For details, see Obtain the Base URL. The Examples below are for reference only; when making actual calls, replace the path values with those corresponding to your region.

Daft invocation

Operator parameters

Input

Input column name

Note

videos

Input video column. The type depends on video_src_type (url/base64/binary).

Output

An array of structs containing keyframe information. Each element includes:

  • tos_paths: List of TOS paths for keyframe images
  • frame_ids: List of original frame indices for keyframes
  • scores: List of semantic similarity scores for keyframes

Parameters

If a parameter does not have a default value, it is required.

Parameter name

Type

Default value

Description

text

str

""

Text description used to calculate semantic similarity.
Default value: ""

model_path

str

"/opt/las/models"

Base path for the model. If empty, the model will be downloaded from Hugging Face Hub.
Default value: "/opt/las/models"

clip_model_name

str

"openai/clip-vit-base-patch32"

CLIP model name/subdirectory.
Default value: "openai/clip-vit-base-patch32"

dtype

str

"float16"

Model inference precision options:

  • float16: Faster inference
  • float32: Higher precision

Optional values: ["float16", "float32"]
Default value: "float16"

video_src_type

str

"video_url"

Input video format type. Supported types:

  • Path/URL (video_url)
  • Base64 encoding (video_base64)
  • Binary stream (video_binary)

Optional values: ["video_url", "video_base64", "video_binary"]
Default value: "video_url"

fps

float

1.0

Candidate frame sampling rate (uniform sampling based on fps).
Default value: 1.0

max_num_frames

int

32

Number of keyframes to be selected.
Default value: 32

t1

float

0.8

Threshold for determining significant peaks (mean_top - mean).
Default value: 0.8

t2

float

-100

Standard deviation threshold for determining whether to continue segmentation.
Default value: -100

all_depth

int

5

Maximum recursion depth.
Default value: 5

img_type

str

".jpg"

Output keyframe image format. Supports ".jpg" and ".png".
Optional values: [".jpg", ".png"]
Default value: ".jpg"

output_tos_dir

str

""

Save keyframe images to the target path in TOS. If the value is an empty string, the images will not be uploaded.
Default value: ""

return_keyframes

bool

true

Whether to return the array data of keyframe images.
Default value: True

batch_size

int

16

The number of frames for batch inference.
Default value: 16

rank

int

0

GPU index.
Default value: 0

video_format

str

"mp4"

The video format for binary/base64 input (such as mp4, mov).
Default value: "mp4"

Examples

The following code demonstrates how to use Daft (for distributed scenarios) to run the operator for video adaptive keyframe extraction.

from __future__ import annotations

import os

import daft
from daft import col
from daft.las.functions.udf import las_udf
from daft.las.functions.video.video_adaptive_keyframes_sampling import VideoAdaptiveKeyframesSampling

if __name__ == "__main__":
    # The extracted keyframes will be saved to the specified TOS path. Therefore, you need to set environment variables to ensure write permissions to TOS, including: ACCESS_KEY, SECRET_KEY, TOS_ENDPOINT, TOS_REGION, TOS_TEST_DIR
    TOS_TEST_DIR = os.getenv("TOS_TEST_DIR", "your-bucket")
    output_tos_dir = f"tos://{TOS_TEST_DIR}/video_adaptive_keyframes_sampling"
    
    if os.getenv("DAFT_RUNNER", "native") == "ray":
        import logging

        import ray

        def configure_logging():
            logging.basicConfig(
                level=logging.INFO,
                format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S",
            )
            logging.getLogger("tracing.span").setLevel(logging.WARNING)
            logging.getLogger("daft_io.stats").setLevel(logging.WARNING)
            logging.getLogger("DaftStatisticsManager").setLevel(logging.WARNING)
            logging.getLogger("DaftFlotillaScheduler").setLevel(logging.WARNING)
            logging.getLogger("DaftFlotillaDispatcher").setLevel(logging.WARNING)

        ray.init(dashboard_host="0.0.0.0", runtime_env={"worker_process_setup_hook": configure_logging})
        daft.set_runner_ray()
    daft.set_execution_config(actor_udf_ready_timeout=600)
    daft.set_execution_config(min_cpu_per_task=0)

    # Construct the URL using environment variables
    tos_dir_url = os.getenv("TOS_DIR_URL", "las-cn-beijing-public-online.tos-cn-beijing.volces.com")
    samples = {
        "video": [
            f"https://{tos_dir_url}/public/shared_video_dataset/cooking.mp4"
        ]
    }

    ds = daft.from_pydict(samples)

    keyframe_sampler = las_udf(
        VideoAdaptiveKeyframesSampling,
        construct_args={
            "text": "spoon",
            "output_tos_dir": output_tos_dir,
            "max_num_frames": 4,
            "fps": 2.0,
            "batch_size": 16,
            "rank": 0,
            "return_keyframes": True,
            "img_type": ".jpg", 
        },
        num_gpus=1,
        concurrency=1,
        batch_size=1,
    )

    # Use Daft for distributed processing
    ds = ds.with_column("keyframes", keyframe_sampler(col("video")))

    ds.show()
    # ╭────────────────────────────────┬───────────────────────────────────────────────────────────────────────────────╮
    # │ video                          ┆  keyframes                                                                    │
    # │ ---                            ┆ ---                                                                           │
    # │ Utf8                           ┆ Struct[tos_paths: List[Utf8], frame_ids: List[Int64], scores: List[Float32]]  │
    # ╞════════════════════════════════╪═══════════════════════════════════════════════════════════════════════════════╡
    # │ https://las-cn-beijing-publi-… ┆  {tos_paths: [las-cn-beijing…, ...], frame_ids: [123, ...], scores: [...]}    │
    # ╰────────────────────────────────┴───────────────────────────────────────────────────────────────────────────────╯
Last updated: 2026.05.24 15:42:39