Custom face retrieval

更新时间:
复制 MD 格式

Use the Content Moderation Python SDK to search a face image against a custom face group. The SDK submits a synchronous scan request and returns matched faces with a scene and suggestion for each result.

Prerequisites

Before you begin, ensure that you have:

  • Python dependencies installed. For installation instructions, see Installation

    Use the Python version specified in the Installation topic. Using a different version causes operation calls to fail.
  • The Extension.Uploader utility class downloaded and imported into your project. This is required for local file submissions.

How it works

  1. Create an AcsClient pointed at the cn-shanghai region and override the endpoint with region_provider.modify_point.

  2. Build a task object with a unique dataId, the image source (url), and a groupId that identifies which face group to search.

  3. Submit an ImageSyncScanRequest with the sface-n scene. The SDK returns results synchronously.

  4. Iterate the response to read the scene and suggestion for each matched face.

Submit an image URL for face retrieval

Replace the following values before running the code:

PlaceholderDescriptionExample
<your-access-key-id>AccessKey ID of your RAM userLTAI5tXxx
<your-access-key-secret>AccessKey secret of your RAM userxXxXxXx
<image-url>Publicly accessible URL of the face imagehttps://example.com/face.jpg
<group-id>ID of the face group to searchpython_groupId_1
Reuse the instantiated client across requests. Creating a new client for each request degrades moderation performance and causes unnecessary connection overhead.
# coding=utf-8
import json
import uuid

from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest

# Create a client for the cn-shanghai region.
# Load credentials from environment variables to avoid hardcoding secrets.
#   AccessKey ID:     os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
#   AccessKey secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
clt = client.AcsClient("<your-access-key-id>", "<your-access-key-secret>", "cn-shanghai")
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')

request = ImageSyncScanRequest.ImageSyncScanRequest()
request.set_accept_format('JSON')

# Build the task. The synchronous face retrieval operation supports one image per request.
# groupId identifies the face group to search against.
task1 = {
    "dataId": str(uuid.uuid1()),
    "url": "<image-url>",
    "extras": {"groupId": "<group-id>"}
}

request.set_content(bytearray(json.dumps({"tasks": [task1], "scenes": ["sface-n"]}), "utf-8"))

response = clt.do_action_with_exception(request)
print response
result = json.loads(response)

if 200 == result["code"]:
    taskResults = result["data"]
    for taskResult in taskResults:
        if 200 == taskResult["code"]:
            sceneResults = taskResult["results"]
            for sceneResult in sceneResults:
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]
                print suggestion
                print scene
                # Take action based on the scene and suggestion values.

The code prints the raw response JSON first, then the suggestion and scene values for each result. Check the suggestion field to determine how to handle the image.

Submit a local file for face retrieval

Replace the following values before running the code:

PlaceholderDescriptionExample
<your-access-key-id>AccessKey ID of your RAM userLTAI5tXxx
<your-access-key-secret>AccessKey secret of your RAM userxXxXxXx
<local-file-path>Absolute path to the local face imaged:/test/test.jpg
<group-id>ID of the face group to searchpython_groupId_1
# coding=utf-8
import json
import uuid

from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
from aliyunsdkgreenextension.request.extension import ClientUploader

# Create a client for the cn-shanghai region.
# Load credentials from environment variables to avoid hardcoding secrets.
#   AccessKey ID:     os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
#   AccessKey secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
clt = client.AcsClient("<your-access-key-id>", "<your-access-key-secret>", "cn-shanghai")
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')

request = ImageSyncScanRequest.ImageSyncScanRequest()
request.set_accept_format('JSON')

# Upload the local file to the server and get a temporary URL.
uploader = ClientUploader.getImageClientUploader(clt)
url = uploader.uploadFile('<local-file-path>')

# Build the task using the uploaded file URL.
# groupId identifies the face group to search against.
task1 = {
    "dataId": str(uuid.uuid1()),
    "url": url,
    "extras": {"groupId": "<group-id>"}
}

request.set_content(bytearray(json.dumps({"tasks": [task1], "scenes": ["sface-n"]}), "utf-8"))

response = clt.do_action_with_exception(request)
print response
result = json.loads(response)

if 200 == result["code"]:
    taskResults = result["data"]
    for taskResult in taskResults:
        if 200 == taskResult["code"]:
            sceneResults = taskResult["results"]
            for sceneResult in sceneResults:
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]
                print suggestion
                print scene
                # Take action based on the scene and suggestion values.

What's next