Java SDK を使用して、カスタム LoRA モデルをトレーニングし、AI ポートレートを生成します。
前提条件
-
Java 環境がインストールされていること。
-
5〜20 枚のトレーニング画像と 1 枚のテンプレート画像を準備します。サポートされているフォーマット:
.jpg、.jpeg、.png。-
ソロポートレートの場合、テンプレート画像には顔が 1 つだけ含まれている必要があります。トレーニング画像には同じ人物が写っている必要があります。
-
複数人ポートレートの場合、テンプレート画像には、トレーニングに使用される model_id の値の数と一致する複数の顔が含まれている必要があります。
-
画像の解像度は 512 × 512 ピクセルより大きい必要があります。
-
SDK のセットアップ
-
pom.xml の
<dependencies>セクションに aiservice 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); } }次のパラメーターを置き換えます:
パラメーター
説明
<HOST>
サーバーサイドのエンドポイント:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com。<YOUR-APPID>
有効化後、AI ポートレートページから取得します。
<YOUR-TOKEN>
有効化後、AI ポートレートページから取得します。
詳細については、GitHub のオープンソースコードをご参照ください。
API の例
AI ポートレートには、モデルトレーニング (数分) とポートレート生成 (数秒) の 2 つのステージがあります。
画像のチェック (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); // リクエスト ID。 String request_id = response.getRequestId(); // リクエスト状態。 String code = response.getCode(); // リクエスト状態の詳細。 String message = response.getMessage(); // レスポンス内容。 AIGCImageCheckData data = response.getData(); // チェック結果コード。 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 ポートレートページから取得します。
<YOUR-TOKEN>
有効化後、AI ポートレートページから取得します。
-
レスポンスの例:
レスポンスタイプ: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: 成功
-
error: 失敗
String
message
リクエスト状態の詳細。「success」はリクエストが成功したことを示します
String
data
返されたデータの詳細
AIGCImageCheckData
データフィールド (AIGCImageCheckData)
パラメーター
説明
タイプ
checkResults
各画像の検出結果。url (画像 URL)、message (検出詳細)、frontal (画像が正面ビューかどうか) を含みます
List<AIGCImageCheckResult>
costTime
サーバーサイドの処理時間 (秒)
float
images
チェックされた画像の URL
List<String>
requestId
リクエスト ID (親の requestId と同じ)
String
チェック結果メッセージ:
message
状態コード
説明
success
1
リクエスト ID。
Image decode error.
2
初回画像再構成強度
Number of faces is not 1
3
LoRA モデル名。トレーニングの model_id を入力してください。
Image detection error
4
顔検出中にエラーが発生しました
Image encoding error
5
顔を特徴ベクトルにエンコーディングする際にエラーが発生しました。顔が検出されなかったことを示します
Photo does not match other photos
6
複数の画像の顔が同じ人物のものではありません
-
モデルのトレーニング (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>
シャープネスの度合い。適切な値にすると、鮮明さが向上します。
<YOUR-APPID>
有効化後、AI ポートレートページから取得します。
<YOUR-TOKEN>
有効化後、AI ポートレートページから取得します。
-
レスポンスの例:
レスポンスタイプ: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 は成功を示し、error は失敗を示します。
String
message
リクエスト状態の詳細。「success」はリクエストが成功したことを示します。
String
data
各入力イメージの検出結果です。各イメージは、url、message、frontal という 3 つのキーを含む辞書に対応します。これらのキーは、それぞれイメージ URL、イメージの検出詳細、およびイメージが正面ビューであるかどうかを表します。
InlineResponse200Data
data フィールドの説明
パラメーター名
説明
タイプ
jobId
タスクの状態コード:
int
modelId
このトレーニングタスクからのモデルの ID。36 文字の文字列です。
String
-
job_id を使用してトレーニング結果をクエリします。
-
ポートレート生成サービスを呼び出すには、model_id を指定します。
-
トレーニングステータスのクエリ (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
リクエスト ID。
String
code
リクエスト状態コード。OK は成功を示し、error は失敗を示します。
String
message
リクエスト状態の詳細。「success」はリクエストが成功したことを示します
String
data
返されたデータの詳細。
Map<String, AsyncJobData>
data の job フィールドの説明
パラメーター名
説明
タイプ
id
タスク ID (job_id)
int
appId
ユーザー AppId
String
state
タスク状態コード:
-
0: 初期化中。
-
1: 実行中。
-
2: 成功。
-
3: 失敗。
int
message
タスク実行情報
String
Result
モデルの結果
String
モデル結果の説明 (タイプ:String)
パラメーター
説明
cost_time
トレーニングタスクが消費した合計時間
states
対応するモデルサービスがデプロイされていません。
各入力画像の検出結果。各画像は、url、message、frontal の 3 つのキーを含む辞書に対応します。これらのキーは、それぞれ画像 URL、画像検出の詳細、画像が正面ビューであるかどうかを表します。
model_id
LoRA モデル名。
これはトレーニングリクエストから取得した model_id と同じもので、ポートレート生成の入力として使用されます。
-
-
関連エラーコード
-
サービスリクエストのエラーコードは次のとおりです:
HTTP ステータスコード
code
message
説明
400
PARAMETER_ERROR
not found appid
AppId が正しくありません。
401
PARAMETER_ERROR
sign error
トークンが正しくありません。
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 Diffusion 1.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); // リクエスト ID。 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
モデルの戻り値の構成。デフォルトは None です。
configure
Map<String, Object>
モデルの戻り値の構成。デフォルトは None です
<HOST>
String
サーバーサイドのエンドポイント:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com<YOUR-APPID>
String
有効化後、AI ポートレートページから AppId を取得します
<YOUR-TOKEN>
String
有効化後、AI ポートレートページからトークンを取得します
-
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); // リクエスト ID。 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 またはプロンプトで生成する場合は、これを "t2i_generate" に設定します。
model_name
string
モデル名。Stable Diffusion XL を使用するには、これを create_xl に設定します。
configure
Map<String, Object>
モデルは `configure` 構成を返します。これはデフォルトで `None` です。
-
-
複数人ポートレート生成用 API (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); // リクエスト ID。 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
トレーニング済みモデルのモデル ID。
templateImage
String
テンプレート URL パス
model_name
String
モデル名。デフォルトは空の文字列です
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 ポートレートページでトークンを表示します。
-
-
レスポンスの例:
{ 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
トークンが正しくありません。
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.
2 番目のポートレート合成中にエラーが発生しました。
469
error
Second Stable Diffusion Process error. Check the webui status.
2 番目の Stable Diffusion プロセス中にエラーが発生しました。
469
error
Please confirm if the number of faces in the template corresponds to the user ID.
提供されたユーザー ID の数と顔の数が一致するか確認してください。
469
error
Third Stable Diffusion Process error. Check the webui status.
バックグラウンド処理中にエラーが発生しました。テンプレートを交換してください。
-
完全なワークフローの例
現在のディレクトリに AI ポートレート画像を生成する完全な例:
-
標準フロー (Stable Diffusion 1.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); // リクエスト ID。 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) { // ジョブは実行中です。 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 ポートレートページでトークンを表示します。
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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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, enormous 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); // リクエスト ID。 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); // リクエスト ID。 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); // リクエスト ID。 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, enormous filesize, best quality, realistic, photo-realistic, ultra high res, raw photo, put on makeup"; Create(t2i_prompt, template_image, ref_image); } }