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

Lake AI Service

Copy page
Download PDF
Hands-on practice
Hands-on practice: Video data ingestion and processing
Copy page
Download PDF
Hands-on practice: Video data ingestion and processing

Practice objectives

By following the steps described in this document, you can fully experience the end-to-end process from video data ingestion, video dataset processing, to text-to-image and image-to-image search. Through this process, you will master the following skills:

  • You will gain a clearer understanding of the core logic of video processing scenarios based on LAS, master the technical implementation details and procedures, and further enhance your ability to break down requirements and design solutions for actual customer business scenarios.
  • You will learn about the data processing operators of LAS (Lakehouse Analytics Service), including the process for invoking online and offline operators.
  • You will understand the basic process for using LAS Key features, including: datasets (creating datasets, reading and writing data), queue resources, and development machines.

Large visual models can interpret visual information in videos, completing tasks such as describing objects within them and analyzing action logic. These models can be used for automated video content review, intelligent monitoring analysis, and more, significantly reducing labor costs. They are suitable for fields such as intelligent security, sports event analysis, and media content management.
The common approaches to constructing business systems based on VLM are as follows.
Image
Audio and video content can be stored in Volcano Engine TOS. After ingesting audio and video data into the lake via LAS (converting to Lance format data), you can call LAS data processing operators to process the audio and video data, and perform content understanding/vectorization on the audio and video content, facilitating subsequent consumption of the audio and video content.

Preparation

Prepare experimental data

This practice uses key frame extraction from video files as an example to introduce the operational process of video data ingestion and processing. Prepare a test video file in a common format such as MP4, AVI, or MOV, and follow the steps in this practice to complete the process.

TOS

You need to enable Volcano Engine Object Storage TOS and create a TOS bucket to store the test video data during this experiment.

Preparation

Key operational points

Reference documentation

Configuration example

Create Bucket

  • All practical operations in this exercise use resources from the North China 2 (Beijing) region. Therefore, when creating a Bucket:
    • You must create a Bucket in the Beijing region.
    • Keep all other parameters at their default settings.

Create storage bucket

Bucket name: las-doctest
Image

Access control (IAM)

You need to log in to the Access Control (IAM) console and prepare an AK and SK for subsequent API access to TOS and LAS.

Preparation

Key operational points

Reference documentation

Configuration example

Obtain AK and SK

To ensure the security of access to TOS/LAS services, you must provide valid access keys (AK/SK) for subsequent authentication.

  • The access key permissions of the primary account are extensive. You can create a sub-account with TOS and LAS operation permissions on the access control (IAM) page, enable access keys for the sub-account, and then use the sub-account's access keys going forward.
  • Access key information is highly sensitive. Leakage may result in data insecurity. Therefore, it is recommended to configure AK and SK information as environment variables in subsequent development environments.

View AKSK information

Image

LAS

You need to enable the LAS service and create the queue resources and development machine environment required for this experiment.

Preparations

Operation key points

Reference documents

Configuration example

Queue resources

  • If you have already created LAS queue resources, you can use them.
  • If you have not previously created queue resources, you need to create one. When creating queue resources for practical exercises:
    • It is recommended to use resources in the North China 2 (Beijing) region.
    • For experimental practice, you can select resources with the minimum CPU specification. There is no need to enable GPU resources.
    • Other parameters can remain at their default values.

Queue management

See operation key points

LAS API Key

Before you call the LAS online function, you need to first generate an API Key for authentication.

  • If you already have an LAS API Key, you can use the existing LAS API Key. Otherwise, you need to create an LAS API Key.
  • Because API Key information is highly sensitive, leaking the API Key may result in others consuming your model usage, resulting in potential losses. Therefore, after obtaining the API Key, it is recommended to configure it as an environment variable in subsequent development environments to ensure secure and proper use.

warning

LAS provides you with two types of data processing operators: offline and online. Only online operators require LAS API Key authentication.

  • Online operators are invoked directly by calling the operator API.
  • Offline operators use the Daft engine for operator invocation. LAS provides the VeDaft engine, which integrates the SDK for offline operator invocation, enabling more efficient scheduling and execution of batch data processing tasks.

Obtain and configure the API Key

See operation key points

Development machine

Before you call the LAS offline function, you need to prepare the development environment for calling the offline function.

  • LAS provides you with a development machine with pre-installed images such as the veDaft engine. You can directly create an LAS development machine. After creation, you can remotely log in to the development machine to develop and debug data processing tasks for offline functions. When creating a development machine:
    • Queue: Select the queue resources prepared above.
    • Image: It is recommended to select the latest version of the built-in ve-daft image. The version used in this example is: 0.7.2.post4-py3.11-ubuntu24.04.
    • When creating a development machine, it is recommended to configure the above TOS AK/SK, Endpoint, Region, and LAS API Key as environment variables. If you did not configure them when creating the development machine, you can also configure them after logging in to the development machine.
    • After generating the SSH public key locally using the ssh-keygen -t rsa command and configuring it on the development machine, you can conveniently obtain the remote login command directly from the development machine page.
    • Keep all other parameters at their default values.
  • To develop and debug offline operators in your own environment, you must first deploy the Daft engine. For details, see: Quick start.

Image

Practice steps

Step 1: Create a video dataset

warning

The main purpose of this practice step is to upload videos to the TOS Bucket and create a video dataset in LAS. Subsequently, you can directly preview, process, and perform other operations on videos in the LAS video dataset.

Upload video to TOS bucket

After logging in to the TOS product console, upload the video to be processed to the TOS bucket.

Operation steps

Operation key points

Reference documentation

Configuration example

Upload video

Upload the video to be processed to the prepared TOS Bucket. You can create folders as needed and upload videos to the folders.
Image
After the upload is complete, you can click "Copy path" to record the TOS path where the current video data is located.

Upload file

The TOS path is: tos://las-doctest/video

Create a video dataset

Log in to the LAS console, click Datasets > Common dataset in the left navigation bar, and after entering the dataset page, click "Create dataset". Refer to the following configuration points to set the dataset parameters. After completing the configuration, click "Create" to finish creating the video dataset.

Operation steps

Operation key points

Reference documentation

Configuration example

Create video dataset

Image

  • Dataset name: Custom dataset name.
  • Data source: Select TOS and set the TOS path to the TOS path where the video to be processed was uploaded in the previous step.
  • Dataset format: Select "Video".

Create a dataset

  • Dataset name: las_dataset_video.
  • TOS path for the data source: tos://las-doctest/video

Preview video data

After the dataset is created, you can view the basic information of the dataset on the dataset details page. For video datasets, previewing the first ten videos is supported.
Image

Step summary/Extended knowledge

  • Common dataset operations:
    • After the LAS dataset is created, you can manage permissions for the dataset and authorize it for use by other sub-users under the same primary account.
    • Cross-account sharing of the dataset is also supported. After sharing, the corresponding primary or sub-account will have the granted dataset operation permissions. For details, see Dataset sharing.
  • At this point, although we have a video dataset, it is not much different from storing it in TOS. Demonstrating the advantages of the dataset—enabling better, faster, and smarter consumption of video data—is our goal. You can continue with the following sections to perform video data lake ingestion, data processing, and other operations.

Step 2: Video data lake ingestion

warning

The main purpose of this practice step is to convert the video dataset to a Lance dataset, enabling video data lake ingestion and facilitating subsequent data processing operations such as video frame extraction.

Create the TOS path for the Lance dataset

You need to first log in to the TOS console and prepare a TOS path for storing the converted Lance dataset data. The TOS path for the Lance dataset in this example is: tos://las-doctest/video2lance/.

Configure environment variables

This step is mainly performed on the development machine, where VeDaft is used to call the SDK for reading and writing operations on the dataset. Since this involves accessing the TOS Bucket, it is recommended to configure certain authentication parameters and fixed path parameters as environment variables in the development environment for easier reference in subsequent code execution.

  1. You can refer to the following content to prepare the environment variable configuration.

    # Region settings. This example uses the North China 2 - Beijing region
    export REGION="cn-beijing"
    
    # Authentication AK-related environment variables
    # Authentication sk and ak for accessing TOS and LAS
    export LAS_TOS_SECRET_KEY="<your_sk>"
    export LAS_TOS_ACCESS_KEY="<your_ak>"
    
    # TOS access-related environment variables
    # TOS access endpoint
    export LAS_TOS_ENDPOINT="https://tos-cn-beijing.ivolces.com"
    # TOS endpoint (for TOSConfig)
    export TOS_ENDPOINT="https://tos-cn-beijing.ivolces.com"
    
  2. In the development machine environment, run the source env.sh command to activate the environment variables.

Convert the video dataset to a Lance dataset

  1. Run the following Python script on the development machine to create a new Lance dataset, convert the video data to the Lance format of the Lance dataset, and write it to the new Lance dataset. The core sample code is as follows.
    # Please execute the following code on the LAS development machine
    import os
    
    """
    Convert to Lance Dataset
    """
    import daft
    from daft.io import CreateLasDatasetOptions, IOConfig, LanceWriteOptions
    from daft.las.io import TOSConfig
    
    # You can customize the path for your new dataset
    dataset_name = "las_dataset_video"
    lance_tos_dir = f"tos://las-doctest/video2lance/{dataset_name}.lance"
    LANCE_DATASET_FORMAT = "lance"
    
    # Create the relevant configuration
    io_config = IOConfig(s3=TOSConfig.from_env().to_s3_config())
    write_options = LanceWriteOptions(io_config=io_config, uri=lance_tos_dir)
    create_ds_options = CreateLasDatasetOptions(
        nick_name="daft_test_lance_write",
        privacy="public",
        description="This is my dataset",
    )
    
    # Read the raw data
    df = daft.read_las_dataset(name=dataset_name)
    
    # Create here
    new_dataset_name = dataset_name + "_lance"
    df.write_las_dataset(
        name=new_dataset_name,
        format=LANCE_DATASET_FORMAT,
        write_options=write_options,
        create_ds_options=create_ds_options,
    )
    
    # Read the newly converted dataset
    df = daft.read_las_dataset(name=new_dataset_name)
    print("\n\nnew dataset:")
    df.show()
    

You need to modify the following parameters.

  • dataset_name: Set to the video dataset name. In this example, it is las_dataset_video
  • lance_tos_dir: Set the TOS path for the newly converted Lance dataset prepared in the previous steps.

Other parameters can be kept as the example values.

  1. After the script is executed, the page will display the details of the newly converted Lance dataset. An example output is shown below.
new dataset:
╭────────────────────────────────┬───────────┬──────────╮
│ video                          ┆ size      ┆ num_rows │
│ ---                            ┆ ---       ┆ ---      │
│ String                         ┆ Int64     ┆ Int64    │
╞════════════════════════════════╪═══════════╪══════════╡
│ s3://las-doctest/video/LAS AI… ┆ 225602609 ┆ None     │
╰────────────────────────────────┴───────────┴──────────╯

The converted Lance dataset contains the fields "video", "size", and "num_rows". Details:

  • The video field: the TOS path (in s3 format) of each video data in the current Lance dataset.
  • The size field: the size of each video.

If an ERROR message appears in the output but the dataset data is returned normally, the ERROR message can be ignored.

View the Lance dataset

After completing the operation to convert to a Lance dataset, you can log in to the LAS console and view the newly created Lance dataset on the dataset list page.
Image

Step summary/Further knowledge

  • Register metadata: Similar to the steps above, after converting to a Lance dataset, you can manage permissions for the dataset. In addition, you can register this dataset in the LAS Catalog, so you can later view the metadata details of the dataset in the LAS Catalog. When the dataset fields change, the dataset metadata in the Catalog will also be automatically updated in real time.

Step 3: Preliminary processing of video data

warning

The main purpose of this step is to perform simple processing on the videos, writing the binary video data into the Lance dataset ingested into the lake. This allows video content to be previewed directly in the Lance dataset and prepares for subsequent operations such as video content understanding and vectorization.
The main purpose of this step is to invoke LAS data processing operators to enhance the video data:

  • Invoke the video keyframe extraction operator: Use a large model to understand the video content, write the understood content into the Lance dataset, and facilitate subsequent application scenarios for consuming video data, such as text-to-image retrieval.

Invoke the multimodal vectorization operator: Use a large model to vectorize the video, write the vectorization results into the Lance dataset, and facilitate subsequent application scenarios for consuming video data, such as image-to-image retrieval.

Configure environment variables

  1. Refer to the following to configure environment variables.
# Region settings. In this example, North China 2 - Beijing region is used
export REGION="cn-beijing"

# Authentication AK-related environment variables
# Authentication sk and ak for accessing TOS and LAS
export LAS_TOS_SECRET_KEY="<your_sk>"
export LAS_TOS_ACCESS_KEY="<your_ak>"

# TOS access-related environment variables
# TOS access endpoint
export LAS_TOS_ENDPOINT="https://tos-cn-beijing.ivolces.com"
# TOS endpoint (for TOSConfig)
export TOS_ENDPOINT="https://tos-cn-beijing.ivolces.com"

# DAFT executor type, set to local mode
export DAFT_RUNNER="native" 

This step adds:

  • DAFT_RUNNER: Set the Daft executor for the video data processing operator to local mode.
  1. In the development machine environment, execute the source env.sh command to activate the environment variables.

Video data processing: Video key frame extraction operator

The following uses Video keyframe extraction as an example to demonstrate how to process video. During processing, a new Lance dataset will be created, and key parameters such as the TOS path of the original video, the binary result and TOS path after video frame extraction, and so on will be written into the newly created Lance dataset.

Run the following script on the development machine.

# Import features from future versions to ensure compatibility
from __future__ import annotations

# Import necessary libraries
import base64  # For Base64 encoding and decoding
import hashlib  # For generating SHA256 hashes
import os  # For operating system interactions, such as obtaining environment variables

import pyarrow as pa  # For processing columnar data

import daft  # Import the daft data processing framework
from daft import DataType, col  # Import data types and column operation tools
from daft.io import (
    CreateLasDatasetOptions,  # Configuration options for creating LAS datasets
    IOConfig,  # IO configuration class
    LanceWriteOptions,  # Lance format write options
)
from daft.io.object_store_options import io_config_to_storage_options  # Convert IO configuration to storage options
from daft.daft import IOConfig  # Import IOConfig again (possibly to ensure correctness)
from daft.las.functions.udf import las_udf  # Import the LAS user-defined function decorator
from daft.las.functions.video import VideoKeyframes  # Import the video key frame processing function
from daft.las.io.tos import TOSConfig  # Import the TOS storage configuration


# Set the TOS path where the video source file is located
TOS_TEST_DIR = "tos://las-doctest/video/LAS AI Product Introduction.mp4"
# Set the TOS path for storing the resulting images after video frame extraction
TOS_TEST_OUTPUT_DIR = "tos://las-doctest/video/result/"

# Create a new Lance dataset from the video frame extraction results; the following parameters are used to configure the new Lance dataset
# Customize the name of the new Lance dataset
DATASET_NAME = "las_dataset_video_lance_kf"
# Set the TOS path for the new Lance dataset
TOS_TEST_LANCE_DIR = "tos://las-doctest/video2lance/las_dataset_video_kf.lance"
# After frame extraction, customize the video path column name when writing to the Lance dataset
VIDEO_COLUMN = os.getenv("VIDEO_COLUMN", "video")
# After frame extraction, customize the video key frame column name when writing to the Lance dataset
VIDEO_KEYFRAMES_COLUMN = os.getenv("VIDEO_KEYFRAMES_COLUMN", "video_keyframes")
# After frame extraction, customize the TOS path column name for the video key frames when writing to the Lance dataset
VIDEO_KEYFRAMES_TOS_COLUMN = os.getenv("VIDEO_KEYFRAMES_TOS_COLUMN", "video_keyframes_tos")


# If the DAFT executor is ray, initialize ray
if os.environ['DAFT_RUNNER'] == 'ray':
    import ray  # Import the ray distributed computing framework


    ray.init(address='auto')  # Automatically connect to the ray cluster


# Define a DAFT UDF: convert a Base64 string to binary data
# ✅ New syntax: use @daft.func instead of @daft.udf (stateless function)
@daft.func
def base64_to_binary(base64_str: DataType.string()) -> DataType.binary():
    import base64 as b64
    return b64.b64decode(base64_str)


# Define a DAFT UDF: generate a SHA256 hash value
@daft.func
def generate_sha256_hash(s: DataType.string()) -> DataType.string():
    import hashlib
    return hashlib.sha256(str(s).encode()).hexdigest()


# Main function entry point
if __name__ == "__main__":
    # Create IO configuration from environment variable settings (adapted for TOS storage)
    io_config = IOConfig(s3=TOSConfig.from_env().to_s3_config())


    # Create sample data containing video paths
    samples = {VIDEO_COLUMN: [f"{TOS_TEST_DIR}"]}
    # Create a daft dataset from a dictionary
    ds = daft.from_pydict(samples)
    
    # Create a video key frame extractor UDF
    extractor = las_udf(
        VideoKeyframes,  # Use the video key frame extraction function
        construct_args={
            "method": "I_frame",  # Extraction method: I-frame
            "keyframes_cnt": 50,  # Number of extracted key frames
            "output_tos_dir": f"{TOS_TEST_OUTPUT_DIR}",  # Output directory in TOS
        },
    )
    
    # Apply the extractor to add a key frame column to the dataset
    ds = ds.with_column(VIDEO_KEYFRAMES_COLUMN, extractor(col(VIDEO_COLUMN)))


    # Extract the TOS path column from the key frame results
    ds = ds.with_column(VIDEO_KEYFRAMES_TOS_COLUMN, col(VIDEO_KEYFRAMES_COLUMN)["tos_paths"])


    # Extract the base64-encoded image data from the key frame results
    ds = ds.with_column(VIDEO_KEYFRAMES_COLUMN, col(VIDEO_KEYFRAMES_COLUMN)["base64"])
    # Expand the key frame data and corresponding TOS paths (one row becomes multiple rows)
    ds = ds.explode(col(VIDEO_KEYFRAMES_COLUMN), col(VIDEO_KEYFRAMES_TOS_COLUMN))
    # Convert the base64-encoded image data to binary
    ds = ds.with_column(VIDEO_KEYFRAMES_COLUMN, base64_to_binary(col(VIDEO_KEYFRAMES_COLUMN)))
    # Generate a data item ID (SHA256 hash) based on the TOS path
    ds = ds.with_column("__data_item_id", generate_sha256_hash(col(VIDEO_KEYFRAMES_TOS_COLUMN)))


    # Set the data storage format to lance
    format = "lance"
    # Configure Lance write options
    write_options = LanceWriteOptions(uri=TOS_TEST_LANCE_DIR, io_config=io_config)
    # Print the IO configuration (for debugging)
    print(io_config)
    
    # Configure options for creating the LAS dataset
    create_ds_options = CreateLasDatasetOptions(
        nick_name=DATASET_NAME,  # Dataset nickname
        privacy="public",  # Privacy setting: public
        description="This is test dataset"  # Dataset description
    )
    
    # Write the dataset to LAS
    ds.write_las_dataset(
        name=DATASET_NAME,  # Dataset name
        format=format,  # Storage format
        write_options=write_options,  # Write options
        create_ds_options=create_ds_options,  # Create dataset options
    )
    
# Read the dataset
df = daft.read_las_dataset(name=DATASET_NAME)
df.show()    

You need to modify some parameters as needed:

  • TOS_TEST_DIR: Set to the TOS path where the video files to be processed are located.
  • TOS_TEST_OUTPUT_DIR: Set to the TOS path where the extracted keyframe images are located after video keyframe extraction.
  • DATASET_NAME: Set to the name of the Lance dataset for the newly created video keyframe extraction results.
  • TOS_TEST_LANCE_DIR: The TOS path of the newly added Lance dataset.
  • VIDEO_COLUMN/VIDEO_KEYFRAMES_COLUMN/VIDEO_KEYFRAMES_TOS_COLUMN: After video keyframe extraction is completed, the column names in the Lance dataset for the original video TOS path, video keyframes, and the TOS path where the video keyframes are located.

You can also modify the relevant parameters of the video keyframe extraction operator as needed:

  • method: Keyframe extraction method. In this example, it is set to I_frame.
  • keyframes_cnt: Number of keyframes to extract. In this example, it is set to 50, extracting 50 keyframe images.

View the results of video data processing

In the LAS dataset, you can see the created video keyframe extraction result dataset. Click "Data Details" to view the extracted video result images stored in the data lake in Lance format.
Image

Last updated: 2026.05.22 13:51:37