使用Java SDK調用AI寫真的演算法服務介面進行模型訓練和寫真製作。通過SDK,您可以定製LoRA模型,並根據模板製作寫真。本文為您介紹使用Java SDK調用介面之前的準備工作以及使用樣本。
前提條件
已準備好Java環境。
已準備好5-20張訓練圖片和1張模板圖片,用於模型訓練和寫真製作。圖片格式支援
.jpg、.jpeg、.png等。如果進行單人寫真製作,模板圖片中包含單張人臉即可。多張訓練圖片中的人臉屬於同一個人。
如果進行多人寫真製作,模板圖片中需包含多張人臉,且人臉數量與模型訓練的model_id數量一致。
請確保訓練圖片和模板圖片的尺寸大於512×512像素。
準備工作
環境依賴:在Maven工程中使用aiservice SDK,必須在pom.xml檔案<dependencies>中添加aiservice SDK的依賴,如下所示:
<dependency> <groupId>com.aliyun.openservices.aiservice</groupId> <artifactId>aiservice-sdk</artifactId> <version>1.0.1</version> </dependency>
初始化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寫真是一個資源消耗量較大的服務,主要包括模型訓練和寫真製作兩個環節。模型訓練通常需要幾分鐘的回應時間,而寫真製作則只需要數十秒即可完成。
核驗請求(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 } }
返回結果中的各欄位說明如下:
參數名稱
參數說明
類型
requestId
請求流水號。
String
code
請求狀態代碼,是否完成,OK或者error。
String
message
請求狀態詳細資料,成功為success,其他視具體返回內容。
String
data
返回資料詳情。
InlineResponse200Data
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)
預測Stable Diffusion1.5
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
模型名稱,預設輸入Null 字元串。
configure
Map<String, Object>
模型返回配置,預設輸入None。
<HOST>
String
服務端地址:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com。<YOUR-APPID>
String
開通AI寫真後,您可以直接在AI寫真頁面查看AppId。
<YOUR-TOKEN>
String
開通AI寫真後,您可以直接在AI寫真頁面查看Token。
預測Stable Diffusion XL
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
模型名稱,使用Stable Diffusion XL則需要設定為create_xl。
configure
Map<String, Object>
模型返回配置configure,預設輸入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
模型名稱,預設輸入Null 字元串。
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.
使用者上傳的圖片解碼異常,請檢查是否模型是否訓練。
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寫真製作圖片。
常規鏈路(Stable Diffusion1.5)
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一致。用於多人寫真製作。
常規鏈路(Stable Diffusion XL)
使用Stable Diffusion XL模型,首先需要聯絡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); } }
通過單參考圖進行AI寫真製作(無需進行模型訓練)
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); } }通過提示詞和單參考圖產生模板映像進行AI寫真製作(無需提供模板映像)
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); } }通過提示詞和單參考圖產生模板映像進行AI寫真製作(無需提供模板映像和進行模型訓練)
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); } }