Java ソフトウェア開発キット (SDK) を使用して AI ポートレートサービスを呼び出し、モデルトレーニングとポートレート生成を実行できます。SDK を使用すると、LoRA モデルをカスタマイズし、テンプレートからポートレートを生成できます。このトピックでは、必要な事前準備について説明し、コード例を示します。
前提条件
-
Java 環境がインストールされていること。
-
モデルトレーニングとポートレート生成用に、5〜20 枚のトレーニングイメージと 1 枚のテンプレートイメージが用意されていること。サポートされているイメージフォーマットは、
.jpg、.jpeg、.pngです。-
シングルポートレートの場合、テンプレートイメージには顔が 1 つだけ含まれている必要があります。トレーニングイメージ内の顔は、すべて同じ人物のものである必要があります。
-
複数人ポートレートの場合、テンプレートイメージには複数の顔が含まれている必要があります。顔の数は、モデルトレーニングに使用される model_id の値の数と同じである必要があります。
-
トレーニングイメージとテンプレートイメージのディメンションが 512 × 512 ピクセル以上であることを確認してください。
-
事前準備
-
aiservice SDK の依存関係を `pom.xml` ファイルの <dependencies> セクションに追加します。
<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 ポートレートをアクティベートした後、AI ポートレートページで AppId を表示できます。
<YOUR-TOKEN>
AI ポートレートをアクティベートした後、AI ポートレートページでトークンを表示できます。
詳細については、GitHub のオープンソースコードをご参照ください。
コード例
AI ポートレートはリソース集約型のサービスであり、モデルトレーニングとポートレート生成の 2 つの主要な段階があります。モデルトレーニングは通常、完了までに数分かかりますが、ポートレート生成は数十秒で完了します。
チェックリクエスト (api.aigcImagesCheck)
-
次のコードブロックは、リクエスト例を示しています。
import com.aliyun.openservices.aiservice.api; import com.aliyun.openservices.aiservice.ApiClient; import com.aliyun.openservices.aiservice.ApiException; import com.aliyun.openservices.aiservice.model.AIGCCreatRequest; import com.aliyun.openservices.aiservice.model.AIGCImageCheckResponse; import com.aliyun.openservices.aiservice.model.AIGCImageCreateResponse; import com.aliyun.openservices.aiservice.model.Response; import java.util.Arrays; import java.util.List; public class AIGCImageTest { public static ApiClient apiClient; private AigcImagesApi api ; static { String host = 'HOST'; String appId = 'YOUR-APPID'; String token = 'YOUR-TOKEN'; apiClient = new ApiClient(host, appId, token); api = new AigcImagesApi(apiClient); } public void aigcImagesCheckTest() throws Exception { // トレーニングイメージの URL。 List<String> images =Arrays.asList( "https://xxx/0.jpg", "https://xxx/1.jpg", "https://xxx/2.jpg" ); AIGCImageCheckResponse response = api.aigcImagesCheck(images); // リクエスト 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 ポートレートをアクティベートした後、AI ポートレートページで AppId を表示できます。
<YOUR-TOKEN>
AI ポートレートをアクティベートした後、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
data フィールドの説明 (タイプ: AIGCImageCheckData)
パラメーター名
説明
タイプ
checkResults
各入力イメージの検出結果。各イメージは、url、message、frontal の 3 つのキーを含む辞書に対応します。これらのキーは、それぞれイメージ URL、イメージ検出の詳細、およびイメージが正面ビューであるかどうかを表します。
List<AIGCImageCheckResult>
costTime
この API 呼び出しのサーバー側での計算時間。
float
images
チェックされたイメージの URL のリスト。
List<String>
requestId
リクエスト ID。これは親の request_id と同じです。
String
check_results のメッセージの概要:
message
ステータスコード
説明
success
1
要件を満たしています。
Image decode error.
2
イメージをダウンロードまたはデコードできません。
Number of face is not 1.
3
イメージ内の顔の数が 1 ではありません。
Image detect error.
4
顔検出中にエラーが発生しました。
Image encoding error.
5
顔を特徴ベクトルにエンコードする際にエラーが発生しました。これは、顔が検出されなかったことを示します。
This photo is not the same person in photos.
6
このエラーは、複数のイメージの顔が同じ人物のものではないことを示します。
-
モデルトレーニングの開始 (api.aigcImagesTrain)
-
次のコードブロックは、リクエスト例を示しています。
package com.aliyun.aisdk; import com.aliyun.openservices.aiservice.api.AigcImagesApi; import com.aliyun.openservices.aiservice.ApiClient; import com.aliyun.openservices.aiservice.ApiException; import com.aliyun.openservices.aiservice.model.*; import java.util.Arrays; import java.util.List; import java.io.IOException; public class AIGCImageTrain { public String host = 'HOST'; public String appId = 'YOUR-APPID'; public String token = 'YOUR-TOKEN'; public ApiClient apiClient = new ApiClient(host, appId, token); public AigcImagesApi api = new AigcImagesApi(apiClient); public void aigcImagesTrainTest() throws Exception { List<String> images =Arrays.asList( "https://xxx/0.jpg", "https://xxx/1.jpg", "https://xxx/2.jpg" ); AIGCImageTrainResponse response = api.aigcImagesTrain(images); int jobId = response.getData().getJobId(); String modelId = response.getData().getModelId(); String message = response.getMessage(); InlineResponse200Data Data = response.getData(); System.out.println(response); System.out.println(response.getMessage()); System.out.println("jobId:" + jobId); System.out.println("modelId:" + modelId); System.out.println("Data:" + Data); } }パラメーター
パラメーターの場所
説明
images
イメージ URL のリスト。タイプ: List<String>。
<HOST>
サーバー側アドレス:
http://ai-service.ce8cc13b6421545749e7b4605f3d02607.cn-hangzhou.alicontainer.com。<YOUR-APPID>
AI ポートレートをアクティベートした後、AI ポートレートページで AppId を表示できます。
<YOUR-TOKEN>
AI ポートレートをアクティベートした後、AI ポートレートページでトークンを表示できます。
-
次のコードブロックは、レスポンス例を示しています。
レスポンスタイプ: 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
返されたデータの詳細。
InlineResponse200Data
data フィールドの説明
パラメーター名
説明
タイプ
jobId
タスク ID。
int
modelId
このトレーニングタスクから得られるモデルの ID。36 文字の文字列です。
String
-
job_id を使用してトレーニング結果をクエリします。
-
ポートレート生成サービスを呼び出すには、model_id を指定する必要があります。
-
トレーニング結果のクエリ (jobApi.getAsyncJob)
-
次のコードブロックは、リクエスト例を示しています。
import com.aliyun.openservices.aiservice.api.AiServiceJobApi; import com.aliyun.openservices.aiservice.api.AigcImagesApi; import com.aliyun.openservices.aiservice.ApiClient; import com.aliyun.openservices.aiservice.ApiException; import com.aliyun.openservices.aiservice.model.*; import java.util.Arrays; import java.util.List; import java.io.IOException; public class AIGCJobCheck { public void aigcJobStateGet() throws Exception { Integer jobId = new Integer(xxxx); // 非同期タスク ID AiServiceJobApi jobApi = new AiServiceJobApi(apiClient); AsyncJobResponse jobResponse = jobApi.getAsyncJob(jobId); String request_id = jobResponse.getRequestId(); String job_code = jobResponse.getCode(); String job_message = jobResponse.getMessage(); Map<String, AsyncJobData> job_data = jobResponse.getData(); String Result_string = (String) job_data.get("job").getResult(); JsonObject jsonObject = new JsonParser().parse(Result_string).getAsJsonObject(); JsonArray result_states = jsonObject.get("states").getAsJsonArray(); for (int result_idx=0; result_idx < result_states.size(); result_idx++){ JsonObject result_one = result_states.get(result_idx).getAsJsonObject(); String result_url = result_one.get("url").getAsString(); } } } -
次の表は、パラメーターを説明しています。
パラメーター
タイプ
説明
jobId
Integer
トレーニングタスクの ID。
-
次のコードブロックは、レスポンス例を示しています。
-
モデルトレーニングが進行中の場合、次のレスポンスが返されます。
{ requestId: 9a76c77d-c241-4691-8c93-fc6953fb668c code: OK message: success data: { job=AsyncJobData{ id=12746, appId='xxxxxxxxxx', state=1, message='model requesting', result="", requestId='111a6503-c2f7-4141-b17b-f8567e6a0a5f' } } } -
モデルトレーニングが完了すると、次のレスポンスが返されます。
{ requestId: 0fc513d1-5a9e-48e1-9b6f-2eca7c0b62e9 code: OK message: success data: { job=AsyncJobData{ id=12744, appId='xxxxxxxxxxx', state=2, message='success', result={ "cost_time":232.83351230621338, "model_id":"xxxxxxxxxxxx", "states":[{"code":1, "frontal":true, "message":"success", "url":"https://xxxx/train/1.jpg"}] }, requestId='83146ee3-68aa-40f7-b523-06f029e1db15' } } }
-
-
戻り値の説明
パラメーター名
説明
タイプ
requestId
リクエスト 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 (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
モデル名。デフォルトは空の文字列です。
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 ポートレートページでトークンを表示できます。
-
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); } }