Action LiveDetect

Function

Action LiveDetect determines whether a person in a video is alive by checking whether the person's actions in the video are consistent with those in the input action list. If multiple faces appear, the largest face is selected.

Prerequisites:

Restrictions:

  • Currently, only video files and Base64-encoded videos can be detected. User clients need to obtain the video streams, save them as files, and then call the LiveDetect API.
  • The size of a video file cannot exceed 8 MB. It is recommended that the video file be compressed to 200 KB to 2 MB on the client.
  • Use standard JSON format in the body of the application/json request.
  • Do not use carriage return characters in Base64 code.
  • The system does not save videos of users.
  • For details about other restrictions, see Restrictions and Limitations.

Suggestions:

  • The recommended frame rate is 10 fps to 30 fps.
  • It is recommended that the video file be compressed to 200 KB to 2 MB on the client.

URI

POST /v1/{project_id}/live-detect

Table 1 Path parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Project ID. For details about how to obtain the ID, see Obtaining the Project ID, Account Name, and AK/SK.

Request Message

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

User token.

During API authentication using a token, the token is added to requests to obtain permissions for calling the API. The value of X-Subject-Token in the response header is the obtained token.

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

video_url

Either video_url, video_file, or video_base64 is mandatory.

String

Video URL. Currently, only the URL of an OBS bucket on HUAWEI CLOUD is supported and FRS must have the permission to read data in the OBS bucket. For details about how to enable the read permission, see Service Authorization. The video requirements are as follows:
  • The video size after Base64 encoding cannot exceed 8 MB.
  • The video duration must be 1 to 15 seconds.
  • The recommended frame rate is 10 fps to 30 fps.
  • The encapsulation format can be MP4, AVI, FLV, WEBM, ASF, or MOV.
  • The video encoding format can be H.261, H.263, H.264, HEVC, VC-1, VP8, VP9, or WMV3.

video_file

Either video_file, video_url, or video_base64 is mandatory.

File

Local video file. The request format is Multipart. The video requirements are as follows:
  • The size of a video file cannot exceed 8 MB. It is recommended that the video file be compressed to 200 KB to 2 MB on the client.
  • The video duration must be 1 to 15 seconds.
  • The recommended frame rate is 10 fps to 30 fps.
  • The encapsulation format can be MP4, AVI, FLV, WEBM, ASF, or MOV.
  • The video encoding format can be H.261, H.263, H.264, HEVC, VC-1, VP8, VP9, or WMV3.

video_base64

Either video_base64, video_url, or video_file is mandatory.

String

Video data (Base64-encoded). Its requirements are as follows:
  • The video size after Base64 encoding cannot exceed 8 MB. It is recommended that the video file be compressed to 200 KB to 2 MB on the client.
  • The video duration must be 1 to 15 seconds.
  • The recommended frame rate is 10 fps to 30 fps.
  • The encapsulation format can be MP4, AVI, FLV, WEBM, ASF, or MOV.
  • The video encoding format can be H.261, H.263, H.264, HEVC, VC-1, VP8, VP9, or WMV3.

actions

Yes

String

Action code sequence list. Actions are separated by commas (,). Currently, the following actions are supported:
  • 1: Shake the head to the left.
  • 2: Shake the head to the right.
  • 3: Nod the head.
  • 4: Mouth movement

action_time

No

String

String of the action time array. The length of the array is the same as the number of actions. Each item contains the start time and end time of the action in the corresponding sequence. The unit is the milliseconds from the video start time.

Response Message

Status code: 200

Table 4 Response body parameters

Parameter

Type

Description

video-result

Object

LiveDetect result. For details about the VideoDetectResult structure, see VideoDetectResult.

This parameter is not included when the API fails to be called.

warning-list

Object

Warning information list. For details about the WarningList structure, see WarningList.

This parameter is not included when the API fails to be called.

error_code

String

Error code returned after the API fails to be called. For details, see Error Codes.

This parameter is not included when the API is successfully called.

error_msg

String

Error message returned after the API fails to be called.

This parameter is not included when the API is successfully called.

Example Requests

For details about how to obtain the value of X-Auth-Token, see Authentication.

  • Example request (Method 1: Use a Base64-encoded video.)
    POST https://{endpoint}/v1/{project_id}/live-detect
     Request Header: 
     Content-Type: application/json 
     X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... 
      
     Request Body: 
     { 
        "video_base64":"/9j/4AAQSkZJRgABAgEASABIAAD...", 
        "actions":"1,3,2",
        "action_time":"1000-3000,4000-7000,9000-12000"
     }
  • Example request (Method 2: Use a video file.)
    POST https://{endpoint}/v1/{project_id}/live-detect
     Request Header: 
     X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... 
      
     Request Body: 
     video_file: File (Video file)
     actions: 1,3,2
     action_time: 1000-3000,4000-7000,9000-12000
  • Example request (Method 3: Use the video URL.)
    POST https://{endpoint}/v1/{project_id}/live-detect
     Request Header: 
     Content-Type: application/json 
     X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... 
      
     Request Body: 
     { 
        "video_url":"/BucketName/ObjectName", 
        "actions":"1,3,2",
        "action_time":"1000-3000,4000-7000,9000-12000"
     }
  • Sample code for a Python 3 request (For codes in other languages, refer to the following sample or use the FRS SDK.)
    # -*- coding:utf-8 -*-
    
    import requests
    import base64
    
    endpoint = 'Endpoint of the region where the service is enabled'
    project_id = 'Project ID of the region where the service is enabled'
    token = "Actual token value obtained by the user"
    headers = {'Content-Type': 'application/json', 'X-Auth-Token': token}
    
    url = "https://{endpoint}/v1/{project_id}/face-compare".format(endpoint=endpoint, project_id=project_id)
    video_file_path = r'./data/face-video-demo.mp4'
    with open(video_file_path, "rb") as bin_data:
        video_data = bin_data.read()
    video_base64 = base64.b64encode(video_data).("utf-8") 
    body = {"video_base64": video_base64, "actions": "1,2,3", "action_time": "1000-3000,4000-7000,9000-12000"}
    response = requests.post(url, headers=headers, json=body, verify=False)
    print(response.text)
  • Sample code for a Java request (For codes in other languages, refer to the following sample or use the FRS SDK.)
    import com.huawei.trace.http.apache.httpclient.TraceApacheHttpClientBuilder;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpHeaders;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.socket.PlainConnectionSocketFactory;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.ssl.SSLContextBuilder;
    import org.apache.http.ssl.TrustStrategy;
    import org.apache.http.util.EntityUtils;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.concurrent.TimeUnit;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLContext;
    
    /**
     * This demo is used only for tests. You are advised to use the SDK.
     * Before using this demo, configure the HttpClient JAR package. Obtain this package by downloading the SDK.
     */
    
    public class LiveDetect {
        protected static HttpClientBuilder buildClient(HttpClientBuilder httpClientBuilder) {
            SSLContext sslContext = null;
            try {
                sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build();
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e.getMessage());
            } catch (KeyManagementException e) {
                throw new RuntimeException(e.getMessage());
            } catch (KeyStoreException e) {
                throw new RuntimeException(e.getMessage());
            }
            httpClientBuilder.setSSLContext(sslContext);
            httpClientBuilder.setConnectionTimeToLive(30, TimeUnit.SECONDS);
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            Registry<ConnectionSocketFactory> socketFactoryRegistry
                = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
                PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
            PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            connMgr.setMaxTotal(200);
            connMgr.setDefaultMaxPerRoute(100);
            httpClientBuilder.setConnectionManager(connMgr);
            return httpClientBuilder;
        }
    
        public static String doPost(String url, String jsonStr, String token, CloseableHttpClient client) {
            HttpPost post = new HttpPost(url);
            StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            //time unit is milliseconds
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
            post.setConfig(requestConfig);
            post.setHeader("X-Auth-Token", token);
            HttpResponse response = null;
            String result = "";
            try {
                response = client.execute(post);
                HttpEntity responseBody = response.getEntity();
                if (responseBody == null) {
                    System.out.println("the response body is null.");
                    return result;
                } else {
                    byte[] byteStream = EntityUtils.toByteArray(responseBody);
                    System.arraycopy(byteStream, 0, new byte[byteStream.length], 0, byteStream.length);
                    result = new String(byteStream, StandardCharsets.UTF_8);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
    
        public static void main(String[] args) {
            CloseableHttpClient client = buildClient(TraceApacheHttpClientBuilder.create()).build();
            // Replace endpoint and project_id with the actual ones.
            String url = "https://{{endpoint}}/v1/{{project_id}}/live-detect";
            String jsonStr = "{ \"video_base64\": \"/9j/4AAQSkZJRgABAgEASABIAAD...\", \"actions\": \"1,2,3\", \"action_time\": \"1000-3000,4000-7000,9000-12000\"}";
            String token = "Token of the corresponding region";
            String result = doPost(url, jsonStr, token, client);
            System.out.println(result);
        }
    }

Example Responses

Status code: 200

Response example (successful request)
{
  "video-result": {
    "alive": true,
    "actions": [{
        "action": 1,
        "confidence": 0.823
      },{
        "action": 3,
        "confidence": 0.823
      },{
        "action": 2,
        "confidence": 0.823
      }],
    "picture": "/9j/4AAQSkZJRgABAQEAYABgAAD/2w..."
  },
  "warning-list": []
}

Status code: 400

Example response (failed request)
{ 
   "error_code": "FRS.0701", 
   "error_msg": "Parse video data failed."
 }

Status Code

For details about the status code, see Status Codes.

Error Code

For details about the error code, see Error Codes.