All Products
Search
Document Center

Intelligent Media Management:IMM SDK for Python

Last Updated:Dec 26, 2024

Alibaba Cloud OpenAPI Explorer provides API documentation, API debugging, and SDK examples to help you get started with API development. This topic describes how to install and use Intelligent Media Management (IMM) SDK for Python.

Prerequisites

  • An AccessKey pair is created and obtained. For more information, see Create an AccessKey pair.

  • OSS is activated, a bucket is created, and objects are uploaded to the bucket. For more information, see Upload objects.

  • IMM is activated. For more information, see Activate IMM.

  • A project is created in the IMM console. For more information about how to create a project by using the IMM console, see Create a project.

    Note
    • You can also create a project by calling the CreateProject operation. For more information, see CreateProject.

    • You can call the ListProjects operation to query existing projects in a specific region. For more information, see ListProjects.

Install the SDK

Important

To use IMM API V2020-09-30, you must use IMM SDK V2020-09-30.

For more information about how to use IMM SDK for Python, see Quick Start.

Credentials

The following types of access credentials are supported:

  • Temporary access credentials: In scenarios where high security is critical, such as temporary authorization of access to IMM, we recommend that you use temporary access credentials. Temporary access credentials are valid within the specified period of time, which helps prevent credential leaks. Temporary access credentials support fine-grained access control, which prevents security risks caused by excessive permissions.

  • Long-term access credentials: To ensure data security, we recommend that you do not use long-term access credentials. In scenarios where convenience is essential, long-term access credentials eliminate the need for multiple refreshes within a long period of time. We recommend that you change your long-term access credentials every three months to ensure account security. If long-term access credentials are leaked or no longer used, you must delete or disable the long-term access credentials at the earliest opportunity to reduce security risks.

Use temporary access credentials

You can configure temporary access credentials for temporary access to IMM by using IMM SDK for Python. For more information, see Configure environment variables to store temporary access credentials.

The following sample code provides an example on how to detect faces and face attributes in an image within a project in the China (Hangzhou) region by using temporary access credentials.

  1. Create a demon.py file and write the following content to the file.

    import os
    import sys
    
    from typing import List
    
    from alibabacloud_imm20200930.client import Client as imm20200930Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_imm20200930 import models as imm_20200930_models
    from alibabacloud_tea_util import models as util_models
    from alibabacloud_tea_util.client import Client as UtilClient
    from alibabacloud_sts20150401.client import Client as Sts20150401Client
    from alibabacloud_sts20150401 import models as sts_20150401_models
    
    
    class Sample:
        def __init__(self):
            pass
    
        @staticmethod
        def create_client() -> imm20200930Client:
            """
            Use your AccessKey ID and AccessKey secret to initialize the client.
            @return: Client
            @throws Exception
            """
            sts_config = open_api_models.Config(
                # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. 
                access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. 
                access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
            )
            # Specify the Security Token Service (STS) endpoint for the region in which the IMM project resides.
            sts_config.endpoint = "sts-share.cn-hangzhou.aliyuncs.com"
            sts_client = Sts20150401Client(sts_config)
            # Call the AssumeRole operation.
            assume_role_request = sts_20150401_models.AssumeRoleRequest(
                # Specify the validity period of the STS token. Unit: seconds.
                duration_seconds=3600,
                # Specify the name of the role session.
                role_session_name="immtest",
                # role arn
                role_arn="acs:ram::xxxxxxx:role/imm-test-role-for-amp"
            )
            runtime = util_models.RuntimeOptions()
            response = sts_client.assume_role_with_options(assume_role_request, runtime)
            credential = response.to_map().get("body", dict()).get("Credentials", dict())
            # Use the STS token to create an IMM client.
            imm_config = open_api_models.Config(
                access_key_id=credential["AccessKeyId"],
                access_key_secret=credential["AccessKeySecret"],
                security_token=credential["SecurityToken"])
            # Specify the IMM endpoint. For a list of IMM endpoints for supported regions, visit https://api.alibabacloud.com/product/imm.
            imm_config.endpoint = f'imm.cn-hangzhou.aliyuncs.com'
            return imm20200930Client(imm_config)
    
        @staticmethod
        def main(
            args: List[str],
        ) -> None:
            client = Sample.create_client()
            detect_image_faces_request = imm_20200930_models.DetectImageFacesRequest(
                source_uri='oss://your-bucket-name/your-path/test.jpg',
                project_name='immtest'
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Print the response of the API operation if necessary.
                response = client.detect_image_faces_with_options(
                    detect_image_faces_request, runtime)
                print(response.body.to_map())
            except Exception as error:
                # Handle exceptions with caution in your actual business scenario and never ignore exceptions in your project. In this example, error messages are printed. 
                # Display error messages.
                print(error.message)
                # Show the URL for troubleshooting.
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
    
    if __name__ == '__main__':
        Sample.main(sys.argv[1:])
  2. Run the python demo.py command. A response similar to the following one is returned:

    {
       "Faces": [
          {
             "Age": 25,
             "AgeSD": 7,
             "Attractive": 0.998,
             "Beard": "none",
             "BeardConfidence": 1,
             "Boundary": {
                "Height": 127,
                "Left": 81,
                "Top": 62,
                "Width": 96
             },
             "Emotion": "happiness",
             "EmotionConfidence": 0.999,
             "FaceQuality": 0.998,
             "FigureClusterId": "figure-cluster-id-unavailable",
             "FigureConfidence": 0.999,
             "FigureId": "30f18b25-db81-4dc6-8461-fd63ab0ef16d",
             "FigureType": "face",
             "Gender": "female",
             "GenderConfidence": 1,
             "Glasses": "none",
             "GlassesConfidence": 1,
             "Hat": "none",
             "HatConfidence": 1,
             "HeadPose": {
                "Pitch": -16.989,
                "Roll": 6.006,
                "Yaw": 7.47
             },
             "Mask": "none",
             "MaskConfidence": 0.83,
             "Mouth": "open",
             "MouthConfidence": 0.998,
             "Sharpness": 1
          }
       ],
       "RequestId": "28084591-0A06-0981-9AD5-B0FBD0967FD7"
    }            

Use long-term access credentials

To access IMM by using IMM SDK for Python based on long-term access credentials, you need to configure long-term access credentials first. For more information, see Configure long-term access credentials.

The following sample code provides an example on how to create a document conversion task in the China (Beijing) region by using IMM SDK for Python V1.27.3.

  1. Create a demon.py file and write the following content to the file.

    # -*- coding: utf-8 -*-
    # This file is auto-generated, don't edit it. Thanks.
    import os
    import sys
    
    from typing import List
    
    from alibabacloud_imm20200930.client import Client as imm20200930Client
    from alibabacloud_tea_openapi import models as open_api_models
    from alibabacloud_imm20200930 import models as imm_20200930_models
    from alibabacloud_tea_util import models as util_models
    from alibabacloud_tea_util.client import Client as UtilClient
    
    
    class Sample:
        def __init__(self):
            pass
    
        @staticmethod
        def create_client() -> imm20200930Client:
            """
            Use your AccessKey ID and AccessKey secret to initialize the client.
            @return: Client
            @throws Exception
            """
            # If the project code is leaked, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. The following lines are provided for reference only. 
            # For security reasons, we recommend that you use temporary access credentials that are provided by STS. For more information, visit https://www.alibabacloud.com/help/en/sdk/developer-reference/v2-manage-php-access-credentials. 
            config = open_api_models.Config(
                # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured. ,
                access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                # Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured. ,
                access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
            )
            # Specify the IMM endpoint. For more information about endpoints, visit https://api.aliyun.com/product/imm.
            config.endpoint = f'imm.cn-beijing.aliyuncs.com'
            return imm20200930Client(config)
    
        @staticmethod
        def main(
            args: List[str],
        ) -> None:
            client = Sample.create_client()
            notification_mns = imm_20200930_models.MNS(
                topic_name='mns_topic_name'
            )
            notification = imm_20200930_models.Notification(
                mns=notification_mns,
                extended_message_uri='oss://your-bucket-name/test-object.json'
            )
            create_office_conversion_task_request = imm_20200930_models.CreateOfficeConversionTaskRequest(
                project_name='immtest',
                source_uri='oss://your-bucket-name/your-path/your-doc.doc',
                target_uri='oss://your-bucket-name/output',
                target_uriprefix='oss://your-bucket-name/output',
                target_type='png',
                notification=notification
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Print the response of the API operation if necessary.
                client.create_office_conversion_task_with_options(create_office_conversion_task_request, runtime)
            except Exception as error:
                # Handle exceptions with caution in your actual business scenario and never ignore exceptions in your project. In this example, error messages are printed. 
                # Display error messages.
                print(error.message)
                # Show the URL for troubleshooting.
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
        @staticmethod
        async def main_async(
            args: List[str],
        ) -> None:
            client = Sample.create_client()
            notification_mns = imm_20200930_models.MNS(
                topic_name='mns_topic_name'
            )
            notification = imm_20200930_models.Notification(
                mns=notification_mns,
                extended_message_uri='oss://your-bucket-name/test-object.json'
            )
            create_office_conversion_task_request = imm_20200930_models.CreateOfficeConversionTaskRequest(
                project_name='immtest',
                source_uri='oss://your-bucket-name/your-path/your-doc.doc',
                target_uri='oss://your-bucket-name/output',
                target_uriprefix='oss://your-bucket-name/your-path/your-doc-output',
                target_type='png',
                notification=notification
            )
            runtime = util_models.RuntimeOptions()
            try:
                # Print the response of the API operation if necessary.
                await client.create_office_conversion_task_with_options_async(create_office_conversion_task_request, runtime)
            except Exception as error:
                # Handle exceptions with caution in your actual business scenario and never ignore exceptions in your project. In this example, error messages are printed. 
                # Display error messages.
                print(error.message)
                # Show the URL for troubleshooting.
                print(error.data.get("Recommend"))
                UtilClient.assert_as_string(error.message)
    
    
    if __name__ == '__main__':
        Sample.main(sys.argv[1:])
  2. Run the python demo.py command. A response similar to the following one is returned:

    // The response of the document conversion operation. 
    {
        "TaskId": "OfficeConversion-65ab9c57-4598-4eb4-bf73-****",
        "RequestId": "A637DBBA-3E98-00F5-B0F2-****",
        "EventId": "011-1LNuW4Ws2lRfjGsZl4a****"
    }
    
    // The SMQ message. If the value of the Status field is Succeeded, the document conversion task is successful. 
    {
        "ProjectName": "immtest",
        "DatasetName": "",
        "RequestId": "A637DBBA-3E98-00F5-B0F2-****",
        "StartTime": "2022-07-19T10:41:44.649Z",
        "EndTime": "2022-07-19T10:41:45.26Z",
        "UserData": "",
        "TaskType": "OfficeConversion",
        "TaskId": "OfficeConversion-65ab9c57-4598-4eb4-bf73-****",
        "Status": "Succeeded",
        "Code": "",
        "Message": ""
    }