SDK for Javaを使用すると、モデルトレーニングとポートレート作成のためにAI Portraitのアルゴリズムサービスインターフェイスを呼び出すことができます。 SDKを使用して、カスタムLoRAモデルを設定し、テンプレートイメージに基づいてポートレートを作成できます。 このトピックでは、SDK for Javaを使用して関連するインターフェイスを呼び出す前に必要な準備について説明します。 このトピックでは、インターフェイスの呼び出し方法の例も示します。
前提条件
Java環境を用意する。
1枚のテンプレート画像と5〜20枚のトレーニング画像が、モデルトレーニングとポートレート作成のために用意される。 次のイメージ形式がサポートされています。
. jpg
,. jpeg
、および. png
.ソロポートレートの場合、テンプレート画像は1つの顔のみを含む必要があります。
ソロポートレートの場合、複数のトレーニング画像の顔は同じ人物に属している必要があります。
複数の人物のポートレートの場合、テンプレート画像に複数の顔が含まれている必要があり、顔の数はモデルのトレーニングに使用されるmodel_idパラメーターの数と同じである必要があります。
各画像のサイズが512 × 512ピクセルより大きいことを確認してください。
準備
Mavenプロジェクトのpom.xmlファイルにai-service SDKの依存関係を追加します。
<dependency> <groupId>com.aliyun.openservices.aiservice</groupId> <artifactId>aiservice-sdk</artifactId> <version>1.0.1</version> </dependency>
クライアントを初期化します。
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); } }
ビジネス要件に基づいてパラメーターを設定します。 下表に、各パラメーターを説明します。
パラメーター
説明
<ホスト>
サーバーアドレス。 例:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com
。<YOUR-APPID>
登録申請 ID。 AI Portraitを有効にすると、AI PortraitページでアプリケーションIDを表示できます。
<YOUR-TOKEN>
トークン。 AI Portraitを有効にすると、AI Portraitページでトークンを表示できます。
詳細については、「GitHubオープンソースコード」をご参照ください。
サンプルコード
AI Portraitは、モデルトレーニングとポートレート作成を含むリソース集約型のサービスです。 ほとんどの場合、モデルのトレーニングには数分かかりますが、ポートレートの作成には数十秒しかかかりません。
チェックリクエスト (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 { // Enter the URL of a training image. List<String> images =Arrays.asList( "https://xxx/0.jpg", "https://xxx/1.jpg", "https://xxx/2.jpg" ); AIGCImageCheckResponse response = api.aigcImagesCheck(images); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. AIGCImageCheckData data = response.getData(); // The code of the check result. 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); } } }
次の表に、上記のコードのパラメーターを示します。
パラメーター
説明
画像
List<String> で指定されたイメージURL。
<ホスト>
サーバーアドレス。 例:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com
。<YOUR-APPID>
登録申請 ID。 AI Portraitを有効にすると、AI PortraitページでアプリケーションIDを表示できます。
<YOUR-TOKEN>
トークン。 AI Portraitを有効にすると、AI Portraitページでトークンを表示できます。
次のコードブロックは、応答のサンプルを示しています。
応答タイプ: 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
リクエストの ID。
String
code
リクエストのステータスコード。 有効な値: OKとエラー。 OKはリクエストが完了したことを示し、エラーはリクエストが完了していないことを示します。
String
message
リクエストのステータスの詳細。 リクエストが成功した場合、成功が返されます。 他のシナリオでは、異なるメッセージが返されます。
String
data
返されたデータの詳細。
AIGCImageCheckData
次の表に、型がAIGCImageCheckDataのデータフィールドについて説明します。
パラメーター
の説明
タイプ
checkResults
各入力画像の検出結果。 各画像は辞書に対応する。 辞書には、url、message、およびfrontalのキーが含まれています。 urlキーは画像のURLを示し、メッセージキーは画像の検出内容を示し、正面キーは画像が正面であるか否かを示す。
リスト <AIGCImageCheckResult>
costTime
サーバーがAPIを呼び出すのに必要な計算時間。
float
イメージ
チェックされている画像のURL。
リスト <String>
requestId
リクエストの ID。 IDは、上位レベルのrequestIdパラメーターの値と同じです。
String
次の表に、check_resultsのメッセージを示します。
メッセージ
ステータスコード
の説明
success
1
イメージは要件を満たしています。
イメージのデコードエラー。
2
イメージをダウンロードまたはデコードできません。
顔の数は1ではありません。
3
面の数は1ではありません。
イメージ検出エラー。
4
顔の検出中にエラーが発生しました。
画像エンコードエラー。
5
顔を特徴ベクトルとしてエンコード中にエラーが発生しました。 ほとんどの場合、顔が検出されないために問題が発生します。
この写真は写真の同じ人物ではありません。
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); } }
次の表に、上記のコードのパラメーターを示します。
パラメーター
説明
画像
List<String> で指定されたイメージURL。
<ホスト>
サーバーアドレス。 例:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com
。<YOUR-APPID>
登録申請 ID。 AI Portraitを有効にすると、AI PortraitページでアプリケーションIDを表示できます。
<YOUR-TOKEN>
トークン。 AI Portraitを有効にすると、AI Portraitページでトークンを表示できます。
次のコードブロックは、応答のサンプルを示しています。
レスポンスタイプ: AIGCImageTrainResponse
{ requestId: 2bd438df-2358-4852-b6b0-bf7d39b6dde7 code: OK message: success data: class InlineResponse200Data { jobId: xxxx modelId: xxxx-xxxxxxxx-xxxxxx } }
下表にレスポンスパラメーターを示します。
パラメーター
説明
データ型
requestId
リクエストの ID。
String
code
リクエストのステータスコード。 有効な値: OKとエラー。 OKはリクエストが完了したことを示し、エラーはリクエストが完了していないことを示します。
String
message
リクエストのステータスの詳細。 リクエストが成功した場合、成功が返されます。 他のシナリオでは、異なるメッセージが返されます。
String
data
返されたデータの詳細。
InlineResponse200Data
次の表に、データフィールドを示します。
パラメーター
説明
データ型
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); // The ID of the asynchronous job. 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
リクエストの ID。
String
code
リクエストのステータスコード。 有効な値: OKとエラー。 OKはリクエストが完了したことを示し、エラーはリクエストが完了していないことを示します。
String
message
リクエストのステータスの詳細。 リクエストが成功した場合、成功が返されます。 他のシナリオでは、異なるメッセージが返されます。
String
data
返されたデータの詳細。
マップ <文字列、AsyncJobData>
次の表に、data.get("job") によって返される結果フィールドを示します。
パラメーター
説明
データ型
id
ジョブのID。job_idパラメーターの値と同じです。
int
appId
ユーザーのアプリケーションID。
String
です。
ジョブのステータスコード。
0: ジョブの初期化中です。
1: ジョブが実行中です。
2: ジョブが完了しました。
3: ジョブに失敗しました。
int
message
ジョブの実行情報。
String
結果
モデルによって返された結果。
String
次の表に、モデルによって返される結果を示します。 Resultパラメーターのデータ型は文字列です。
パラメーター
説明
cost_time
このトレーニングに費やされた時間。
状態
各画像のチェック結果。
各入力画像の検出結果。 各画像は辞書に対応する。 辞書には、url、message、およびfrontalのキーが含まれています。 urlキーは画像のURLを示し、メッセージキーは画像の検出内容を示し、正面キーは画像が正面であるか否かを示す。
model_id
LoRAモデルのID。トレーニングリクエストで取得したmodel_idパラメーターの値と同じです。 ポートレートの作成中に名前を入力できます。
関連するエラーコードの説明
次の表に、リクエストのエラーコードを示します。
HTTPステータスコード
エラーコード
メッセージ
説明
400
PARAMETER_ERROR
appidが見つかりません
アプリケーションIDが無効です。
401
PARAMETER_ERROR
サインエラー
トークンが無効です。
404
PARAMETER_ERROR
モデルが見つかりません
要求されたモデルサービスがデプロイされていません。
次の表に、結果クエリのエラーコードを示します。
HTTPステータスコード
エラーコード
メッセージ
説明
462
error
無効な入力データ
入力データの解析中にエラーが発生しました。
462
error
提供されていない画像
トレーニング画像は提供されません。
462
error
ossエラーでdirを作成します。
Object Storage Service (OSS) にフォルダーを作成できませんでした。 OSSバケットがマウントされているかどうかを確認します。
462
error
画像処理エラー。
イメージの前処理中にエラーが発生しました。
469
error
トレーニング-最高のテンプレート画像を取得しない
予期せずトレーニングが終了し、参照画像の生成に失敗する。
469
error
トレーニング-ロラの体重を増やさない
トレーニングは予期せず終了し、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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. AIGCImageCreateData data = createResponse.getData(); // The Base64-encoded image. String imgStr = createResponse.getData().getImage(); BASE64Decoder decoder = new BASE64Decoder(); byte[] imgBtyes = decoder.decodeBuffer(imgStr); for (int i = 0; i < imgBtyes.length; ++i) { // Modify abnormal data. 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パラメーターがTrueに設定されている場合、このパラメーターを "" に設定します。
templateImage
String
テンプレートのURLパス。
model_name
String
モデルの名前。 デフォルトでは、空の文字列が入力されます。
設定
Map<String, Object>
設定アイテムが返されました。 デフォルト値 : None。
<ホスト>
String
サーバーアドレス。 例:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com
。<YOUR-APPID>
String
登録申請 ID。 AI Portraitを有効にすると、AI PortraitページでアプリケーションIDを表示できます。
<YOUR-TOKEN>
String
トークン。 AI Portraitを有効にすると、AI Portraitページでトークンを表示できます。
予測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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. AIGCImageCreateData data = createResponse.getData(); // The Base64-encoded image. String imgStr = createResponse.getData().getImage(); BASE64Decoder decoder = new BASE64Decoder(); byte[] imgBtyes = decoder.decodeBuffer(imgStr); for (int i = 0; i < imgBtyes.length; ++i) { // Modify abnormal data. 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パラメーターがTrueに設定されている場合、このパラメーターを "" に設定します。
templateImage
String
テンプレートのURLパス。
scene_loraまたはプロンプトを使用してイメージを生成する場合は、パラメーターをt2i_generateに設定します。
model_name
String
モデルの名前。 SDXLを使用する場合は、パラメーターをcreate_xlに設定します。
インストールと
Map<String, Object>
設定アイテムが返されました。 デフォルト値 : 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. AIGCImageCreateData data = createResponse.getData(); // The Base64-encoded image. String imgStr = createResponse.getData().getImage(); BASE64Decoder decoder = new BASE64Decoder(); byte[] imgBtyes = decoder.decodeBuffer(imgStr); for (int i = 0; i < imgBtyes.length; ++i) { // Modify abnormal data. 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
返されたモデルのID。
templateImage
String
テンプレートのURLパス。
model_name
String
モデルの名前。 デフォルトでは、空の文字列が入力されます。
設定
Map<String, Object>
設定アイテムが返されました。 デフォルト値 : None。
<ホスト>
String
サーバーアドレス。 例:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com
。<YOUR-APPID>
String
登録申請 ID。 AI Portraitを有効にすると、AI PortraitページでアプリケーションIDを表示できます。
<YOUR-TOKEN>
String
トークン。 AI Portraitを有効にすると、AI Portraitページでトークンを表示できます。
次のコードブロックは、応答のサンプルを示しています。
{ requestId: 5eb7741b-540b-4a5c-9c98-fdd1d714e51f code: OK message: success data: com.aliyun.openservices.aiservice.model.AIGCImageCreateData@358c99f5 }
次の表に、型がAIGCImageCreateDataのデータフィールドについて説明します。
パラメーター
説明
データ型
costTime
ポートレートの作成に費やした時間。
浮く
イメージ
Base64-encodedイメージ。
String
ポートレート作成時に返されるエラーコードの説明
リクエストエラー
HTTPステータスコード
エラーコード
メッセージ
の説明
400
PARAMETER_ERROR
appidが見つかりません
アプリケーションIDが無効です。
401
PARAMETER_ERROR
サインエラー
トークンが無効です。
404
PARAMETER_ERROR
モデルが見つかりません
要求されたモデルサービスがデプロイされていません。
結果クエリエラー
HTTPステータスコード
エラーコード
メッセージ
の説明
462
error
入力データが無効です。 入力dictを確認してください。
入力データの解析中にエラーが発生しました。
462
error
提供されていない画像。 template_imageを確認してください。
ポートレート作成に使用するテンプレート画像は提供されません。
462
error
プロンプトがエラーを取得します。 model_idを確認してください。
model_idパラメーターの値の形式が無効です。
462
error
顔id画像decordエラー。 ユーザーのloraが訓練されているかどうかを確認してください。
イメージのデコード中にエラーが発生しました。 モデルがトレーニングされているかどうかを確認します。
462
error
Roop image decordエラー。 ユーザーのloraが訓練されているかどうかを確認してください。
Roopイメージは存在しません。 モデルがトレーニングされているかどうかを確認します。
462
error
テンプレート画像のデコードエラー。 新しいテンプレートを与えてください。
テンプレートイメージのデコード中にエラーが発生しました。 新しいテンプレートイメージを提供します。
462
error
テンプレートに顔がありません。 新しいテンプレートを与えてください。
テンプレート画像では顔を検出できません。 新しいテンプレートイメージを提供します。
462
error
テンプレート画像処理エラー。 新しいテンプレートを与えてください。
テンプレートイメージの前処理中にエラーが発生しました。 新しいテンプレートイメージを提供します。
469
error
最初の顔融合エラー、テンプレート画像で顔を取得できません。
最初のポートレートマージ中にエラーが発生しました。
469
error
最初の安定した拡散プロセスエラー。 webuiステータスを確認します。
最初の安定拡散中にエラーが発生しました。
469
error
2番目の顔融合エラー、テンプレート画像で顔を取得できません。
2回目のポートレートマージ中にエラーが発生しました。
469
error
第2安定拡散プロセスエラー。 webuiステータスを確認します。
2回目の安定拡散中にエラーが発生しました。
469
error
テンプレートの顔の数がユーザーIDに対応しているかどうかを確認してください。
指定されたユーザーIDの数が顔の数と一致するかどうかを確認します。
469
error
第3安定拡散プロセスエラー。 webuiステータスを確認します。
バックグラウンドの前処理中にエラーが発生しました。 テンプレートを変更します。
エンドツーエンドのポートレート作成プロセスのサンプルコード
次のコードブロックは、エンドツーエンドのポートレート作成プロセスの例を示しています。 コードの実行後、現在のディレクトリにAIポートレートが作成されます。
レギュラーリンク (安定した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) { // Modify abnormal data. 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); // The ID of the asynchronous task. 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); // The Base64-encoded image. 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. 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) } }
下表に、各パラメーターを説明します。
パラメーター
説明
<ホスト>
サーバーアドレス。 例:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com
。<YOUR-APPID>
登録申請 ID。 AI Portraitを有効にすると、AI PortraitページでアプリケーションIDを表示できます。
<YOUR-TOKEN>
トークン。 AI Portraitを有効にすると、AI Portraitページでトークンを表示できます。
画像
モデルのトレーニングに使用されるイメージのURL。 複数のURLを指定する場合は、複数のURLをコンマ (,) で区切ります。
templateImage
1つの顔を含むテンプレート画像のURL。 テンプレート画像は、ソロポートレート作成に使用されます。
multiTemplateImage
テンプレート画像のURL。 テンプレート画像には複数の顔が含まれており、顔の数は指定されたmodel_idパラメーターの数と同じです。 テンプレート画像は、複数人のポートレート作成に使用されます。
レギュラーリンク (安定拡散XL)
SDXLモデルをモデルトレーニングとポートレート作成に使用する前に、Platform for AI (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) { // Modify abnormal data. if (imgBtyes[i] < 0) { imgBtyes[i] += 256; } } return imgBtyes; } public boolean Check(List<String> images) throws ApiException { AIGCImageCheckResponse response = this.api.aigcImagesCheck(images); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. AIGCImageCheckData data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. InlineResponse200Data Data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. 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) { // Modify abnormal data. if (imgBtyes[i] < 0) { imgBtyes[i] += 256; } } return imgBtyes; } public boolean Check(List<String> images) throws ApiException { AIGCImageCheckResponse response = this.api.aigcImagesCheck(images); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. AIGCImageCheckData data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. 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) { // Modify abnormal data. if (imgBtyes[i] < 0) { imgBtyes[i] += 256; } } return imgBtyes; } public boolean Check(List<String> images) throws ApiException { AIGCImageCheckResponse response = this.api.aigcImagesCheck(images); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. AIGCImageCheckData data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. InlineResponse200Data Data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. 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) { // Modify abnormal data. if (imgBtyes[i] < 0) { imgBtyes[i] += 256; } } return imgBtyes; } public boolean Check(List<String> images) throws ApiException { AIGCImageCheckResponse response = this.api.aigcImagesCheck(images); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. AIGCImageCheckData data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = response.getRequestId(); // The request status. String code = response.getCode(); // The details of the request status. String message = response.getMessage(); // The response to the request. InlineResponse200Data Data = response.getData(); // Print the returned result. 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); // The ID of the request. String request_id = createResponse.getRequestId(); // The request status. String code = createResponse.getCode(); // The details of the request status. String message = createResponse.getMessage(); // The response to the request. 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); } }