Create a data pipeline (Python SDK V2)

Updated at:

Calls PutDataPipelineConfiguration through OSS Python SDK V2 to create a data pipeline (DataPipeline) rule. After the rule is created, OSS automatically vectorizes the raw data in the source bucket and writes the vector data to the specified vector index in the vector bucket.

Prerequisites

  • OSS Python SDK V2 is installed. You can run pip install alibabacloud-oss-v2 to install it.

  • Access credentials are configured by using environment variables. The example in this topic uses EnvironmentVariableCredentialsProvider to read credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

  • A RAM role is created for the data pipeline, and the role is granted the required permissions.

  • The destination vector bucket and the vector index in it are created. The index dimension must match the output dimension of the model you use.

  • DataPipeline operations are forwarded by OSS to the underlying workflow service. Make sure that the source general-purpose bucket and the destination vector bucket are located in the same region.

Sample code

Vectorization with Alibaba Cloud Model Studio

The following example processes the images under the data/ prefix in the source bucket, uses qwen2.5-vl-embedding for vectorization, and writes the vectors to one vector index.

import argparse

import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.dataprocess as oss_dataprocess

parser = argparse.ArgumentParser(description="put data pipeline configuration sample")
parser.add_argument('--region', help='The region of the bucket.', required=True)
parser.add_argument('--endpoint', help='The endpoint of OSS.')
parser.add_argument('--data-pipeline-name', help='The name of the data pipeline.', required=True)
parser.add_argument('--bucket', help='The name of the source bucket.', required=True)
parser.add_argument('--vector-bucket', help='The name of the vector bucket.', required=True)
parser.add_argument('--vector-index', help='The name of the vector index.', required=True)
parser.add_argument('--role', help='The ARN of the RAM role assumed by OSS.', required=True)
parser.add_argument('--api-key', help='The API key of Alibaba Cloud Model Studio (Bailian).', required=True)


def main():
    args = parser.parse_args()

    # Initialize the client. Data pipeline operations use the regular OSS endpoint.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint
    client = oss_dataprocess.Client(cfg)

    try:
        # Describe the source data: process the images under the data/ prefix, including
        # the existing objects and the incremental objects.
        source = oss_dataprocess.models.DataPipelineSource(
            input_bucket=args.bucket,
            input_data_scope='All',
            ignore_delete=False,
            filter_configuration=oss_dataprocess.models.DataPipelineSourceFilterConfiguration(
                prefix_set=['data/'],
                object_media_types=['image'],
            ),
        )

        # Configure the embedding model. These fields cannot be mixed with those of AI VibeStudio.
        embedding_configuration = oss_dataprocess.models.DataPipelineEmbeddingConfiguration(
            embedding_provider='bailian',
            api_key=args.api_key,
            model='qwen2.5-vl-embedding',
            fps=1.0,
        )

        # Configure the vector destination. vector_index_names accepts only one index, and
        # the index dimension must match the model output dimension.
        destination = oss_dataprocess.models.DataPipelineDestination(
            vector_bucket_name=args.vector_bucket,
            vector_index_names=[args.vector_index],
            vector_key_prefix='v1',
        )

        # Assemble the configuration. ignore skips the objects that fail. To use
        # ignoreAndRecord, specify error_bucket and error_prefix (the bucket must differ
        # from the source bucket).
        configuration = oss_dataprocess.models.PutDataPipelineConfigurationConfiguration(
            data_pipeline_description='Vectorize images with Model Studio',
            sources=[source],
            data_pipeline_embedding_configuration=embedding_configuration,
            destination=destination,
            data_pipeline_error=oss_dataprocess.models.DataPipelineError(
                error_mode='ignore',
            ),
        )

        # Create the data pipeline. role is a required parameter.
        result = client.put_data_pipeline_configuration(
            oss_dataprocess.models.PutDataPipelineConfigurationRequest(
                data_pipeline_name=args.data_pipeline_name,
                role=args.role,
                configuration=configuration,
            ))
        print(f'status code: {result.status_code}, request id: {result.request_id}')
    except Exception as e:
        print(f'error:\n{e}')


if __name__ == '__main__':
    main()

Vectorization with AI VibeStudio

The following example processes the images, videos, and documents under the media/ prefix in the source bucket.

import argparse

import alibabacloud_oss_v2 as oss
import alibabacloud_oss_v2.dataprocess as oss_dataprocess

parser = argparse.ArgumentParser(description="put data pipeline configuration sample")
parser.add_argument('--region', help='The region of the bucket.', required=True)
parser.add_argument('--endpoint', help='The endpoint of OSS.')
parser.add_argument('--data-pipeline-name', help='The name of the data pipeline.', required=True)
parser.add_argument('--bucket', help='The name of the source bucket.', required=True)
parser.add_argument('--vector-bucket', help='The name of the vector bucket.', required=True)
parser.add_argument('--role', help='The ARN of the RAM role assumed by OSS.', required=True)


def main():
    args = parser.parse_args()

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint
    client = oss_dataprocess.Client(cfg)

    try:
        # Describe the source data: process the images, videos, and documents under
        # the media/ prefix.
        source = oss_dataprocess.models.DataPipelineSource(
            input_bucket=args.bucket,
            input_data_scope='All',
            ignore_delete=False,
            filter_configuration=oss_dataprocess.models.DataPipelineSourceFilterConfiguration(
                prefix_set=['media/'],
                object_media_types=['image', 'video', 'document'],
            ),
        )

        # Configure the processing template. These fields cannot be mixed with the
        # Alibaba Cloud Model Studio embedding fields. In fast mode, each source file
        # type uses one index. In balanced mode, configure image_text_embedding and
        # video_text_embedding separately for images and videos.
        data_process_configuration = oss_dataprocess.models.DataPipelineDataProcessConfiguration(
            search_mode='fast',
        )

        # Configure the vector destination. Specify the target index for each source
        # file type.
        destination = oss_dataprocess.models.DataPipelineDestination(
            image_embedding=oss_dataprocess.models.ImageEmbedding(
                bucket=args.vector_bucket,
                index_name='ImageEmbedding',
                prefix='v2',
            ),
            video_frame_embedding=oss_dataprocess.models.VideoFrameEmbedding(
                bucket=args.vector_bucket,
                index_name='VideoFrameEmbedding',
                prefix='v2',
            ),
            document_chunk_embedding=oss_dataprocess.models.DocumentChunkEmbedding(
                bucket=args.vector_bucket,
                index_name='DocumentChunkEmbedding',
                prefix='v2',
            ),
        )

        # Assemble the configuration. model_tier currently supports only standard.
        configuration = oss_dataprocess.models.PutDataPipelineConfigurationConfiguration(
            data_pipeline_description='Vectorize media with AI VibeStudio',
            sources=[source],
            model_tier='standard',
            data_pipeline_data_process_configuration=data_process_configuration,
            destination=destination,
            data_pipeline_error=oss_dataprocess.models.DataPipelineError(
                error_mode='ignore',
            ),
        )

        result = client.put_data_pipeline_configuration(
            oss_dataprocess.models.PutDataPipelineConfigurationRequest(
                data_pipeline_name=args.data_pipeline_name,
                role=args.role,
                configuration=configuration,
            ))
        print(f'status code: {result.status_code}, request id: {result.request_id}')
    except Exception as e:
        print(f'error:\n{e}')


if __name__ == '__main__':
    main()