文档

AI写真:Java SDK使用说明

更新时间:

使用Java SDK调用AI写真的算法服务接口进行模型训练和写真制作。通过SDK,您可以定制LoRA模型,并根据模板制作写真。本文为您介绍使用Java SDK调用接口之前的准备工作以及使用示例。

前提条件

  • 已准备好Java环境。

  • 已准备好5-20张训练图片和1张模板图片,用于模型训练和写真制作。图片格式支持.jpg.jpeg.png等。

    • 如果进行单人写真制作,模板图片中包含单张人脸即可。

    • 多张训练图片中的人脸属于同一个人。

    • 如果进行多人写真制作,模板图片中需包含多张人脸,且人脸数量与模型训练的model_id数量一致。

    • 请确保图片的尺寸大于512×512像素。

准备工作

  1. 环境依赖:Java,maven,aiservice-sdk写入pom.xml的dependencies如下所示。

    <dependency>
     <groupId>com.aliyun.openservices.aiservice</groupId>
     <artifactId>aiservice-sdk</artifactId>
     <version>1.0.1</version>
    </dependency>
  1. 初始化Client。

    import com.aliyun.openservices.aiservice.ApiClient;
    
    public class AIGCImageTest {
     public static ApiClient apiClient;
     static {
     String host = 'HOST';
     String appId = 'YOUR-APPID';
     String token = 'YOUR-TOKEN';
     apiClient = new ApiClient(host, appId, token);
     }
    }

    您需要根据实际情况,替换以下参数值。

    参数

    描述

    <HOST>

    服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

    <YOUR-APPID>

    开通AI写真后,您可以直接在AI写真页面查看AppId。

    <YOUR-TOKEN>

    开通AI写真后,您可以直接在AI写真页面查看Token。

更多详细内容,请参见github开源代码

调用代码示例

AI-Service的AI写真是一个非常消耗资源的服务,整体分为模型训练(分钟级别响应)和写真制作(数十秒)两个大的环节。

image

核验请求(api.aigcImagesCheck)

  • 请求代码示例如下:

    import com.aliyun.openservices.aiservice.api;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.AIGCCreatRequest;
    import com.aliyun.openservices.aiservice.model.AIGCImageCheckResponse;
    import com.aliyun.openservices.aiservice.model.AIGCImageCreateResponse;
    import com.aliyun.openservices.aiservice.model.Response;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class AIGCImageTest {
        public static ApiClient apiClient;
        private  AigcImagesApi api ;
        static {
            String host  = 'HOST';
            String appId = 'YOUR-APPID';
            String token = 'YOUR-TOKEN';
            apiClient = new ApiClient(host, appId, token);
            api = new AigcImagesApi(apiClient);
        }
    
        public void aigcImagesCheckTest() throws Exception {
            // 输入训练的图片,以URL形式存在。
            List<String> images =Arrays.asList(
                "https://xxx/0.jpg",
                "https://xxx/1.jpg",
                "https://xxx/2.jpg"
            );
    
            AIGCImageCheckResponse response = api.aigcImagesCheck(images);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            AIGCImageCheckData data = response.getData();
    
            // 返回检查结果code。
            List<AIGCImageCheckResult> CheckResultsList =  response.getCheckResults();
            for(int i=0; i < CheckResultsList.size(); i++ ){
                AIGCImageCheckResult result = CheckResultsList.get(i);
                Integer ResultCode = result.getCode();
                System.out.println(ResultCode);
            }
        }
    
    }

    参数说明

    参数位置

    参数说明

    images

    图片URL列表,List<String>。

    <HOST>

    服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

    <YOUR-APPID>

    开通AI写真后,您可以直接在AI写真页面查看AppId。

    <YOUR-TOKEN>

    开通AI写真后,您可以直接在AI写真页面查看Token。

  • 响应结果示例如下:

    response 类型:AIGCImageCheckResponse

    {
    	requestId: 3c0eeb6b-1faf-4dc4-8f9a-9a02486051c6
    	code: OK
    	message: success
    	data:
    		AIGCImageCheckData{
    			requestId = '3c0eeb6b-1faf-4dc4-8f9a-9a02486051c6', 
     			images = ["https://xxx/0.jpg",
     								"https://xxx/1.jpg",
     								"https://xxx/2.jpg"], 
    		costTime=0.5460958480834961, 
     		checkResults=[
     			AIGCImageCheckResult{
     				code=1, 
     				frontal=false, 
     				url='https://xxx/0.jpg',
     				message='success'}, 
     			AIGCImageCheckResult{
            code=1, 
              frontal=true, 
              url='https://xxx/1.jpg',
              message='success'}, 
          AIGCImageCheckResult{
            code=4,
            frontal=false, 
            url='https://xxx/2.jpg',
            message='Image detect error.'}
      		]
    		}
    }

    检查返回值说明

    参数名称

    参数说明

    类型

    requestId

    请求流水号。

    String

    code

    请求状态码,是否完成,OK或者error。

    String

    message

    请求状态详细信息,成功为success,其他视具体返回内容。

    String

    data

    返回数据详情。

    AIGCImageCheckData

    data字段说明: 类型 AIGCImageCheckData

    参数名称

    参数说明

    类型

    checkResults

    代表输入每张图片的检测结果。 每个图片对应一个字典,每个字典一共有三个key,分别是url、message与frontal,分别代表图片的URL、图片检测详情和是否为正面。

    List<AIGCImageCheckResult>

    costTime

    本次API花费的服务端计算时长。

    float

    images

    核验的图片URL list。

    List<String>

    requestId

    请求流水号(同上级request_id流水号)。

    String

    check_results的message汇总:

    message

    状态码

    含义

    success

    1

    代表符合要求。

    Image decode error.

    2

    图像无法下载或者解码。

    Number of face is not 1.

    3

    人脸数量不为1。

    Image detect error.

    4

    人脸检测出错。

    Image encoding error.

    5

    人脸编码为特征向量出错。原因一般是无法检测到人脸。

    This photo is not the same person in photos.

    6

    如果不是上面的错误,只是这个错误,代表这张脸和其他脸不是同一张脸。

模型发起训练(api.aigcImagesTrain)

  • 请求代码示例如下:

    package com.aliyun.aisdk;
    
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.*;
    
    import java.util.Arrays;
    import java.util.List;
    
    import java.io.IOException;
    
    public class AIGCImageTrain {
      public String host = 'HOST';
      public String appId = 'YOUR-APPID';
      public String token = 'YOUR-TOKEN';
    
      public ApiClient apiClient = new ApiClient(host, appId, token);
      public AigcImagesApi api = new AigcImagesApi(apiClient);
    
      public void aigcImagesTrainTest() throws Exception {
        List<String> images =Arrays.asList(
          "https://xxx/0.jpg",
          "https://xxx/1.jpg",
          "https://xxx/2.jpg"
        );
        AIGCImageTrainResponse response = api.aigcImagesTrain(images);
        int jobId = response.getData().getJobId();
        String modelId = response.getData().getModelId();
        String message = response.getMessage();
        InlineResponse200Data Data = response.getData();
    
        System.out.println(response);
        System.out.println(response.getMessage());
    
        System.out.println("jobId:" + jobId);
        System.out.println("modelId:" + modelId);
        System.out.println("Data:" + Data);
      }
    }

    参数说明

    参数位置

    参数说明

    images

    图片URL列表,List<String>。

    <HOST>

    服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

    <YOUR-APPID>

    开通AI写真后,您可以直接在AI写真页面查看AppId。

    <YOUR-TOKEN>

    开通AI写真后,您可以直接在AI写真页面查看Token。

  • 响应结果示例如下:

    response 类型:AIGCImageTrainResponse

    {
      requestId: 2bd438df-2358-4852-b6b0-bf7d39b6dde7
      code: OK
      message: success
      data: class InlineResponse200Data {
              	jobId: xxxx
                modelId: xxxx-xxxxxxxx-xxxxxx
              }
    }

  • 返回结果中的各字段说明如下:

    data字段说明

    参数名称

    参数说明

    类型

    jobId

    任务ID。

    int

    modelId

    本次模型训练的模型id,为一串长度为36的字符串编码。

    String

    • 需要获取job_id来进行训练结果查询;

    • 需要获取model_id来对进行写真制作服务的请求。

训练结果查询(jobApi.getAsyncJob)

  • 请求代码示例如下:

    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.*;
    
    
    import java.util.Arrays;
    import java.util.List;
    
    import java.io.IOException;
    
    public class AIGCJobCheck {
    	public void aigcJobStateGet() throws Exception {
        Integer jobId = new Integer(xxxx); // 异步任务ID
    
        AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        AsyncJobResponse jobResponse = jobApi.getAsyncJob(jobId);
        String request_id = jobResponse.getRequestId();
        String job_code = jobResponse.getCode();
        String job_message = jobResponse.getMessage();
        Map<String, AsyncJobData> job_data = jobResponse.getData();
    
        String Result_string = (String) job_data.get("job").getResult();
        JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
        JsonArray result_states = jsonObject.get("states").getAsJsonArray();
    
        for (int result_idx=0; result_idx < result_states.size(); result_idx++){
          JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
          String result_url = result_one.get("url").getAsString();
        }
      }
    }
  • 参数说明如下:

    参数

    类型

    描述

    jobId

    Integer

    训练任务ID。

  • 响应结果示例如下:

    • 当模型训练未执行完成时,响应结果如下:

      {
          requestId: 9a76c77d-c241-4691-8c93-fc6953fb668c
          code: OK
          message: success
          data: {
                job=AsyncJobData{
                  id=12746, 
                  appId='xxxxxxxxxx', 
                  state=1, 
                  message='model requesting', 
                  result="", 
                  requestId='111a6503-c2f7-4141-b17b-f8567e6a0a5f'
                  }
          }
      }
    • 当模型训练执行完成后,响应结果如下:

      {
            requestId: 0fc513d1-5a9e-48e1-9b6f-2eca7c0b62e9
            code: OK
            message: success
              data: {
                job=AsyncJobData{
                  id=12744, 
                  appId='xxxxxxxxxxx', 
                  state=2, 
                  message='success', 
                  result={
                    "cost_time":232.83351230621338,
                    "model_id":"xxxxxxxxxxxx",
                    "states":[{"code":1,
                               "frontal":true,
                               "message":"success",
                               "url":"https://xxxx/train/1.jpg"}]
                  }, 
                  requestId='83146ee3-68aa-40f7-b523-06f029e1db15'
                }
              }
      }
  • 训练返回值说明

    参数名称

    参数说明

    类型

    requestId

    请求流水号。

    String

    code

    请求状态码,是否完成,OK或者error。

    String

    message

    请求状态详细信息,成功为success,其他视具体返回内容。

    String

    data

    返回数据详情。

    Map<String, AsyncJobData>

    data.get("job") 字段说明

    参数名称

    参数说明

    类型

    id

    任务ID,即 job_id。

    int

    appId

    用户的AppId。

    String

    state

    任务状态码:

    • 0:任务初始化。

    • 1:任务执行中。

    • 2:任务完成。

    • 3:任务失败。

    int

    message

    任务执行信息。

    String

    Result

    模型返回结果。

    String

    Result模型返回结果说明 : Result类型String

    参数名称

    参数说明

    cost_time

    本次训练消耗的总时间

    states

    每张图片核验的结果。

    代表输入每张图片的检测结果。 每个图片对应一个字典,每个字典一共有三个key,分别是url、message与frontal,分别代表图片的URL、图片检测详情和是否为正面。

    model_id

    LoRA模型名称,同训练请求时获得的model_id。

    LoRA模型名称,等同于训练请求时获得的model_id,用于写真制作时输入。

  • 相关错误码说明

    • 请求服务错误码如下:

      HTTP状态码

      code

      message

      说明

      400

      PARAMETER_ERROR

      not found appid

      appId填写错误。

      401

      PARAMETER_ERROR

      sign error

      token填写错误。

      404

      PARAMETER_ERROR

      model not found

      对应模型服务未部署。

    • 结果查询错误如下:

      HTTP状态码

      code

      message

      说明

      462

      error

      Invalid input data

      输入数据解析错误。

      462

      error

      Image not provided

      并未提供训练图片。

      462

      error

      Make dir in oss Error.

      OSS创建文件夹失败,检查是否挂载OSS。

      462

      error

      Image process error.

      图像预处理出错。

      469

      error

      Training - Not get best template image

      训练异常退出导致没有生成参考图片。

      469

      error

      Training - Not get lora weight

      训练异常退出导致没有生成LoRA的权重。

写真制作

  • 请求代码示例如下:

    • 单人写真制作请求接口(api.aigcImagesCreate)

      • 预测sd15

        import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
        import com.aliyun.openservices.aiservice.api.AigcImagesApi;
        import com.aliyun.openservices.aiservice.ApiClient;
        import com.aliyun.openservices.aiservice.ApiException;
        import com.aliyun.openservices.aiservice.model.*;
        
        
        import java.io.FileOutputStream;
        import java.io.OutputStream;
        import java.util.Arrays;
        import java.util.List;
        
        import java.io.IOException;
        
        import sun.misc.BASE64Decoder;
        import sun.misc.BASE64Encoder;
        
        public class AIGCImageService {
          public String host = 'HOST';
          public String appId = 'YOUR-APPID';
          public String token = 'YOUR-TOKEN';
        
          public ApiClient apiClient = new ApiClient(host, appId, token);
          public AigcImagesApi api = new AigcImagesApi(apiClient);
        
          public void aigcImageCreateGet() throws Exception {
            String modelId = "xxx-xxxx";
            String templateImage = "https://xxxx.jpg";
            String model_name = "";
            Map<String, Object> configure = new TreeMap<String, Object>();
        
            AIGCImageCreateResponse createResponse = api.aigcImagesCreate(modelId, templateImage, model_name, configure);
        
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
        
            // 生成图片的 base64
            String imgStr = createResponse.getData().getImage();
        
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
              //调整异常数据
              if (imgBtyes[i] < 0) {
                imgBtyes[i] += 256;
              }
            }
        
            String imgFilePath = "test_single.jpg";
            OutputStream out = new FileOutputStream(imgFilePath);
        
            out.write(imgBtyes);
            out.flush();
            out.close();
          }
        }

        参数说明如下:

        参数

        类型

        描述

        modelId

        String

        LoRA模型名称,需要输入训练获得的model-id。

        当使用ipa_control_only模式时设置为""。

        templateImage

        String

        模板的URL路径。

        model_name

        String

        模型名称,默认输入空字符串。

        configure

        Map<String, Object>

        模型返回配置configure,默认输入None。

        <HOST>

        String

        服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

        <YOUR-APPID>

        String

        开通AI写真后,您可以直接在AI写真页面查看AppId。

        <YOUR-TOKEN>

        String

        开通AI写真后,您可以直接在AI写真页面查看Token。

        configure内部参数

        configure内部参数名称

        参数说明

        类型

        是否必须

        默认值

        取值范围

        lora_weights

        LoRA强度。

        float

        0.90

        0.5~1.0

        first_denoising_strength

        第一次图像重建的强度。

        float

        0.45

        0.0~1.0

        second_denoising_strength

        第二次图像重建的强度。

        float

        0.30

        0.0~1.0

        more_like_me

        更像我的强度。

        float

        0.50

        0.0~1.0

        crop_face_preprocess

        是否裁剪图像后进行重建,大图建议开启。

        bool

        True

        True, False

        apply_face_fusion_before

        是否进行第一次人像融合。

        bool

        True

        True, False

        apply_face_fusion_after

        是否进行第二次人像融合。

        bool

        True

        True, False

        color_shift_middle

        是否进行第一次颜色校正。

        bool

        True

        True, False

        color_shift_last

        是否进行第二次颜色校正。

        bool

        True

        True, False

        background_restore

        是否重建背景。

        bool

        False

        True, False

        skin_retouching_bool

        是否进行皮肤平滑。

        开启后会进行皮肤的平滑与变亮,一般会使得图片更好看,但可能会导致皮肤过白,关闭后可以提高皮肤的质感。

        bool

        False

        True, False

        photo_enhancement_bool

        是否进行人像增强。

        开启后会进行人像修复或者超分,用于提高生成图片质量。

        bool

        True

        True, False

        photo_enhancement_method

        人像增强方式。

        photo_fix则是进行图像修复,可能会导致一些失真但会修复不合理的地方,可能会失去一些皮肤的质感。

        super_resolution则仅进行图像超分,更大幅度的保留原图。

        String

        photo_fix

        photo_fix, super_resolution

        makeup_transfer

        是否进行妆容迁移。

        开启后会进行妆容迁移,防止图片过素,但也可能导致图像有一些不像用户。

        bool

        False

        True, False

        makeup_transfer_ratio

        进行妆容迁移的强度。

        理论上值越大妆容迁移的比例就越大,生成的妆容也越像模板,但也可能导致图像有一些不像用户。

        float

        0.5

        0.0~1.0

        face_shape_match

        是否进行脸型的适配。

        开启后会减弱控制的强度,脸型与皮肤质感相比于之前会更加贴近用户。

        bool

        False

        True, False

        ipa_control

        是否进行ipa的控制。

        开启后会提高人像的相似度,但容易受到参考图片的影响。

        bool

        False

        True, False

        ipa_control_only

        开启后可以无需训练进行预测。

        开启后必须填入ipa_image_path。

        bool

        False

        True, False

        ipa_image_path

        参考人像的URL。

        开启ipa_control_only后必须填写。

        String

        None

        可下载的url

        ipa_weight

        ipa的控制强度。

        理论上,值越大时出图越像用户,但值太大容易导致图像失真。

        float

        0.5

        0.0~1.0

        style_name

        用于设置生成的风格。

        真实或者漫画风格。

        str

        Realistic

        Realistic,

        Anime

        lcm_accelerate

        用于设置生成的风格,是否进行lcm加速。

        bool

        False

        True, False

        sharp_ratio

        锐化程度,适当的值可以提高清晰度。

        过高会导致图片失真。

        float

        0.15

        0.0~1.0

        t2i_prompt

        如果期望使用文生图功能,则需要在这里设置提示词。

        如果设置了t2i_prompt则可以不传入模板的URL路径。

        String

        None

      • 预测sdxl

        import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
        import com.aliyun.openservices.aiservice.api.AigcImagesApi;
        import com.aliyun.openservices.aiservice.ApiClient;
        import com.aliyun.openservices.aiservice.ApiException;
        import com.aliyun.openservices.aiservice.model.*;
        
        
        import java.io.FileOutputStream;
        import java.io.OutputStream;
        import java.util.Arrays;
        import java.util.List;
        
        import java.io.IOException;
        
        import sun.misc.BASE64Decoder;
        import sun.misc.BASE64Encoder;
        
        public class AIGCImageService {
          public String host = 'HOST';
          public String appId = 'YOUR-APPID';
          public String token = 'YOUR-TOKEN';
        
          public ApiClient apiClient = new ApiClient(host, appId, token);
          public AigcImagesApi api = new AigcImagesApi(apiClient);
        
          public void aigcImageCreateGet() throws Exception {
            String modelId = "xxx-xxxx";
            String templateImage = "https://xxxx.jpg";
            String model_name = "create_xl";
            Map<String, Object> configure = new TreeMap<String, Object>();
        
            AIGCImageCreateResponse createResponse = api.aigcImagesCreate(modelId, templateImage, model_name, configure);
        
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
        
            // 生成图片的 base64
            String imgStr = createResponse.getData().getImage();
        
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
              //调整异常数据
              if (imgBtyes[i] < 0) {
                imgBtyes[i] += 256;
              }
            }
        
            String imgFilePath = "test_single.jpg";
            OutputStream out = new FileOutputStream(imgFilePath);
        
            out.write(imgBtyes);
            out.flush();
            out.close();
          }
        }

        参数说明如下:

        参数位置

        类型

        参数说明

        modelId

        string

        LoRA模型名称,需要输入训练获得的model-id。当使用ipa_control_only模式时设置为""。

        templateImage

        string

        模板的URL路径。

        当使用scene_lora或者prompt生成时设置为"t2i_generate"。

        model_name

        string

        模型名称,使用sdxl则需要设置为create_xl。

        configure

        Map<String, Object>

        模型返回配置configure,默认输入None。

        configure内部参数

        configure内部参数名称

        参数说明

        类型

        是否必须

        默认值

        取值范围

        lora_weights

        LoRA的应用强度。

        理论上,值越大时出图越像用户,但值太大容易导致图像失真。

        float

        0.90

        0.5~1.0

        first_diffusion_steps

        第一次diffusion的步数。

        不建议修改,过低会导致图像失真。

        int

        50

        20-50

        first_denoising_strength

        第一次图像重建的强度。

        人物脸部的重建强度,越大进行的重建越多,理论上越大时出图越像用户,但值太大会导致图片不协调。

        float

        0.45

        0.0~1.0

        second_diffusion_steps

        第二次diffusion的步数。

        不建议修改,过低会导致图像失真。

        int

        30

        20-50

        second_denoising_strength

        第二次图像重建的强度。

        人物脸部边缘的重建强度,值太大会导致图片不协调。

        float

        0.30

        0.0~1.0

        more_like_me

        更像我的强度。

        人像融合的比例,值越大越像本人,值太大会导致图片真实感降低。

        float

        0.60

        0.0~1.0

        crop_face_preprocess

        是否裁剪图像后进行重建,大图建议开启。

        不建议调整。

        bool

        True

        True, False

        apply_face_fusion_before

        是否进行第一次人像融合。

        开启后会进行人像融合,不开启会导致相似度降低。

        bool

        True

        True, False

        apply_face_fusion_after

        是否进行第二次人像融合。

        开启后会进行人像融合,不开启会导致相似度降低。

        bool

        True

        True, False

        color_shift_middle

        是否进行第一次颜色校正。

        开启后会进行颜色矫正,使得输出图片的肤色更像模板。不开启则不会矫正,存在色偏的可能。

        bool

        True

        True, False

        color_shift_last

        是否进行第二次颜色校正。

        开启后会进行颜色矫正,使得输出图片的肤色更像模板。不开启则不会矫正,存在色偏的可能。

        bool

        True

        True, False

        background_restore

        是否重建背景。

        开启后会进行背景重建,理论上会让图片更自然,但会改变背景并且增加耗时。

        bool

        False

        True, False

        skin_retouching_bool

        是否进行皮肤平滑。

        开启后会进行皮肤的平滑与变亮,一般会使得图片更好看,但可能会导致皮肤过白,关闭后可以提高皮肤的质感。

        bool

        False

        True, False

        photo_enhancement_bool

        是否进行人像增强。

        开启后会进行人像修复或者超分,用于提高生成图片质量。

        bool

        True

        True, False

        photo_enhancement_method

        人像增强方式:

        photo_fix则是进行图像修复,可能会导致一些失真,但会修复不合理的地方,可能会失去一些皮肤的质感。

        super_resolution则仅进行图像超分,更大幅度地保留原图。

        String

        photo_fix

        photo_fix, super_resolution

        makeup_transfer

        是否进行妆容迁移。

        开启后会进行妆容迁移,防止图片过素,但也可能导致图像有一些不像用户。

        bool

        False

        True, False

        makeup_transfer_ratio

        进行妆容迁移的强度。

        理论上值越大妆容迁移的比例就越大,生成的妆容也越像模板,但也可能导致图像有一些不像用户。

        float

        0.5

        0.0~1.0

        ipa_control

        是否进行ipa的控制。

        开启后会提高人像的相似度,但容易受到参考图片的影响。

        bool

        False

        True, False

        ipa_control_only

        开启后可以无需训练进行预测。

        开启后必须填入ipa_image_path。

        bool

        False

        True, False

        ipa_image_path

        参考人像的URL。

        开启ipa_control_only后必须填入。

        String

        None

        可下载的URL

        ipa_weight

        ipa的控制强度。

        理论上越大时出图越像用户,但值太大容易导致图像失真。

        float

        0.5

        0.0~1.0

        lcm_accelerate

        用于设置生成的风格,是否进行lcm加速。

        bool

        False

        True, False

        sharp_ratio

        锐化程度,适当的值可以提高清晰度。

        过高会导致图片失真

        float

        0.15

        0.0~1.0

        scene_id

        如果期望使用scene lora则需要在这里设置scene id。

        scene id由训练获得,训练sdxl场景LoRA时返回model id即为scene id。

        String

        None

        t2i_prompt

        如果期望使用文生图功能则需要在这里设置提示词。

        如果设置了t2i_prompt则可以不传入模板的URL路径。

        String

        None

    • 多人写真制作请求接口(api.aigcImagesCreateByMultiModelIds)

      import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
      import com.aliyun.openservices.aiservice.api.AigcImagesApi;
      import com.aliyun.openservices.aiservice.ApiClient;
      import com.aliyun.openservices.aiservice.ApiException;
      import com.aliyun.openservices.aiservice.model.*;
      
      
      import java.io.FileOutputStream;
      import java.io.OutputStream;
      import java.util.Arrays;
      import java.util.List;
      
      import java.io.IOException;
      
      import sun.misc.BASE64Decoder;
      import sun.misc.BASE64Encoder;
      
      public class AIGCImageService {
        public String host = 'HOST';
        public String appId = 'YOUR-APPID';
        public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
      
        public void aigcImageCreateMulti() throws Exception {
          String[] modelIds = new String[]{"model-id1","model-id2"};
          String templateImage = "https://xxxx.jpg";
          String model_name = "";
          Map<String, Object> configure = new TreeMap<String, Object>();
      
          AIGCImageCreateResponse createResponse = api.aigcImagesCreateByMultiModelIds(model_id, template_image, model_name, config);
      
          // 请求流水号
          String request_id = createResponse.getRequestId();
          // 请求状态
          String code = createResponse.getCode();
          // 请求状态具体信息
          String message = createResponse.getMessage();
          // 请求返回内容
          AIGCImageCreateData data = createResponse.getData();
      
          // 生成图片的Base64
          String imgStr = createResponse.getData().getImage();
      
          BASE64Decoder decoder = new BASE64Decoder();
          byte[] imgBtyes = decoder.decodeBuffer(imgStr);
          for (int i = 0; i < imgBtyes.length; ++i) {
            // 调整异常数据
            if (imgBtyes[i] < 0) {
              imgBtyes[i] += 256;
            }
          }
      
          String imgFilePath = "test_multi.jpg";
          OutputStream out = new FileOutputStream(imgFilePath);
      
          out.write(imgBtyes);
          out.flush();
          out.close();
        }
      }

      参数

      类型

      描述

      modelId

      String

      训练模型的model id。

      templateImage

      String

      模板的URL路径。

      model_name

      String

      模型名称,默认输入空字符串。

      configure

      Map<String, Object>

      模型返回配置configure,默认输入None。

      <HOST>

      String

      服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

      <YOUR-APPID>

      String

      开通AI写真后,您可以直接在AI写真页面查看AppId。

      <YOUR-TOKEN>

      String

      开通AI写真后,您可以直接在AI写真页面查看Token。

  • 响应结果示例如下:

    {
     requestId: 5eb7741b-540b-4a5c-9c98-fdd1d714e51f
     code: OK
     message: success
     data: com.aliyun.openservices.aiservice.model.AIGCImageCreateData@358c99f5
    }

    data 类型 AIGCImageCreateData

    参数名称

    参数说明

    类型

    costTime

    生成花费时间。

    Float

    image

    图片base64。

    String

  • 制作错误码说明

    • 请求服务错误

      HTTP状态码

      code

      message

      说明

      400

      PARAMETER_ERROR

      not found appid

      appId填写错误

      401

      PARAMETER_ERROR

      sign error

      token填写错误

      404

      PARAMETER_ERROR

      model not found

      对应模型服务未部署

    • 结果查询错误

      HTTP状态码

      code

      message

      说明

      462

      error

      Invalid input data. Please check the input dict.

      输入数据解析错误。

      462

      error

      Image not provided. Please check the template_image.

      并未提供写真制作的模板图片。

      462

      error

      Prompts get error. Please check the model_id.

      检查提供的model_id格式。

      462

      error

      Face id image decord error. Pleace check the user's lora is trained or not.

      face id图片解码异常,请检查是否模型是否训练。

      462

      error

      Roop image decord error. Pleace check the user's lora is trained or not.

      Roop图像不存在,请检查模型是否训练。

      462

      error

      Template image decode error. Please Give a new template.

      模板图片解码错误,请给一张新的模板。

      462

      error

      There is not face in template. Please Give a new template.

      模板图像不存在人脸,请给一个新的模板。

      462

      error

      Template image process error. Please Give a new template.

      模板图片预处理错误,请提供一张新的模板。

      469

      error

      First Face Fusion Error, Can't get face in template image.

      第一次人脸融合出错。

      469

      error

      First Stable Diffusion Process error. Check the webui status.

      第一次Stable Diffusion处理出错

      469

      error

      Second Face Fusion Error, Can't get face in template image.

      第二次人脸融合出错。

      469

      error

      Second Stable Diffusion Process error. Check the webui status.

      第二次Stable Diffusion处理出错。

      469

      error

      Please confirm if the number of faces in the template corresponds to the user ID.

      请检查所给的user id数量与人脸数量是否相符。

      469

      error

      Third Stable Diffusion Process error. Check the webui status.

      背景处理出错,请更换模板。

端到端流程示例代码

端到端流程的代码示例如下。当代码执行成功后,会在当前目录生成AI写真制作图片。

  • 常规链路(sd15)

    package com.aliyun.aisdk;
    
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.model.*;
    
    
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.util.Arrays;
    import java.util.List;
    
    import java.io.IOException;
    
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    
    public class AIGCImageRunner {
    
      public String host = 'HOST';
      public String appId = 'YOUR-APPID';
      public String token = 'YOUR-TOKEN';
    
      public ApiClient apiClient = new ApiClient(host, appId, token);
      public AigcImagesApi api = new AigcImagesApi(apiClient);
    
      public byte[] base64ToBytes(String imgStr) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imgBtyes = decoder.decodeBuffer(imgStr);
        for (int i = 0; i < imgBtyes.length; ++i) {
          //调整异常数据
          if (imgBtyes[i] < 0) {
            imgBtyes[i] += 256;
          }
        }
    
        return imgBtyes;
      }
    
      public void aigcImagesCheck(List<String> images) throws Exception{
        AIGCImageCheckResponse response = api.aigcImagesCheck(images);
      }
    
      public Object[] aigcImagesTrainRun(List<String> images) throws Exception {
    
        AIGCImageTrainResponse response = api.aigcImagesTrain(images);
        int jobId = response.getData().getJobId();
    
        Object[] trainOut = new Object[2];
    
        System.out.println(response);
        System.out.println(response.getMessage());
    
        System.out.println("jobId:" + jobId);
        System.out.println("modelId:" + response.getData().getModelId());
        System.out.println(response.getData());
    
        trainOut[0]=jobId;
        trainOut[1] = response.getData().getModelId();
        return trainOut;
      }
    
      public Integer aigcJobStateGet(AiServiceJobApi jobApi, int jobId_int) throws Exception {
        Integer jobId = new Integer(jobId_int); // 异步任务ID
    
        AsyncJobResponse jobResponse = jobApi.getAsyncJob(jobId);
    
        System.out.println(jobResponse.getData().get("job").getResult());
    
        return jobResponse.getData().get("job").getState();
      }
    
      public void CreateSingle(String modelId, String templateImage) throws Exception {
    
        AIGCImageCreateResponse createResponse = api.aigcImagesCreate(modelId, templateImage);
    
        // 生成图片的 base64
        String imgStr = createResponse.getData().getImage();
        System.out.println(createResponse.getData());
    
        byte[] imgBtyes = base64ToBytes(imgStr);
    
        String imgFilePath = "test_single.jpg";
        OutputStream out = new FileOutputStream(imgFilePath);
    
        out.write(imgBtyes);
        out.flush();
        out.close();
      }
      
      public void CreateMulti(String[] model_ids, String template_image)throws ApiException, IOException {
            
        		String imgFilePath = "test_multi.jpg";
        		AIGCImageCreateResponse createResponse = api.aigcImagesCreateByMultiModelIds(model_ids, template_image, model_name, config);
    
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_ids,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
              	
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
        }
    
    
      public void aigcEndtoEndCreate() throws Exception {
        List<String> images =Arrays.asList(
          "https://xxx/0.jpg",
          "https://xxx/1.jpg",
          "https://xxx/2.jpg"
        );
        String templateImage = "https://xxx.jpg";
        String multiTemplateImage = "https://xxx.jpg";
    
        Object[] o = aigcImagesTrainRun(images);
        int jobId = (int)o[0];
        String modelId = (String)o[1];
        
        AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        while(true){
          Integer jobState = aigcJobStateGet(jobApi, jobId);
    
          if (jobState == AsyncJobState.JOB_STATE_WAIT) { // job running
            System.out.println("job running");
          } else if (jobState == AsyncJobState.JOB_STATE_SUCCESS) {
            System.out.println("job success");
            break;
          } else {
            System.out.println("job fail");
            throw new Exception("job fail");
          }
    
          try {
            Thread.sleep(30000);
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }
        }
        
        
    
        CreateSingle(modelId,templateImage);
    
    
        String[] modelIds = new String[]{modelId,modelId};
        CreateMulti(model_ids, template_image)
    
      }
    
    }

    参数说明如下:

    参数

    描述

    <HOST>

    服务端地址:http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com

    <YOUR-APPID>

    开通AI写真后,您可以直接在AI写真页面查看AppId。

    <YOUR-TOKEN>

    开通AI写真后,您可以直接在AI写真页面查看Token。

    images

    用于训练模型的图片URL地址,多个URL地址之间使用半角逗号(,)分隔。

    templateImage

    模板图片的URL地址,包含单张人脸。用于单人写真制作。

    multiTemplateImage

    模板图片的URL地址,包含多张人脸,且人脸数量和所给的model_id一致。用于多人写真制作。

  • 常规链路(sdxl)

    sdxl需要首先联系PAI的同学开通服务后,通过指定模型名称来进行使用。

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    
    public class PhotoEndtoEndTest {
    
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                //调整异常数据
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            AIGCImageCheckData data = response.getData();
    
            // 打印返回结果
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
        public Object[] Train(List<String> images, String model_name, Map<String, Object> config) throws ApiException {
            Integer job_id = -1;
            String model_id = "";
    
            AIGCImageTrainResponse response = this.api.aigcImagesTrain(images,model_name,config);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            InlineResponse200Data Data = response.getData();
    
            // 打印返回结果
            if (!code.equals("OK")){
                System.out.printf("aigc_images_train failed, request id is %s\n", request_id);
    
            }else{
                job_id = response.getData().getJobId();
                model_id = response.getData().getModelId();
    
                System.out.printf("train job_id is %d, model id %s\n",job_id.intValue(),model_id);
    
            }
            Integer state = -1;
            while(true){
                AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
                String job_code = jobResponse.getCode();
                String job_message = jobResponse.getMessage();
                Map<String, AsyncJobData> job_data = jobResponse.getData();
    
                if (!job_code.equals("OK")){
                    System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                            request_id, job_message);
                    job_id = new Integer(-1);
                    model_id = "";
    
                }else{
                    state = job_data.get("job").getState();
                    if (state.equals(2)){
                        System.out.printf("model %s trained successfully\n",model_id);
                        break;
                    }else if(!state.equals(3)){
                        System.out.printf("training model %s\n",model_id);
    
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        System.out.printf("model %s trained failed, message: %s\n",model_id,job_message);
                        break;
                    }
                }
    
            }
    
            if (!state.equals(2)){
                model_id = "";
            }
    
            Object[] out = new Object[2];
            out[0] = job_id;
            out[1] = model_id;
    
            return out;
    
        }
    
        public String[] QueryValidImageUrlsByJob(Integer job_id) throws ApiException {
            String[] image_urls = null;
    
            AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
            String request_id = jobResponse.getRequestId();
            String job_code = jobResponse.getCode();
            String job_message = jobResponse.getMessage();
            Map<String, AsyncJobData> job_data = jobResponse.getData();
    
            if (!job_code.equals("OK")) {
                System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                        request_id, job_message);
            }else {
                Integer state = job_data.get("job").getState();
                if (state == 2){
                    System.out.printf("Job %s trained successfully\n", job_id);
                    String Result_string = (String) job_data.get("job").getResult();
                    JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
                    JsonArray result_states = jsonObject.get("states").getAsJsonArray();
                    image_urls = new String[result_states.size()];
                    for (int result_idx=0; result_idx < result_states.size(); result_idx++){
                        JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
                        String result_url = result_one.get("url").getAsString();
                        image_urls[result_idx] = result_url;
                    }
    
                }else{
                    System.out.printf("job %s not ready\n",job_id);
                }
            }
    
            return image_urls;
        }
    
        public boolean Create(String model_id, String template_image, String output_image, String model_name, Map<String, Object> config) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
            try{
                createResponse = api.aigcImagesCreate(model_id, template_image, model_name, config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_id,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
        public boolean CreateMulti(String[] model_ids, String template_image, String output_image, String model_name, Map<String, Object> config) throws ApiException, IOException {
            AIGCImageCreateResponse createResponse = api.aigcImagesCreateByMultiModelIds(model_ids, template_image, model_name, config);
    
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_ids,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
            List<String> images = Arrays.asList(
                    "https://xxx/0.jpg",
                    "https://xxx/1.jpg",
                    "https://xxx/2.jpg"
            );
    
            
    
            String template_image = "https://xxx.jpg";
            String multi_template_image = "https://xxx.jpg";
          
            String model_name = "train_xl";
            Map<String, Object> config = new HashMap<String, Object>();
    
            Object[] train_out = Train(images, model_name, config);
    
            Integer job_id= (Integer) train_out[0];
            String model_id =  (String) train_out[1];
    
    
    
            String[] model_ids = {model_id,model_id};
            model_name = "create_xl"; //""
            Map<String, Object> configure = new TreeMap<String, Object>();
    
            Create(model_id, template_image,"single_out.jpg", model_name,configure);
    
            CreateMulti(model_ids, multi_template_image,"multi_out.jpg", model_name,configure);
    
    
        }
    
    }

  • 无需训练,通过单参考图制作链路。

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    public class PhotoReferCreateTest {
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                //调整异常数据
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            AIGCImageCheckData data = response.getData();
    
            // 打印返回结果
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
    
    
        public boolean Create(String template_image, String output_image, String ref_image) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
    
            Map<String, Object> config = new TreeMap<String, Object>();
    
            config.put("ipa_control_only",true);
            config.put("ipa_weight",0.6);
            config.put("ipa_image_path",ref_image);
            try{
                createResponse = api.aigcImagesCreate("", template_image, "", config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_id,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream(output_image);
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
    
            String template_image = "https://demo.jpg";
            String ref_image = "https://reference.jpg";
          
            Create(template_image,"ref_out.jpg", ref_image);
    
    
        }
    }
    

  • 无需模板,通过提示词生成模板制作链路。

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Ignore;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    public class PhotoPtomptCreateTest {
    
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                //调整异常数据
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            AIGCImageCheckData data = response.getData();
    
            // 打印返回结果
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
        public Object[] Train(List<String> images, String model_name, Map<String, Object> config) throws ApiException {
            Integer job_id = -1;
            String model_id = "";
    
            AIGCImageTrainResponse response = this.api.aigcImagesTrain(images,model_name,config);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            InlineResponse200Data Data = response.getData();
    
            // 打印返回结果
            if (!code.equals("OK")){
                System.out.printf("aigc_images_train failed, request id is %s\n", request_id);
    
            }else{
                job_id = response.getData().getJobId();
                model_id = response.getData().getModelId();
    
                System.out.printf("train job_id is %d, model id %s\n",job_id.intValue(),model_id);
    
            }
            Integer state = -1;
            while(true){
                AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
                String job_code = jobResponse.getCode();
                String job_message = jobResponse.getMessage();
                Map<String, AsyncJobData> job_data = jobResponse.getData();
    
                if (!job_code.equals("OK")){
                    System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                            request_id, job_message);
                    job_id = new Integer(-1);
                    model_id = "";
    
                }else{
                    state = job_data.get("job").getState();
                    if (state.equals(2)){
                        System.out.printf("model %s trained successfully\n",model_id);
                        break;
                    }else if(!state.equals(3)){
                        System.out.printf("training model %s\n",model_id);
    
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        System.out.printf("model %s trained failed, message: %s\n",model_id,job_message);
                        break;
                    }
                }
    
            }
    
            if (!state.equals(2)){
                model_id = "";
            }
    
            Object[] out = new Object[2];
            out[0] = job_id;
            out[1] = model_id;
    
            return out;
    
        }
    
        public String[] QueryValidImageUrlsByJob(Integer job_id) throws ApiException {
            String[] image_urls = null;
    
            AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
            String request_id = jobResponse.getRequestId();
            String job_code = jobResponse.getCode();
            String job_message = jobResponse.getMessage();
            Map<String, AsyncJobData> job_data = jobResponse.getData();
    
            if (!job_code.equals("OK")) {
                System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                        request_id, job_message);
            }else {
                Integer state = job_data.get("job").getState();
                if (state == 2){
                    System.out.printf("Job %s trained successfully\n", job_id);
                    String Result_string = (String) job_data.get("job").getResult();
                    JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
                    JsonArray result_states = jsonObject.get("states").getAsJsonArray();
                    image_urls = new String[result_states.size()];
                    for (int result_idx=0; result_idx < result_states.size(); result_idx++){
                        JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
                        String result_url = result_one.get("url").getAsString();
                        image_urls[result_idx] = result_url;
                    }
    
                }else{
                    System.out.printf("job %s not ready\n",job_id);
                }
            }
    
            return image_urls;
        }
    
        public boolean Create(String model_id, String t2i_prompt, String template_image) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
            HashMap<String,Object> config = new HashMap<String, Object>();
            config.put("t2i_prompt", t2i_prompt);
            try{
                createResponse = api.aigcImagesCreate(model_id, template_image, "", config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, model_id is %s, request_id is %s\n",model_id,request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream("prompt_out.jpg");
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
    
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
    
    
            List<String> images =Arrays.asList(
          			"https://xxx/0.jpg",
          			"https://xxx/1.jpg",
          			"https://xxx/2.jpg"
        		);
    
            String template_image = "https://demo.jpg";
    
            String model_name = "";
            Map<String, Object> config = new HashMap<String, Object>();
    
            Object[] train_out = Train(images, model_name, config);
    
            Integer job_id= (Integer) train_out[0];
            String model_id =  (String) train_out[1];
    
            String t2i_prompt = "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, huge filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup";
            Create(model_id, t2i_prompt, template_image);
    
        }
    
    }
    

  • 无需模板与训练,通过提示词与单参考图生成模板制作链路。

    package com.aliyun.aiservice.demo;
    
    import com.aliyun.openservices.aiservice.ApiClient;
    import com.aliyun.openservices.aiservice.ApiException;
    import com.aliyun.openservices.aiservice.api.AiServiceJobApi;
    import com.aliyun.openservices.aiservice.api.AigcImagesApi;
    import com.aliyun.openservices.aiservice.model.*;
    import com.google.gson.JsonArray;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import org.junit.Ignore;
    import org.junit.Test;
    import sun.misc.BASE64Decoder;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.*;
    
    public class PhotoPtomptCreateTest {
    
        public String host = 'HOST';
      	public String appId = 'YOUR-APPID';
      	public String token = 'YOUR-TOKEN';
      
        public ApiClient apiClient = new ApiClient(host, appId, token);
        public AigcImagesApi api = new AigcImagesApi(apiClient);
        public AiServiceJobApi jobApi = new AiServiceJobApi(apiClient);
    
        public byte[] base64ToBytes(String imgStr) throws IOException {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] imgBtyes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < imgBtyes.length; ++i) {
                //调整异常数据
                if (imgBtyes[i] < 0) {
                    imgBtyes[i] += 256;
                }
            }
    
            return imgBtyes;
        }
    
        public boolean Check(List<String> images) throws ApiException {
            AIGCImageCheckResponse response = this.api.aigcImagesCheck(images);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            AIGCImageCheckData data = response.getData();
    
            // 打印返回结果
            boolean is_ok = false;
            if (!code.equals("OK")){
                System.out.printf("aigc_images_check failed,request id is %\n", request_id);
            }else{
                is_ok = true;
                System.out.printf("check images done, input %d images, return %d images, %d filtered by lvwang\n",
                        images.size(),(data.getCheckResults().size()),(images.size()-data.getCheckResults().size()));
                for (int check_result_idx=0; check_result_idx < data.getCheckResults().size();check_result_idx++ ){
                    AIGCImageCheckResult checkResult = data.getCheckResults().get(check_result_idx);
                    Integer checkResultCode = checkResult.getCode();
                    if (checkResultCode.equals(1)){
                        System.out.printf("check %s success\n", checkResult.getUrl());
                    }else {
                        is_ok = false;
                        System.out.printf("check %s failed, message is %s , request_id is %s\n",
                                checkResult.getUrl(),checkResult.getMessage(),request_id);
                    }
                }
            }
            return is_ok;
        }
    
        public Object[] Train(List<String> images, String model_name, Map<String, Object> config) throws ApiException {
            Integer job_id = -1;
            String model_id = "";
    
            AIGCImageTrainResponse response = this.api.aigcImagesTrain(images,model_name,config);
            // 请求流水号
            String request_id = response.getRequestId();
            // 请求状态
            String code = response.getCode();
            // 请求状态具体信息
            String message = response.getMessage();
            // 请求返回内容
            InlineResponse200Data Data = response.getData();
    
            // 打印返回结果
            if (!code.equals("OK")){
                System.out.printf("aigc_images_train failed, request id is %s\n", request_id);
    
            }else{
                job_id = response.getData().getJobId();
                model_id = response.getData().getModelId();
    
                System.out.printf("train job_id is %d, model id %s\n",job_id.intValue(),model_id);
    
            }
            Integer state = -1;
            while(true){
                AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
                String job_code = jobResponse.getCode();
                String job_message = jobResponse.getMessage();
                Map<String, AsyncJobData> job_data = jobResponse.getData();
    
                if (!job_code.equals("OK")){
                    System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                            request_id, job_message);
                    job_id = new Integer(-1);
                    model_id = "";
    
                }else{
                    state = job_data.get("job").getState();
                    if (state.equals(2)){
                        System.out.printf("model %s trained successfully\n",model_id);
                        break;
                    }else if(!state.equals(3)){
                        System.out.printf("training model %s\n",model_id);
    
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
    
                    }else{
                        System.out.printf("model %s trained failed, message: %s\n",model_id,job_message);
                        break;
                    }
                }
    
            }
    
            if (!state.equals(2)){
                model_id = "";
            }
    
            Object[] out = new Object[2];
            out[0] = job_id;
            out[1] = model_id;
    
            return out;
    
        }
    
        public String[] QueryValidImageUrlsByJob(Integer job_id) throws ApiException {
            String[] image_urls = null;
    
            AsyncJobResponse jobResponse = this.jobApi.getAsyncJob(job_id);
            String request_id = jobResponse.getRequestId();
            String job_code = jobResponse.getCode();
            String job_message = jobResponse.getMessage();
            Map<String, AsyncJobData> job_data = jobResponse.getData();
    
            if (!job_code.equals("OK")) {
                System.out.printf("get_async_job failed, request id is %s, message is %s\n",
                        request_id, job_message);
            }else {
                Integer state = job_data.get("job").getState();
                if (state == 2){
                    System.out.printf("Job %s trained successfully\n", job_id);
                    String Result_string = (String) job_data.get("job").getResult();
                    JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject();
                    JsonArray result_states = jsonObject.get("states").getAsJsonArray();
                    image_urls = new String[result_states.size()];
                    for (int result_idx=0; result_idx < result_states.size(); result_idx++){
                        JsonObject result_one = result_states.get(result_idx).getAsJsonObject();
                        String result_url = result_one.get("url").getAsString();
                        image_urls[result_idx] = result_url;
                    }
    
                }else{
                    System.out.printf("job %s not ready\n",job_id);
                }
            }
    
            return image_urls;
        }
    
        public boolean Create(String t2i_prompt, String template_image, String ref_image) throws IOException {
            System.out.println("Create");
            AIGCImageCreateResponse createResponse = null;
            HashMap<String,Object> config = new HashMap<String, Object>();
    
            config.put("t2i_prompt", t2i_prompt);
            config.put("ipa_control_only", true);
            config.put("ipa_weight", 0.6);
            config.put("ipa_image_path", ref_image);
    
            try{
                createResponse = api.aigcImagesCreate("", template_image, "", config);
            }catch (ApiException e){
                System.out.println();
                System.out.println(e.getResponseBody());
            }
            System.out.println(createResponse);
            // 请求流水号
            String request_id = createResponse.getRequestId();
            // 请求状态
            String code = createResponse.getCode();
            // 请求状态具体信息
            String message = createResponse.getMessage();
            // 请求返回内容
            AIGCImageCreateData data = createResponse.getData();
    
            if (!code.equals("OK")){
                System.out.printf("aigc_images_create failed, request_id is %s\n",request_id);
            }else {
                String imgStr = createResponse.getData().getImage();
                byte[] image = base64ToBytes(imgStr);
    
                OutputStream out = new FileOutputStream("ref_prompt_out.jpg");
    
                out.write(image);
                out.flush();
                out.close();
    
            }
            return true;
        }
    
    
    
        @Test
        public void aigcEndtoEndCreate() throws Exception {
    
            String template_image = "https://demo.jpg";
            String ref_image = "https://reference.jpg";
    
    
            String t2i_prompt = "(portrait:1.5), 1girl, bokeh, bouquet, brown_hair, cloud, flower, hairband, hydrangea, lips, long_hair, outdoors, sunlight, white_flower, white_rose, green sweater, sweater, (cloth:1.0), (best quality), (realistic, photo-realistic:1.3), film photography, minor acne, (portrait:1.1), (indirect lighting), extremely detailed CG unity 8k wallpaper, huge filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup";
            Create(t2i_prompt, template_image, ref_image);
    
        }
    
    }
    
  • 本页导读 (1)
文档反馈