Skip to main content

Get started with FaceChain character likeness training

Call the FaceChain face detection and character likeness training APIs to validate training images, upload files, and train a character likeness model.

  • This document applies only to the "Chinese mainland (Beijing)" region. You must use an API key from this region.

Getting started

Prerequisites

Function introduction

Workflow

  1. Activate Alibaba Cloud Model Studio and obtain an API key. For more information, see Obtain an API key and API host.
  2. (Optional) Call the face detection API to check the quality of user-uploaded images. You can use this as a preliminary check in your product to prompt users to replace low-quality images. For more information, see Face Detection API details.
  3. Package the image files, then upload and manage them. For more information, see Alibaba Cloud Model Studio File Management API.
  4. Call the character likeness training API to train a character likeness model and obtain the model ID. For more information, see Character Likeness Training API details.

Sample code

The following code shows how to use the native FaceChain API to train a character likeness model. Before you run the code:
  • Replace YOUR_DASHSCOPE_API_KEY in the example with your API key.
  • Install the required dependencies.
  • Follow the instructions in the code comments to replace the file paths.
If you do not have suitable photos, you can download our samples: sample1, sample2, and sample3.

Dependencies and code

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>the-latest-version2</version>
</dependency>
package com.alibaba.dashscope.demo;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class FacechainDemo {
    private static final String API_KEY = "YOUR_DASHSCOPE_API_KEY";


    public static void main(String[] args) throws Exception {
        List<String> sourceFileLocalPaths = new ArrayList<>();
        // This example shows how to package two local photos into a local ZIP file.
        sourceFileLocalPaths.add("Replace this with the local path of your image file, for example, /home/admin/sample/sample1.jpeg");
        sourceFileLocalPaths.add("Replace this with the local path of your image file, for example, /home/admin/sample/sample2.jpeg");
        String targetZipFileLocalPath = "Replace this with the desired local path for the output ZIP package, for example, /home/admin/sample/sample.zip";
        // Package the files.
        zipFiles(sourceFileLocalPaths, targetZipFileLocalPath);
        // Upload the file to the DashScope platform.
        JSONObject uploadResponse = uploadFile(targetZipFileLocalPath);
        // Get the file_id generated after the file is uploaded.
        String fileId = uploadResponse.getJSONObject("data").getJSONArray("uploaded_files").getJSONObject(0).getString(
            "file_id");
        // Start the training job.
        JSONObject finetuneRequest = new JSONObject();
        // Static field.
        finetuneRequest.put("model", "facechain-finetune");
        JSONArray fileIds = new JSONArray();
        fileIds.add(fileId);
        finetuneRequest.put("training_file_ids", fileIds);
        JSONObject createFinetuneResponse = sendPostRequest("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/fine-tunes",
            finetuneRequest.toJSONString());
        // Get the job ID of the created training job.
        String jobId = createFinetuneResponse.getJSONObject("output").getString("job_id");
        // Poll the job status until it succeeds.
        String queryJobUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/fine-tunes/" + jobId;
        String finetunedOutput = null;
        do {
            JSONObject jobQueryResponse = sendGetRequest(queryJobUrl);
            String jobStatus = jobQueryResponse.getJSONObject("output").getString("status");
            if ("SUCCEEDED".equals(jobStatus)) {
                finetunedOutput = jobQueryResponse.getJSONObject("output").getString("finetuned_output");
            } else if ("FAILED".equals(jobStatus)) {
                throw new Exception("the job is failed");
            } else {
                System.out.println("the job " + jobId + " is now " + jobStatus);
                Thread.sleep(10 * 1000);
            }
        } while (Objects.isNull(finetunedOutput));
        // finetuned_output is the resourceId.
        System.out.println("Got the FaceChain resourceId: " + finetunedOutput);
    }

    private static void zipFiles(List<String> sourceFileLocalPaths, String targetZipFileLocalPath) {
        try {
            FileOutputStream fos = new FileOutputStream(targetZipFileLocalPath);
            ZipOutputStream zos = new ZipOutputStream(fos);
            byte[] buffer = new byte[1024];

            for (String sourceFile : sourceFileLocalPaths) {
                File file = new File(sourceFile);
                FileInputStream fis = new FileInputStream(file);
                zos.putNextEntry(new ZipEntry(file.getName()));

                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }

                fis.close();
                zos.closeEntry();
            }

            zos.close();
            System.out.println("Files compressed successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static JSONObject uploadFile(String fileToUpload) {
        StringBuilder responseBuilder = new StringBuilder();
        try {
            URL url = new URL("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/files");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            // Set the request header.
            conn.setRequestProperty("Authorization", API_KEY);
            conn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=---------------------------1234567890");
            // Create a file stream.
            File file = new File(fileToUpload);
            FileInputStream fis = new FileInputStream(file);
            // Get the output stream.
            OutputStream os = conn.getOutputStream();
            // Write the request body.
            os.write(("-----------------------------1234567890\r\n" +
                "Content-Disposition: form-data; name=\"files\"; filename=\"" + file.getName() + "\"\r\n" +
                "Content-Type: application/octet-stream\r\n" +
                "\r\n").getBytes());

            // Write the file content.
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

            // Write the end flag for the request.
            os.write(("\r\n-----------------------------1234567890--\r\n").getBytes());

            // Close the streams.
            fis.close();
            os.flush();
            os.close();

            // Get the response code.
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("File upload succeeded");
                // Read the response body.
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    responseBuilder.append(line);
                }
                br.close();
            } else {
                System.out.println("File upload failed with response code: " + responseCode);
                // Read the response body.
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    responseBuilder.append(line);
                }
                br.close();
            }
            System.out.println("File upload finished. Response: " + responseBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(responseBuilder.toString());
    }

    public static JSONObject sendPostRequest(String url, String jsonBody) {
        StringBuilder responseBuilder = new StringBuilder();
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)requestUrl.openConnection();
            conn.setRequestMethod("POST");

            // Set the request header.
            conn.setRequestProperty("Authorization", API_KEY);
            conn.setRequestProperty("Content-Type", "application/json");

            // Set the request body.
            conn.setDoOutput(true);
            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            os.writeBytes(jsonBody);
            os.flush();
            os.close();

            // Get the response code.
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Read the response body.
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    responseBuilder.append(line);
                }
                br.close();
            } else {
                System.out.println("HTTP POST request failed with response code: " + responseCode);
                // Read the response body.
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    responseBuilder.append(line);
                }
                br.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("POST request response is: " + responseBuilder.toString());
        return JSONObject.parseObject(responseBuilder.toString());
    }

    public static JSONObject sendGetRequest(String url) {
        StringBuilder responseBuilder = new StringBuilder();
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)requestUrl.openConnection();
            conn.setRequestMethod("GET");
            // Set the request header.
            conn.setRequestProperty("Authorization", API_KEY);
            conn.setRequestProperty("Content-Type", "application/json");
            // Get the response code.
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Read the response body.
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    responseBuilder.append(line);
                }
                br.close();
            } else {
                System.out.println("HTTP GET request failed with response code: " + responseCode);
                // Read the response body.
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    responseBuilder.append(line);
                }
                br.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("GET request response is: " + responseBuilder.toString());
        return JSONObject.parseObject(responseBuilder.toString());
    }
}

Learn more

For details about FaceChain API calls, see Face Detection API details and Character Likeness Training API details.
Text Generation
Video Generation
World models
3D Model Generation
Audio
  • Audio generation
Realtime API
Text Embedding
Decision Model
TokenPlan
Model Production