All Products
Search
Document Center

Platform For AI:AI portrait solution

Last Updated:Jun 21, 2026

The AI portrait solution automatically trains a user-specific LoRA model and uses it with template images to generate personalized AI portraits. Elastic Algorithm Service (EAS) is a model serving platform provided by PAI. This solution provides a deployable algorithm workflow as an EAS online service, which includes the APIs for generating AI portraits. This topic describes how to deploy the EAS online services and call their APIs to generate AI portraits.

Background information

EAS features

EAS is a model service platform provided by PAI. The AI Portrait solution uses the following core features of EAS:

  • Deploy model services, including the verification service, training service, and prediction service, using a custom image. The AI Portrait solution uses this feature to provide three API services: image verification, LoRA training, and image generation. It also supports request load balancing and auto scaling for GPU instances.

  • Asynchronous queue operations let you query and manage queue consumption status and set priorities. For more information, see Asynchronous inference service.

  • EAS provides Python and Java SDKs to pass custom parameters. For more information, see Service invocation SDK.

AI portrait algorithm workflow

  1. Image verification

    Checks that the image quality meets requirements.

  2. LoRA training

    This stage first preprocesses and checks images for quality, then uses LoRA to automatically train and evaluate them, generating an optimized model.

  3. Image generation

    1. Image preprocessing.

    2. Initial image generation.

    3. Secondary image generation.

Prerequisites

  • You have configured a VPC with internet access, which includes the following:

    1. Creating a VPC, a vSwitch, and a security group. For more information, see Create an IPv4 VPC and Create a security group.

    2. Creating a NAT Gateway for the VPC, associating an EIP with it, and configuring an SNAT entry. For more information, see Use the SNAT feature of a NAT Gateway to access the internet.

  • You have activated PAI-EAS and created a default workspace. For more information, see Activate PAI-EAS and create a default workspace.

  • The RAM user that deploys the model must have administrative permissions for PAI-EAS. For more information, see Cloud service dependencies and authorization: EAS.

  • For model training and portrait creation, 5 to 20 training images and 1 template image are prepared. The following image formats are supported: .jpg, .jpeg, and .png. Make sure that the size of each image is greater than 512 x 512 pixels.

    • Single-person portrait: The template image must contain the face of a person. The faces in multiple training images belong to the same person.

    • Multi-person portrait: The template image must contain multiple faces, and the number of faces must be the same as the value of the model_id parameter specified for model training.

Usage limitations

This solution is available only in the China (Beijing) and Singapore regions.

PAI-EAS model service

Verification service

  1. Log on to the PAI console. Select a region on the top of the page. Then, select the desired workspace and click Elastic Algorithm Service (EAS).

  2. Click Deploy Service. In the Custom Model Deployment section, click Custom Deployment.

  3. On the Custom Deployment page, configure the following parameters.

    • In the Basic Information section, set the service name. For example, photog_check.

    • In the Environment Information section, configure the following parameters:

      Parameter

      Description

      Deployment Method

      Select Image-based Deployment and Asynchronous Queue.

      Image Configuration

      Select Image Address and enter the image URL in the text box. The URLs are as follows:

      • China (Beijing): registry.cn-beijing.aliyuncs.com/mybigpai/photog_pub:check.1.0.0.pub.

      • Singapore: registry.ap-southeast-1.aliyuncs.com/mybigpai/photog_pub:check.1.0.0.pub.

      Mount storage

      Configure the storage for your code. The following mount methods are supported:

      • OSS

        • Uri: Select the path to your OSS bucket. For example, oss://examplebucket/.

        • Mount Path: Set the value to /photog_oss.

      • NAS

        • Select File System: Select a NAS file system.

        • Mount Target: Select a NAS mount target.

        • File System Path: Specify the source path in the NAS file system to mount, such as /.

        • Mount Path: Set the value to /photog_oss.

      Command

      Set the value to python app.py.

      Port Number

      Set the value to 7860.

    • In the Resource Information section, configure the following parameters:

      Parameter

      Description

      Resource Type

      Select Public Resources.

      Deployment

      For instance type, select a GPU instance from the GU30 series. We recommend the ml.gu7i.c32m188.1-gu30 instance type.

      Configure a system disk

      Set the size to 120 GiB.

    • In the asynchronous queue section, configure the following parameters:

      Parameter

      Description

      Resource Type

      Select Public Resource Group.

      Deployment

      Configure the following parameters:

      • minimum number of instances: 1

      • CPU: 8 cores

      • Memory: 64 GB

      Maximum Data for A Single Input Request

      Set the value to 20480 KB to prevent errors from oversized requests.

      Maximum Data for A Single Output

    • In the Network Information section, select your VPC, vSwitch, and security group.

    • In the Service Configuration section, click Edit to add the following parameters. You can refer to the complete configuration example below.

      Parameter

      Description

      metadata

      Add the following parameters:

      "rpc": {
                  "keepalive": 3600000,
                  "worker_threads": 1
              }
      • keepalive: The maximum processing time for a single request, in milliseconds. Set the value to 3600000.

      • worker_threads: The number of threads in each EAS instance for concurrent request processing.

        The default value is 5, which allows a single instance to process up to five tasks concurrently. We recommend that you set this parameter to 1 to ensure that requests are processed sequentially.

      queue

      Add the "max_delivery": 1 parameter to prevent multiple redeliveries after a failure.

      The following is a complete configuration example:

      {
          "metadata": {
              "name": "photog_check",
              "instance": 1,
              "rpc": {
                  "keepalive": 3600000,
                  "worker_threads": 1
              },
              "type": "Async"
          },
          "cloud": {
              "computing": {
                  "instance_type": "ml.gu7i.c32m188.1-gu30",
                  "instances": null
              },
              "networking": {
                  "vswitch_id": "vsw-2ze4o9kww55051tf2****",
                  "security_group_id": "sg-2ze0kgiee55d0fn4****",
                  "vpc_id": "vpc-2ze5hl4ozjl4fo7q3****"
              }
          },
          "features": {
              "eas.aliyun.com/extra-ephemeral-storage": "100Gi"
          },
          "queue": {
              "cpu": 8,
              "max_delivery": 1,
              "min_replica": 1,
              "memory": 64000,
              "resource": "",
              "source": {
                  "max_payload_size_kb": 20480
              },
              "sink": {
                  "max_payload_size_kb": 20480
              }
          },
          "storage": [
              {
                  "oss": {
                      "path": "oss://examplebucket/",
                      "readOnly": false
                  },
                  "properties": {
                      "resource_type": "code"
                  },
                  "mount_path": "/photog_oss"
              }
          ],
          "containers": [
              {
                  "image": "registry.cn-beijing.aliyuncs.com/mybigpai/photog_pub:check.1.0.0.pub",
                  "script": "python app.py",
                  "port": 7860
              }
          ]
      }
  4. Click Deploy.

    The deployment is complete when the Service Status shows Running.

Training service

  1. Log on to the PAI console. Select a region on the top of the page. Then, select the desired workspace and click Elastic Algorithm Service (EAS).

  2. Click Deploy Service. In the Custom Model Deployment section, click Custom Deployment.

  3. On the Custom Deployment page, configure the following parameters.

    • In the Basic Information section, enter a name for the service. For example, photog_train_pmml.

    • In the Environment Information section, configure the following parameters:

      Parameter

      Description

      Deployment Method

      Select Image-based Deployment and select Asynchronous Queue.

      Image Configuration

      Select Image Address and enter the image address:

      • For China (Beijing), use: registry.cn-beijing.aliyuncs.com/mybigpai/photog_pub:train.1.0.0.pub.

      • For Asia Pacific SE 1 (Singapore), use: registry.ap-southeast-1.aliyuncs.com/mybigpai/photog_pub:train.1.0.0.pub.

      Mount storage

      Configure the storage mount. The following types are supported:

      • OSS

        • Uri: Select the path to your OSS bucket. Ensure that it is the same as the OSS path you selected for the verification service. For example, oss://examplebucket/.

        • Mount Path: Set this to /photog_oss.

      • NAS

        • Select File System: Select a NAS file system.

        • Mount Target: Select a NAS mount target.

        • File System Path: Specify the source path in the NAS file system to mount, such as /.

        • Mount Path: Set this to /photog_oss.

      Command

      Set this to python app.py.

      Port Number

      Set this to 7860.

    • In the Resource Information section, configure the following parameters:

      Parameter

      Description

      Resource Type

      Select Public Resources.

      Deployment

      For the resource specification, select a GPU instance type from the GU30 series. We recommend using ml.gu7i.c32m188.1-gu30.

      Configure a system disk

      Set the size to 120 GiB.

    • In the Asynchronous Queue section, configure the following parameters:

      Parameter

      Description

      Resource Type

      Select Public Resources.

      Deployment

      Configure the following parameters:

      • Minimum number of instances: 1

      • CPU: 8 cores

      • Memory: 64 GB

      Maximum Data for A Single Input Request

      Set this to 20480 KB to avoid exceeding the queue's per-request storage limit.

      Maximum Data for A Single Output

    • In the Network Information section, select the VPC, VSwitch, and security group that you created.

    • In the Service Configuration section, click Edit and add the following configuration. You can refer to the complete configuration example below.

      Field

      New parameters

      autoscaler

      (Optional) Configure horizontal auto scaling. For more information, see horizontal auto scaling.

      "behavior": {
        "scaleDown": {
          "stabilizationWindowSeconds": 60
        }
      },
      "max": 5,
      "min": 1,
      "strategies": {
                  "queue[backlog]": 1
      }

      metadata

      Add the following parameters:

      "rpc": {
                  "keepalive": 3600000,
                  "worker_threads": 1
              }
      • keepalive: The maximum processing time for a single request, in milliseconds. Set it to 3600000.

      • worker_threads: The number of threads in each EAS instance that process requests concurrently.

        The default value is 5, which means the first five tasks that enter the queue are assigned to the same instance. We recommend setting this parameter to 1 to ensure that requests are processed sequentially.

      queue

      Add the parameter "max_delivery": 1 to prevent failed requests from being redelivered.

      The following code provides a complete configuration example:

      {
          "autoscaler": {
              "behavior": {
                  "scaleDown": {
                      "stabilizationWindowSeconds": 60
                  }
              },
              "max": 5,
              "min": 1,
              "strategies": {
                  "queue[backlog]": 1
              }
          },
          "metadata": {
              "name": "photog_train_pmml",
              "instance": 1,
              "rpc": {
                  "keepalive": 3600000,
                  "worker_threads": 1
              },
              "type": "Async"
          },
          "cloud": {
              "computing": {
                  "instance_type": "ml.gu7i.c32m188.1-gu30",
                  "instances": null
              },
              "networking": {
                  "vswitch_id": "vsw-2ze4o9kww55051tf2****",
                  "security_group_id": "sg-2ze0kgiee55d0fn4****",
                  "vpc_id": "vpc-2ze5hl4ozjl4fo7q3****"
              }
          },
          "features": {
              "eas.aliyun.com/extra-ephemeral-storage": "120Gi"
          },
          "queue": {
              "cpu": 8,
              "max_delivery": 1,
              "min_replica": 1,
              "memory": 64000,
              "resource": "",
              "source": {
                  "max_payload_size_kb": 20480
              },
              "sink": {
                  "max_payload_size_kb": 20480
              }
          },
          "storage": [
              {
                  "oss": {
                      "path": "oss://examplebucket/",
                      "readOnly": false
                  },
                  "properties": {
                      "resource_type": "code"
                  },
                  "mount_path": "/photog_oss"
              }
          ],
          "containers": [
              {
                  "image": "registry.cn-beijing.aliyuncs.com/mybigpai/photog_pub:train.1.0.0.pub",
                  "script": "python app.py",
                  "port": 7860
              }
          ]
      }
  4. Click Deploy.

    The deployment is complete when the Service Status shows Running.

Deploy prediction service

  1. Log on to the PAI console. Select a region on the top of the page. Then, select the desired workspace and click Elastic Algorithm Service (EAS).

  2. Click Deploy Service. In the Custom Model Deployment section, click Custom Deployment.

  3. On the Custom Deployment page, configure the following parameters.

    • In the Basic Information section, specify a service name, for example, photog_pre_pmml.

    • In the Environment Information section, configure the following parameters:

      Parameter

      Description

      Deployment Method

      Select Image-based Deployment and select Asynchronous Queue.

      Image Configuration

      Select Image Address and enter the image URL. You must configure image URLs for both the AI Portrait Prediction service and the WebUI prediction service. In this section, configure the image URL for the AI Portrait Prediction service. The image URL for the WebUI prediction service is configured later in the service configuration section. The following are the supported image URLs. This solution uses the image URL for the China (Beijing) region.

      • China (Beijing) image URLs:

        • AI Portrait Prediction service: registry.cn-beijing.aliyuncs.com/mybigpai/photog_pub:infer.1.0.0.pub.

        • WebUI prediction service: eas-registry-vpc.cn-beijing.cr.aliyuncs.com/pai-eas/stable-diffusion-webui:3.2.

      • Asia Pacific SE 1 (Singapore) image URLs:

        • AI Portrait Prediction service: registry.ap-southeast-1.aliyuncs.com/mybigpai/photog_pub:infer.1.0.0.pub.

        • WebUI prediction service: eas-registry-vpc.ap-southeast-1.cr.aliyuncs.com/pai-eas/stable-diffusion-webui:3.2.

      Mount storage

      Configure a storage mount. The following mount methods are available. This solution uses OSS.

      • OSS

        • Uri: Select your OSS bucket path. This path must be the same as the path selected for the verification service. For example, oss://examplebucket/.

        • Mount Path: Set to /photog_oss.

      • NAS

        • Select File System: Select a NAS file system.

        • Mount Target: Select a NAS mount target.

        • File System Path: Specify the source path in NAS that you want to mount. For example, /.

        • Mount Path: Set to /photog_oss.

      Download and decompress the model files required for the WebUI, and store them in your OSS bucket at the path oss://examplebucket/photog_oss/webui or your NAS path /photog_oss/webui according to the following directory structure. For more information about how to upload files to an OSS bucket, see ossutil command-line tool 1.0. For more information about how to upload files to a NAS path, see Quick Start (Linux) and Use Workbench to manage files on ECS instances. The OSS bucket must contain the file directory structure for the AI model project, including directories such as embeddings, models, and train, and their related files.

      Environment Variable

      Click Add and configure the following two environment variables:

      • Variable Name: URL; Value: http://127.0.0.1:8000.

      • Variable Name: AUTHORIZATION; Value: =.

      Command

      Set to python app.py.

      Port Number

      Set to 7860.

    • In the Resource Information section, configure the following parameters:

      Parameter

      Description

      Resource Type

      Select Public Resources.

      Deployment

      For Resource Specification, select a GPU instance type from the GU30 series. We recommend using ml.gu7i.c32m188.1-gu30.

      Configure a system disk

      Set to 120 GiB.

    • In the Asynchronous Queue section, configure the following parameters:

      Parameter

      Description

      Resource Type

      Select Public Resources.

      Deployment

      Configure the following parameters:

      • Minimum instances: 1.

      • CPU: 8 cores.

      • Memory: 64 GB.

      Maximum Data for A Single Input Request

      Set this value to 20480 KB to prevent requests from failing due to insufficient queue storage.

      Maximum Data for A Single Output

    • In the Network Information section, select the VPC, vSwitch, and security group that you created.

    • In the Service Configuration section, add the following settings. Refer to the complete configuration example below.

      Field

      New parameters

      metadata

      Add the following parameters:

      "rpc": {
                  "keepalive": 3600000,
                  "worker_threads": 1
              }
      • keepalive: The maximum processing time for a single request, in milliseconds. Set this value to 3600000.

      • worker_threads: The number of threads in each EAS instance used for concurrent request processing.

        The default is 5. This means that the first five tasks that enter the queue are assigned to the same instance. We recommend setting this parameter to 1 to ensure that requests are processed sequentially.

      containers

      Add the following parameters:

      {
                  "image": "eas-registry-vpc.cn-beijing.cr.aliyuncs.com/pai-eas/stable-diffusion-webui:3.2",
                  "port": 8000,
                  "script": "./webui.sh --listen --port 8000 --skip-version-check --no-hashing --no-download-sd-model --skip-install --api --filebrowser --sd-dynamic-cache --data-dir /photog_oss/photog/webui/"
              }

      These settings specify the image, run command, and port number for the WebUI prediction service.

      queue

      Add the parameter "max_delivery": 1 to prevent multiple redeliveries after a failure.

      The following is a complete configuration example:

      {
          "metadata": {
              "name": "photog_pre_pmml",
              "instance": 1,
              "rpc": {
                  "keepalive": 3600000,
                  "worker_threads": 1
              },
              "type": "Async"
          },
          "cloud": {
              "computing": {
                  "instance_type": "ecs.gn6v-c8g1.2xlarge",
                  "instances": null
              },
              "networking": {
                  "vswitch_id": "vsw-2ze4o9kww55051tf2****",
                  "security_group_id": "sg-2ze0kgiee55d0fn4****",
                  "vpc_id": "vpc-2ze5hl4ozjl4fo7q3****"
              }
          },
          "features": {
              "eas.aliyun.com/extra-ephemeral-storage": "120Gi"
          },
          "queue": {
              "cpu": 8,
              "max_delivery": 1,
              "min_replica": 1,
              "memory": 64000,
              "resource": "",
              "source": {
                  "max_payload_size_kb": 20480
              },
              "sink": {
                  "max_payload_size_kb": 20480
              }
          },
          "storage": [
              {
                  "oss": {
                      "path": "oss://examplebucket/",
                      "readOnly": false
                  },
                  "properties": {
                      "resource_type": "code"
                  },
                  "mount_path": "/photog_oss"
              }
          ],
          "containers": [
              {
                  "image": "registry.cn-beijing.aliyuncs.com/mybigpai/photog_pub:infer.1.0.0.pub",
                  "env": [
                      {
                          "name": "URL",
                          "value": "http://127.0.0.1:8000"
                      },
                      {
                          "name": "AUTHORIZATION",
                          "value": "="
                      }
                  ],
                  "script": "python app.py",
                  "port": 7861
              },
              {
                  "image": "eas-registry-vpc.cn-beijing.cr.aliyuncs.com/pai-eas/stable-diffusion-webui:3.2",
                  "port": 8000,
                  "script": "./webui.sh --listen --port 8000 --skip-version-check --no-hashing --no-download-sd-model --skip-install --api --filebrowser --sd-dynamic-cache --data-dir /photog_oss/photog/webui/"
              }
          ]
      }
  4. Click Deploy.

    The deployment is complete when the Service Status shows Running.

Call the API

Step 1: Call image verification API

  1. Go to the Elastic Algorithm Service (EAS) page and click the name of your verification service to open the Overview page. In the Basic Information section, click View Endpoint Information. On the Asynchronous Invocation tab, find the service endpoint and token.

  2. Use the following code to create an input queue for image verification and retrieve its information.

    Python SDK

    import json
    from eas_prediction import QueueClient
    # Create an input queue object to write input data.
    input_queue = QueueClient('182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'photog_check')
    input_queue.set_token('<token>')
    input_queue.init()
    datas = json.dumps(
        {
           'request_id'    : 12345,
           'images'        : ["xx.jpg", "xx.jpg"], # urls, a list
           'configure'     : {
                'face_reconize' : True, # Judge whether all pictures are of a person
            }
        }
    )
    index, request_id = input_queue.put(f'{datas}')
    print(index, request_id)
    # View the details of the input queue.
    attrs = input_queue.attributes()
    print(attrs)

    The key configurations are described as follows:

    Parameter

    Description

    Default

    Required

    input_queue

    The service endpoint of the verification service. For configuration details, see the code sample. Type: STRING.

    None

    Yes

    <token>

    Replace this value with the token for the verification service. Type: STRING.

    None

    Yes

    request ID

    The request ID. Type: STRING.

    None

    Yes

    images

    The URLs of the images for verification. Type: LIST.

    None

    Yes

    configure

    face_reconize

    Determines whether faces in multiple images belong to the same person. Type: BOOL.

    False

    No

    Java SDK

    import com.aliyun.openservices.eas.predict.http.HttpConfig;
    import com.aliyun.openservices.eas.predict.http.QueueClient;
    import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
    import org.apache.commons.lang3.tuple.Pair;
    public class AsyncTest {
        public static void main(String[] args) throws Exception {
            /** Create a queue service client. */
            String queueEndpoint = "182848887922****.cn-shanghai.pai-eas.aliyuncs.com";
            String inputQueueName = "photog_check";
            String queueToken = "YmE3NDkyMzdiMzNmMGM3ZmE4ZmNjZDk0M2NiMDA3OTZmNzc1MT****==";
            QueueClient inputQueue =
                new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
            /** Request data. */
            String data = "{\n" +
                "    'request_id': 12345,\n" +
                "    'images'    : [\"xx.jpg\", \"xx.jpg\"],\n" +
                "    'configure' : {\n" +
                "        'face_reconize' : True,\n" +
                "    }\n" +
                "}";
            Pair<Long, String> entry = inputQueue.put(data.getBytes(), null);
            System.out.println(String.format("index = %s, request id = %s", entry.getKey(), entry.getValue()));
            // View the details of the input queue.
            System.out.println(inputQueue.attributes());
            /** Close the client. */
            inputQueue.shutdown();
        }
    }

    The key configurations are described as follows:

    Parameter

    Description

    Default

    Required

    queueEndpoint

    The service endpoint of the verification service. Type: STRING.

    None

    Yes

    inputQueueName

    The name of the verification service. Type: STRING.

    None

    Yes

    queueToken

    Replace this value with the token for the verification service. Type: STRING.

    None

    Yes

    request ID

    The request ID. Type: STRING.

    None

    Yes

    images

    The URLs of the images for verification. Type: LIST.

    None

    Yes

    configure

    face_reconize

    Specifies whether to determine if the faces in multiple images belong to the same person. Type: BOOL.

    False

    No

    Python SDK

    1 6bdea119-01f3-4728-b3d3-b0af366ad3eb
    {'consumers.list.[0]': 'Id: photog_check.photog-check-738569a9-798897bdf5-76****, Index: 0, Pending: 0, Status: Running, Idle: 1h10m4.997s, Window: 1, Slots: 1, AutoCommit: false', 'consumers.stats.total': '1', 'consumers.status.total': '1', 'groups.list.[0]': 'Id: photog_check, Index: 1, Pending: 1, Delivered: 2, Consumers: 1', 'meta.header.group': 'X-EAS-QueueService-Gid', 'meta.header.priority': 'X-EAS-QueueService-Priority', 'meta.header.user': 'X-EAS-QueueService-Uid', 'meta.name': 'photog-check-queue-95e006df', 'meta.state': 'Normal', 'stream.approxMaxLength': '1439', 'stream.firstEntry': '1', 'stream.lastEntry': '1', 'stream.length': '1', 'stream.maxPayloadBytes': '20971520'}

    Java SDK

    index = 2, request id = 61132b43-a527-40dc-89bb-a9a48316ddea
    {"meta.header.priority":"X-EAS-QueueService-Priority","consumers.status.total":"1","stream.firstEntry":"2","stream.maxPayloadBytes":"20971520","consumers.stats.total":"1","stream.approxMaxLength":"1439","stream.length":"1","groups.list.[0]":"Id: photog_check, Index: 2, Pending: 1, Delivered: 3, Consumers: 1","meta.header.group":"X-EAS-QueueService-Gid","stream.lastEntry":"2","consumers.list.[0]":"Id: photog_check.photog-check-738569a9-798897bdf5-76j48, Index: 2, Pending: 0, Status: Running, Idle: 19m11.174s, Window: 1, Slots: 1, AutoCommit: false","meta.name":"photog-check-queue-95e006df","meta.state":"Normal","meta.header.user":"X-EAS-QueueService-Uid"}
    Process finished with exit code 0

    In the output:

    • index: The sequence number of the request in PAI-EAS.

    • request ID: The request ID. Use this ID to retrieve the output result.

    • The rest of the output shows details of the input queue.

  3. Use the following code to create an output queue and retrieve the result. Check the result to confirm whether the images meet the requirements.

    Python SDK

    # Create an output queue object to subscribe to and read the output data.
    sink_queue = QueueClient('182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'photog_check/sink')
    sink_queue.set_token('<token>')
    sink_queue.init()
    sink_queue.get(request_id, auto_delete=True)[0].data.decode('utf-8')

    Parameter description:

    • sink_queue: The service endpoint of the verification service.

    • <token>: Replace this value with the token for the verification service.

    • auto_delete: Defaults to True. If you query a queue by using request_id but do not set the auto_delete parameter, the result in the queue will be deleted. Because you usually need to delete the content of an output queue, we recommend that you set the auto_delete parameter to True.

    Java SDK

    import com.aliyun.openservices.eas.predict.http.HttpConfig;
    import com.aliyun.openservices.eas.predict.http.QueueClient;
    import com.aliyun.openservices.eas.predict.queue_client.DataFrame;
    import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
    import org.apache.commons.lang3.tuple.Pair;
    import java.util.HashMap;
    import java.util.Map;
    public class AsyncPhotoTest {
        public static void main(String[] args) throws Exception {
            /** Create a queue service client. */
            String queueEndpoint = "182848887922****.cn-shanghai.pai-eas.aliyuncs.com";
            String inputQueueName = "photog_check";
            String sinkQueueName = String.format("%s/sink", inputQueueName);
            String queueToken = "YjczMzFlYmRkMDU4YmZmMGQ4NTEwODA4NDk3NmFhODE5N2ExMzEy****";
            QueueClient inputQueue =
                new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
            QueueClient sinkQueue =
                new QueueClient(queueEndpoint, sinkQueueName, queueToken, new HttpConfig(), new QueueUser());
            /** Request data. */
            String data = "{\n" +
                "  \"request_id\": 12345,\n" +
                "  \"images\": [\"xx.jpg\", \"xx.jpg\"],\n" +
                "  \"configure\": {\n" +
                "    \"face_reconize\": true\n" +
                "  }\n" +
                "}";
            Pair<Long, String> entry = inputQueue.put(data.getBytes(), null);
            Long index = entry.getKey();
            final String requestId = entry.getValue();
            System.out.println(String.format("index = %d, request id = %s", index, requestId));
            // View the details of the input queue.
            System.out.println(inputQueue.attributes());
            // View the input data.
            Map<String, String> tags =
                new HashMap<String, String>() {
                    {
                        put("requestId", requestId);
                    }
                };
            DataFrame[] dfs = inputQueue.get(0, 1L, 0, false, tags);
            if (dfs.length > 0) {
                System.out.println(String.format("Successfully get input data = %s, index = %d, tags = %s", new String(dfs[0].getData()), dfs[0].getIndex(), dfs[0].getTags()));
            } else {
                System.out.println("no data");
            }
            // View the output data.
            while (true) {
                dfs = sinkQueue.get(0, 1L, 0, true, tags);
                if (dfs.length > 0) {
                    System.out.println(String.format("Successfully get sink data = %s, tags = %s", new String(dfs[0].getData()), dfs[0].getTags()));
                    break;
                } else {
                    System.out.println("no data");
                    Thread.sleep(5000);
                }
            }
            /** Close the clients. */
            inputQueue.shutdown();
            sinkQueue.shutdown();
        }
    }

    Parameter description:

    • queueEndpoint: The service endpoint of the verification service.

    • inputQueueName: The name of the verification service.

    • queueToken: Replace this value with the token for the verification service.

    The system returns the following result:

    Python SDK

    '{"request_id": "12345", "code": "OK", "message": "success", "data": {"request_id": 12345, "images": ["xx.jpg", "https://xxx.oss-cn-shanghai.aliyuncs.com/photog/user_images/foto/train/0.jpg"], "configure": {"face_reconize": true}, "cost_time": 9.820043325424194, "check_results": [{"url": "https://xx-cn-shanghai.aliyuncs.com/photog/user_images/foto/train/1.jpg", "message": "success", "code": 1, "frontal": true}, {"url": "https://xx-cn-shanghai.aliyuncs.com/photog/user_images/foto/train/0.jpg", "message": "success", "code": 1, "frontal": false}]}}'

    Java SDK

    Successfully get sink data = {"request_id": "12345", "code": "OK", "message": "success", "data": {"request_id": "12345", "images": ["xx.jpg", "xx.jpg"], "configure": {"face_reconize": true}, "cost_time": 0.2047882080078125, "check_results": [{"url": "https://xx-cn-shanghai.aliyuncs.com/photog/user_images/foto/train/1.jpg", "message": "success", "code": 1, "frontal": true}, {"url": "https://xx-cn-shanghai.aliyuncs.com/photog/user_images/foto/train/0.jpg", "message": "success", "code": 1, "frontal": false}]}}

    The parameters are described below:

    Parameter

    Description

    request ID

    The request ID. Type: STRING.

    code

    The status code of the request. Type: STRING.

    • OK: The verification is complete.

    • error: The verification is not complete.

    message

    Details about the request status. A value of success indicates that the request was successful. For other values, refer to the returned content to determine the status.

    data

    The response payload. The fields are described below:

    • check_results: The detection result for each input image.

      • url: The URL of the image.

      • message: Details about the image detection. A value of success indicates that the verification was successful. For more information about the possible values of the message and their corresponding codes, see Message details.

      • frontal: Indicates whether the face in the image is frontal.

    • cost_time: The server-side computation time for this API call.

    • images: A list of URLs for the verified images. Type: List.

    • request ID: The request ID. Type: STRING.

    Message details

    Message

    code

    Description

    success

    1

    The image meets the requirements.

    Image decode error

    2

    Failed to download or decode the image.

    Number of face is not 1

    3

    The number of faces in the image is not 1.

    Image detect error

    4

    An exception occurred during face detection.

    Image encoding error

    5

    An error occurred while encoding the face into a feature vector. This indicates that no face was detected.

    This photo is not the same person in photos

    6

    When this is the only error returned, it means the faces in the submitted images do not belong to the same person.

Step 2: Call the LoRA training API

  1. First, on the Elastic Algorithm Service (EAS) page, click the name of the training service to go to the Overview page. In the Basic Information section, click View Endpoint Information. In the Call Information dialog box, select the Shared Gateway > Asynchronous Invocation tab. Obtain the public input invocation URL to use as the service endpoint and copy the Token value.

  2. Use the following code to create an input queue for LoRA training and get queue information.

    Python SDK

    photog_train_pmmln import json
    from eas_prediction import QueueClient
    # Create an input queue object to write input data.
    input_queue = QueueClient('182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'photog_train_pmml')
    input_queue.set_token('<token>')
    input_queue.init()
    datas = json.dumps(
        {
            'request_id'    : 12345,
            'images'        : ["xx.jpg", "xx.jpg"], # urls
            'configure'     : {
                'user_id'   : "zhoumo", # user id
            }
        }
    )
    index, request_id = input_queue.put(f'{datas}')
    print(index, request_id)
    # View the details of the input queue.
    attrs = input_queue.attributes()
    print(attrs)

    The key parameters are described as follows:

    Parameter

    Description

    Default

    Required

    input_queue

    The service access address for the training service, passed as the first argument to the QueueClient constructor. Type: String.

    None

    Yes

    <token>

    The token that you obtained for the training service. Type: STRING.

    None

    Yes

    request_id

    The request ID. Type: STRING.

    None

    Yes

    images

    The URLs of the training images. Type: LIST.

    None

    Yes

    configure

    user_id

    The user ID. Type: STRING.

    None

    Yes

    sex

    The gender of the person in the training images.

    secret

    No

    max_train_steps

    The total number of training steps.

    400

    No

    val_save_checkpointing_steps

    The number of validation steps during training.

    50

    No

    Java SDK

    import com.aliyun.openservices.eas.predict.http.HttpConfig;
    import com.aliyun.openservices.eas.predict.http.QueueClient;
    import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
    import org.apache.commons.lang3.tuple.Pair;
    public class AsyncTest {
        public static void main(String[] args) throws Exception {
            /** Create a client for the queue service. */
            String queueEndpoint = "182848887922****.cn-shanghai.pai-eas.aliyuncs.com";
            String inputQueueName = "photog_train_pmml";
            String queueToken = "YmE3NDkyMzdiMzNmMGM3ZmE4ZmNjZDk0M2NiMDA3OTZmNzc1MT****==";
            QueueClient inputQueue =
                new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
            /** Request data. */
            String data = "{\n" +
                "        'request_id'    : 12345,\n" +
                "        'images'        : [\"xx.jpg\", \"xx.jpg\"],\n" +
                "        'configure'     : {\n" +
                "            'user_id'   : \"zhoumo\",\n" +
                "        }\n" +
                "    }";
            Pair<Long, String> entry = inputQueue.put(data.getBytes(), null);
            System.out.println(String.format("index = %s, request id = %s", entry.getKey(), entry.getValue()));
            // View the details of the input queue.
            System.out.println(inputQueue.attributes());
            /** Shut down the client. */
            inputQueue.shutdown();
        }
    }

    The key parameters are described as follows:

    Parameter

    Description

    Default

    Required

    queueEndpoint

    The service access address for the training service. Type: STRING.

    None

    Yes

    inputQueueName

    The name of the training service. Type: STRING.

    None

    Yes

    queueToken

    The token for the training service. Type: STRING.

    None

    Yes

    request_id

    The request ID. Type: STRING.

    None

    Yes

    images

    The URLs of the training images. Type: LIST.

    None

    Yes

    configure

    user_id

    The user ID. Type: STRING.

    None

    Yes

    sex

    The gender of the person in the training images.

    secret

    No

    max_train_steps

    The total number of training steps.

    400

    No

    val_save_checkpointing_steps

    The number of validation steps during training.

    50

    No

    The system returns a result similar to the following:

    Python SDK

    2 bb4ce34d-47e4-425d-bee7-b806e29c6d78
    {'consumers.list.[0]': 'Id: photog_train_pmml.photog-train-pmml-78550f91-7545766654-jpdtp, Index: 2, Pending: 0, Status: Running, Idle: 18h46m24.039s, Window: 1, Slots: 1, AutoCommit: false', 'consumers.stats.total': '1', 'consumers.status.total': '1', 'groups.list.[0]': 'Id: photog_train_pmmln, Index: 2, Pending: 1, Delivered: 3, Consumers: 1', 'meta.header.group': 'X-EAS-QueueService-Gid', 'meta.header.priority': 'X-EAS-QueueService-Priority', 'meta.header.user': 'X-EAS-QueueService-Uid', 'meta.name': 'photog-train-pmmln-queue-7a5e7cc6', 'meta.state': 'Normal', 'stream.approxMaxLength': '1438', 'stream.firstEntry': '2', 'stream.lastEntry': '2', 'stream.length': '1', 'stream.maxPayloadBytes': '20971520'}

    Java SDK

    index = 3, request id = ec3b7c21-c395-4490-ae42-8f66d06e9d4d
    {"meta.header.priority":"X-EAS-QueueService-Priority","consumers.status.total":"1","stream.firstEntry":"3","stream.maxPayloadBytes":"20971520","consumers.stats.total":"1","stream.approxMaxLength":"1438","stream.length":"1","groups.list.[0]":"Id: photog_train_pmml, Index: 3, Pending: 1, Delivered: 4, Consumers: 1","meta.header.group":"X-EAS-QueueService-Gid","stream.lastEntry":"3","consumers.list.[0]":"Id: photog_train_pmmln.photog-train-pmmln-78550f91-7545766654-jpdtp, Index: 3, Pending: 0, Status: Running, Idle: 2h30m57.08s, Window: 1, Slots: 1, AutoCommit: false","meta.name":"photog-train-pmmln-queue-7a5e7cc6","meta.state":"Normal","meta.header.user":"X-EAS-QueueService-Uid"}
    Process finished with exit code 0

    In this output:

    • index: Indicates the sequence number of the request in EAS.

    • request_id: A unique identifier for the request, used to retrieve results.

    • The rest of the output shows queue details.

  3. Use the following code to create an output queue, subscribe to it, and read the results to check if the model training was successful.

    Python SDK

    # Create an output queue object to subscribe to and read the output data.
    sink_queue = QueueClient('182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'photog_train_pmml/sink')
    sink_queue.set_token('<token>')
    sink_queue.init()
    sink_queue.get(request_id, auto_delete=True)[0].data.decode('utf-8')

    Parameter descriptions:

    • sink_queue: The service access address of the training service.

    • <token>: The token for the training service.

    Java SDK

    import com.aliyun.openservices.eas.predict.http.HttpConfig;
    import com.aliyun.openservices.eas.predict.http.QueueClient;
    import com.aliyun.openservices.eas.predict.queue_client.DataFrame;
    import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
    import org.apache.commons.lang3.tuple.Pair;
    import java.util.HashMap;
    import java.util.Map;
    public class AsyncPhotoTest {
        public static void main(String[] args) throws Exception {
            /** Create clients for the queue service. */
            String queueEndpoint = "166233998075****.cn-beijing.pai-eas.aliyuncs.com";
            String inputQueueName = "photog_train_pmml";
            String sinkQueueName = String.format("%s/sink", inputQueueName);
            String queueToken = "N2E2YWI0Y2MyNjZmNjdlMWFmZjNhOTM5M2E5ZGNlMGY1NDQwZGYw****";
            QueueClient inputQueue =
                    new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
            QueueClient sinkQueue =
                    new QueueClient(queueEndpoint, sinkQueueName, queueToken, new HttpConfig(), new QueueUser());
            /** Request data. */
            String data = "{\n" +
                    "  \"request_id\": 12345,\n" +
                    "  \"images\": [\"xx.jpg\", \"xx.jpg\"],\n" +
                    "  \"configure\": {\n" +
                    "    \"user_id\": \"zhoumo\"\n" +
                    "  }\n" +
                    "}";
            Pair<Long, String> entry = inputQueue.put(data.getBytes(), null);
            Long index = entry.getKey();
            final String requestId = entry.getValue();
            System.out.println(String.format("index = %d, request id = %s", index, requestId));
            // View the details of the input queue.
            System.out.println(inputQueue.attributes());
            // View the input data.
            Map<String, String> tags =
                    new HashMap<String, String>() {
                        {
                            put("requestId", requestId);
                        }
                    };
            DataFrame[] dfs = inputQueue.get(0, 1L, 0, false, tags);
            if (dfs.length > 0) {
                System.out.println(String.format("Successfully get data = %s, index = %d, tags = %s", new String(dfs[0].getData()), dfs[0].getIndex(), dfs[0].getTags()));
            } else {
                System.out.println("no data");
            }
            // View the output data.
            while (true) {
                dfs = sinkQueue.get(0, 1L, 0, true, tags);
                if (dfs.length > 0) {
                    System.out.println(String.format("Successfully get data = %s, tags = %s", new String(dfs[0].getData()), dfs[0].getTags()));
                    break;
                } else {
                    System.out.println("no data");
                }
            }
            /** Shut down the clients. */
            inputQueue.shutdown();
            sinkQueue.shutdown();
        }
    }

    Parameter descriptions:

    • queueEndpoint: The service access address for the training service.

    • inputQueueName: The name of the training service.

    • queueToken: The token for the training service.

    • images: The URLs of the images for model training.

    Python SDK

    '{"request_id": "12345", "code": "OK", "message": "success", "data": {"user_id": "zhoumo", "cost_time": 272.7406361103058}}'
    Note

    If the returned code is 502, it means the training is still in progress.

    Java SDK

    ...
    no data
    no data
    Successfully get data = {"request_id": "12345", "code": "OK", "message": "success", "data": {"user_id": "zhoumo", "cost_time": 260.7540729045868}}
    Note

    If the result is no data, it means the training is still in progress.

    The following parameters are returned in the response:

    Parameter

    Description

    request_id

    The request ID. Type: STRING.

    code

    Indicates whether the training is complete:

    • OK: The training is complete.

    • error: An error occurred during training.

    message

    Details about the execution status. For example, success indicates that the model training was successful.

    data

    The details of the response. This parameter contains the following fields:

    • user_id: The user ID.

    • cost_time: The server-side computation time for the training task.

Step 3: Call the image generation API

  1. Go to the Elastic Algorithm Service (EAS) page. Click the name of your prediction service to go to the Overview page. In the Basic Information section, click View Endpoint Information. On the Asynchronous Invocation tab, get the service endpoint and token.

  2. Use the following code to create an input queue for image prediction and retrieve its information.

    Python SDK

    import json
    from eas_prediction import QueueClient
    # Create an input queue object for writing input data.
    input_queue = QueueClient('182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'photog_pre_pmml')
    input_queue.set_token('<token>')
    input_queue.init()
    datas = json.dumps({
        'request_id'    : 12345, 
        'template_image': "xx.jpg", 
        'configure'     : { 
            'user_id'   : "zhoumo", # The user ID.
        } 
    })
    index, request_id = input_queue.put(f'{datas}')
    print(index, request_id)
    # View input queue details.
    attrs = input_queue.attributes()
    print(attrs)
    # Query a request by its ID.
    print(input_queue.get(request_id, auto_delete=False)[0].data.decode('utf-8'))

    The following table describes the key configuration parameters.

    Parameter

    Description

    Default

    Required

    input_queue

    The prediction service endpoint. See the code sample for the required value. Type: String.

    None

    Yes

    <token>

    The token for your prediction service. Type: String.

    None

    Yes

    request_id

    The request ID. Type: String.

    None

    Yes

    template_image

    The URL of the input template image. Type: String.

    None

    Yes

    configure

    user_id

    The user ID. Type: String.

    None

    Yes

    sex

    The gender of the person in the template image. Type: String.

    secret

    No

    first_diffusion_steps

    The number of diffusion steps in the first pass. Type: Int.

    50

    No

    first_denoising_strength

    The denoising strength for the first pass. Type: Float.

    0.45

    No

    second_diffusion_steps

    The number of diffusion steps in the second pass. Type: Int.

    20

    No

    second_denoising_strength

    The denoising strength for the second pass. Type: Float.

    0.30

    No

    more_like_me_before

    The face fusion ratio for the first pass. A higher value makes the result more similar to the person in the template image. Type: Float.

    0.50

    No

    more_like_me

    The face fusion ratio for the second pass. A higher value makes the result more similar to the person in the template image. Type: Float.

    0.50

    No

    mask_region

    The region to reconstruct during the second diffusion pass. Type: String. Valid values:

    • edge: Reconstructs the edges.

    • face: Reconstructs the entire face.

    edge

    No

    crop_face_preprocess

    Crops the portrait area before reconstruction. Type: Bool.

    True

    No

    apply_face_fusion_before

    Applies face fusion during the first pass. Type: Bool.

    True

    No

    apply_face_fusion_after

    Applies face fusion during the second pass. Type: Bool.

    True

    No

    color_shift_middle

    Applies color balance to the face during the first pass. Type: Bool.

    True

    No

    color_shift_last

    Applies color balance to the face during the second pass. Type: Bool.

    True

    No

    background_restore

    Restores the background. Type: Bool.

    False

    No

    skin_retouching_bool

    Applies skin smoothing. Type: Bool.

    True

    No

    photo_enhancement_bool

    Applies portrait enhancement. Type: Bool.

    True

    No

    photo_enhancement_method

    The portrait enhancement method. Valid values:

    • photo_fix

    • super_resolution

    photo_fix

    No

    makeup_transfer

    Applies makeup transfer. Type: Bool.

    False

    No

    makeup_transfer_ratio

    The makeup transfer ratio. Type: Float.

    0.50

    No

    Java SDK

    import com.aliyun.openservices.eas.predict.http.HttpConfig;
    import com.aliyun.openservices.eas.predict.http.QueueClient;
    import com.aliyun.openservices.eas.predict.queue_client.DataFrame;
    import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
    import org.apache.commons.lang3.tuple.Pair;
    import java.util.HashMap;
    import java.util.Map;
    public class AsyncTest {
        public static void main(String[] args) throws Exception {
            /** Creates a client for the queue service. */
            String queueEndpoint = "166233998075****.cn-beijing.pai-eas.aliyuncs.com";
            String inputQueueName = "photog_pre_pmml";
            String queueToken = "NjViMTI2NGQxZWQxYTI1NGE5MGQ1YTQ5Y2Y2MGZjY2VlZTVmNWE1****";
            QueueClient inputQueue =
                    new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
            /** Request data */
            String data = "{\n" +
                    "    'request_id'    : 12345, \n" +
                    "    'template_image': \"xx.jpg\", \n" +
                    "    'configure'     : { \n" +
                    "        'user_id'   : \"zhoumo\",\n" +
                    "    } \n" +
                    "}";
            Pair<Long, String> entry = inputQueue.put(data.getBytes(), null);
            System.out.println(String.format("index = %s, request id = %s", entry.getKey(), entry.getValue()));
            // View the details of the input queue.
            System.out.println(inputQueue.attributes());
            // Gets a specific request by its request id.
            final String requestId = entry.getValue();
            Map<String, String> tags =
                    new HashMap<String, String>() {
                        {
                            put("requestId", requestId);
                        }
                    };
            DataFrame df = inputQueue.get(0, 1L, 0, false, tags)[0];
            System.out.println(String.format("Successfully get data = %s, tags = %s", new String(df.getData()), df.getTags()));
            /** Shuts down the client. */
            inputQueue.shutdown();
        }
    }

    The following table describes the key parameters.

    Parameter

    Description

    Default

    Required

    queueEndpoint

    The endpoint of the queue service. Type: STRING.

    None

    Yes

    inputQueueName

    The name of the input queue.

    None

    Yes

    queueToken

    The access token for the queue service. Type: STRING.

    None

    Yes

    request_id

    The request id. Type: STRING.

    None

    Yes

    template_image

    The URL of the template image used for generation.

    None

    Yes

    configure

    user_id

    The user id. Type: STRING.

    None

    Yes

    sex

    The gender of the person in the template image. Type: STRING.

    secret

    No

    first_diffusion_steps

    The number of diffusion steps in the first pass. Type: INT.

    50

    No

    first_denoising_strength

    The denoising strength in the first diffusion pass. Type: FLOAT.

    0.45

    No

    second_diffusion_steps

    The number of diffusion steps in the second pass. Type: INT.

    20

    No

    second_denoising_strength

    The denoising strength in the second diffusion pass. Type: FLOAT.

    0.30

    No

    more_like_me_before

    The face fusion ratio for the first pass. A higher value increases similarity to the original person. Type: FLOAT.

    0.50

    No

    more_like_me

    The face fusion ratio for the second pass. A higher value increases similarity to the original person. Type: FLOAT.

    0.50

    No

    mask_region

    The region for the second diffusion pass. Type: STRING. Valid values:

    • edge: Reconstructs edges.

    • face: Reconstructs the face.

    edge

    No

    crop_face_preprocess

    If True, crops the portrait area before reconstruction. This also enables the large image feature. Type: BOOL.

    True

    No

    apply_face_fusion_before

    If True, applies face fusion in the first pass. Type: BOOL.

    True

    No

    apply_face_fusion_after

    If True, applies face fusion in the second pass. Type: BOOL.

    True

    No

    color_shift_middle

    If True, performs color balance on the face in the first pass. Type: BOOL.

    True

    No

    color_shift_last

    If True, performs color balance on the face in the second pass. Type: BOOL.

    True

    No

    background_restore

    If True, performs background restoration. Type: BOOL.

    False

    No

    skin_retouching_bool

    If True, applies skin retouching. Type: BOOL.

    True

    No

    photo_enhancement_bool

    If True, applies photo enhancement. Type: BOOL.

    True

    No

    photo_enhancement_method

    The photo enhancement method. Valid values:

    • photo_fix

    • super_resolution

    photo_fix

    No

    makeup_transfer

    If True, applies makeup transfer. Type: BOOL.

    False

    No

    makeup_transfer_ratio

    The makeup transfer ratio. Type: FLOAT.

    0.50

    No

    The system returns the following result:

    Python SDK

    1 069173d0-dce9-4ed6-913e-cc5fdda38764
    {'consumers.list.[0]': 'Id: photog_pre_pmml.photog-pre-pmml-835253f3-686f87d4f-d****, Index: 0, Pending: 0, Status: Running, Idle: 21h41m4.995s, Window: 1, Slots: 1, AutoCommit: false', 'consumers.stats.total': '1', 'consumers.status.total': '1', 'groups.list.[0]': 'Id: photog_pre_pmml, Index: 1, Pending: 1, Delivered: 2, Consumers: 1', 'meta.header.group': 'X-EAS-QueueService-Gid', 'meta.header.priority': 'X-EAS-QueueService-Priority', 'meta.header.user': 'X-EAS-QueueService-Uid', 'meta.name': 'photog-pre-pmml-queue-912f2cdb', 'meta.state': 'Normal', 'stream.approxMaxLength': '1439', 'stream.firstEntry': '1', 'stream.lastEntry': '1', 'stream.length': '1', 'stream.maxPayloadBytes': '20971520'}
    {"request_id": 12345, "template_image": "https://xx.oss-cn-beijing.aliyuncs.com/photog/user_images/foto/train/1.jpg", "configure": {"user_id": "zhoumo"}}

    Java SDK

    index = 4, request id = 996cb029-133e-4f18-bb03-e696fc6ae4a1
    {"meta.header.priority":"X-EAS-QueueService-Priority","consumers.status.total":"1","stream.firstEntry":"4","stream.maxPayloadBytes":"20971520","consumers.stats.total":"1","stream.approxMaxLength":"1436","stream.length":"1","groups.list.[0]":"Id: photog_pre_pmml, Index: 4, Pending: 1, Delivered: 5, Consumers: 1","meta.header.group":"X-EAS-QueueService-Gid","stream.lastEntry":"4","consumers.list.[0]":"Id: photog_pre_pmml.photog-pre-pmml-835253f3-686f87d4f-d****, Index: 4, Pending: 0, Status: Running, Idle: 2m12.017s, Window: 1, Slots: 1, AutoCommit: false","meta.name":"photog-pre-pmml-queue-912f2cdb","meta.state":"Normal","meta.header.user":"X-EAS-QueueService-Uid"}
    Successfully get data = {
        'request_id'    : 12345, 
        'template_image': "https://xx.oss-cn-beijing.aliyuncs.com/photog/user_images/foto/train/1.jpg", 
        'configure'     : { 
            'user_id'   : "zhoumo",
        } 
    }, tags = {requestId=996cb029-133e-4f18-bb03-e696fc6ae4a1, ts@source=169778191****}
    Process finished with exit code 0

    Where:

    • index: The sequence number of the request within Elastic Algorithm Service (EAS).

    • request_id: The unique ID of the request. You can use this ID to retrieve the output.

    • Other fields contain information about the queue.

  3. Use the following code to create a client for the output queue and retrieve the result. The response contains the image in Base64 encoding.

    Python SDK

    # Create an output queue object to subscribe to and read the output data.
    sink_queue = QueueClient('182848887922****.cn-shanghai.pai-eas.aliyuncs.com', 'photog_pre_pmml/sink')
    sink_queue.set_token('<token>')
    sink_queue.init()
    sink_queue.get(request_id, auto_delete=True)[0].data.decode('utf-8')

    Where:

    • sink_queue: When initializing QueueClient, use the endpoint of your prediction service.

    • <token>: Replace with the token for your prediction service.

    Java SDK

    import com.aliyun.openservices.eas.predict.http.HttpConfig;
    import com.aliyun.openservices.eas.predict.http.QueueClient;
    import com.aliyun.openservices.eas.predict.queue_client.DataFrame;
    import com.aliyun.openservices.eas.predict.queue_client.QueueUser;
    import org.apache.commons.lang3.tuple.Pair;
    import java.util.HashMap;
    import java.util.Map;
    public class AsyncPhotoTest {
        public static void main(String[] args) throws Exception {
            /** Create the queue service client */
            String queueEndpoint = "166233998075****.cn-beijing.pai-eas.aliyuncs.com";
            String inputQueueName = "photog_pre_pmml";
            String sinkQueueName = String.format("%s/sink", inputQueueName);
            String queueToken = "NjViMTI2NGQxZWQxYTI1NGE5MGQ1YTQ5Y2Y2MGZjY2VlZTVmNWE1****";
            QueueClient inputQueue =
                    new QueueClient(queueEndpoint, inputQueueName, queueToken, new HttpConfig(), new QueueUser());
            QueueClient sinkQueue =
                    new QueueClient(queueEndpoint, sinkQueueName, queueToken, new HttpConfig(), new QueueUser());
            /** Send the request data */
            String data = "{\n" +
                    "  \"request_id\": 12345,\n" +
                    "  \"template_image\": \"xx.jpg\",\n" +
                    "  \"configure\": {\n" +
                    "    \"user_id\": \"zhoumo\"\n" +
                    "  }\n" +
                    "}";
            Pair<Long, String> entry = inputQueue.put(data.getBytes(), null);
            Long index = entry.getKey();
            final String requestId = entry.getValue();
            System.out.println(String.format("index = %d, request id = %s", index, requestId));
            // View the details of the input queue
            System.out.println(inputQueue.attributes());
            // View the input data
            Map<String, String> tags =
                    new HashMap<String, String>() {
                        {
                            put("requestId", requestId);
                        }
                    };
            DataFrame[] dfs = inputQueue.get(0, 1L, 0, false, tags);
            if (dfs.length > 0) {
                System.out.println(String.format("Successfully get data = %s, index = %d, tags = %s", new String(dfs[0].getData()), dfs[0].getIndex(), dfs[0].getTags()));
            } else {
                System.out.println("no data");
            }
            // View the output data
            while (true) {
                dfs = sinkQueue.get(0, 1L, 0, true, tags);
                if (dfs.length > 0) {
                    System.out.println(String.format("Successfully get data = %s, tags = %s", new String(dfs[0].getData()), dfs[0].getTags()));
                    break;
                } else {
                    System.out.println("no data");
                }
            }
            /** Close the clients */
            inputQueue.shutdown();
            sinkQueue.shutdown();
        }
    }

    Where:

    • queueEndpoint: Set to the endpoint of your prediction service.

    • inputQueueName: Set to the name of your input queue.

    • queueToken: Replace with the token for your prediction service.

    • template_image: Set to the URL of your image.

    A successful request returns the following result:

    Python SDK

    '{"request_id": "12345", "code": "OK", "message": "success", "data": {"user_id": "zhoumo", "image": "iVBORw*****CYII=", "cost_time": 329.69798278808594}}'
    Note

    A code of 502 indicates that the image is still being generated.

    Java SDK

    ...
    no data
    no data
    Successfully get data = {"request_id": "12345", "code": "OK", "message": "success", "data": {"user_id": "zhoumo", "image": "iVBORw0KGgoAAA****ABJRU5ErkJggg==", "cost_time": 21.584840059280396}}
    Note

    If the response shows no data, the image is still being generated.

    The response parameters are described below:

    Parameter

    Description

    request_id

    The request ID (string).

    code

    The request status code:

    • OK: The request was successful.

    • error: The request failed.

    message

    Information about the request status. A value of success indicates the request was successful. Any other value describes an error.

    data

    The response content. The nested fields are described below:

    • user_id: The user ID.

    • image: The generated image, in Base64 encoding.

    • cost_time: The time taken (float).