Wan 統合ビデオ編集モデルは、マルチモーダル入力(テキスト、画像、ビデオ)をサポートし、複数画像リファレンス、ビデオ再ペイント、ローカル編集、ビデオ拡張、フレーム拡張の 5 つのコア機能を提供します。
可用性
対応モデルはリージョンによって異なります。リージョン間のリソースは分離されています。API を呼び出す際は、モデル、エンドポイント URL、API キーがすべて同一リージョンに属していることを確認してください。クロスリージョン呼び出しは失敗します。
対応モデル:
国際
国際デプロイメントモードでは、アクセスポイントおよびデータストレージがシンガポールリージョンに配置され、モデル推論の計算リソースは中国本土を除く世界中で動的にスケジュールされます。
モデル | 機能 | 入力モダリティ | 出力ビデオ仕様 |
wan2.1-vace-plus | 音声なしのビデオ 複数画像リファレンス、ビデオ再ペイント、ローカル編集、ビデオ拡張、フレーム拡張 | テキスト、画像、ビデオ | 解像度オプション:720P ビデオ再生時間:最大 5 秒 定義済み仕様:30 fps、MP4(H.264 エンコーディング) |
中国本土
中国本土デプロイメントモードでは、アクセスポイントおよびデータストレージが中国 (北京) リージョンに配置され、モデル推論の計算リソースは中国本土内に制限されます。
モデル | 機能 | 入力モダリティ | 出力ビデオ仕様 |
wanx2.1-vace-plus | 音声なしのビデオ 複数画像リファレンス、ビデオ再ペイント、ローカル編集、ビデオ拡張、フレーム拡張 | テキスト、画像、ビデオ | 解像度オプション:720P ビデオ再生時間:最大 5 秒 定義済み仕様:30 fps、MP4(H.264 エンコーディング) |
このトピックのサンプルコードは、シンガポールリージョン向けです。
コア機能
複数画像リファレンス
説明:人物や背景(人物、動物、衣装、シーンなど)を含む最大 3 枚のリファレンス画像をサポートします。モデルはこれらの画像を統合して、一貫性のあるビデオコンテンツを生成します。
パラメーター設定:
function:必須。値はimage_referenceである必要があります。ref_images_url:URL の配列。1~3 枚のリファレンス画像をサポートします。obj_or_bg:各画像を「被写体(obj)」または「背景(bg)」として識別します。ref_images_url配列の長さと一致する長さの配列である必要があります。
入力プロンプト | 入力リファレンス画像 1(被写体) | 入力リファレンス画像 2(背景) | 出力ビデオ |
ビデオでは、古代の霧に包まれた森の奥から少女が歩き出てきます。その足取りは軽やかで、カメラは彼女の優雅な瞬間をすべて捉えています。少女が立ち止まり、周りの豊かな木々を見渡すと、驚きと喜びの笑顔が顔に広がります。光と影が交錯するこの一瞬のシーンは、彼女と自然との素晴らしい出会いを記録しています。 |
|
|
API を呼び出す前に、API キーを取得します。その後、API キーを環境変数として設定します。
curl
ステップ 1:タスク ID を取得するためのタスクを作成
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "wan2.1-vace-plus",
"input": {
"function": "image_reference",
"prompt": "In the video, a girl gracefully walks out from a misty, ancient forest. Her steps are light, and the camera captures her every nimble moment. When she stops and looks around at the lush woods, a smile of surprise and joy blossoms on her face. This scene, frozen in a moment of interplay between light and shadow, records her wonderful encounter with nature.",
"ref_images_url": [
"http://wanx.alicdn.com/material/20250318/image_reference_2_5_16.png",
"http://wanx.alicdn.com/material/20250318/image_reference_1_5_16.png"
]
},
"parameters": {
"prompt_extend": true,
"obj_or_bg": ["obj","bg"],
"size": "1280*720"
}
}'ステップ 2:タスク ID を使用して結果を取得
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1"
# API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
headers = {"X-DashScope-Async": "enable", "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
def create_task():
"""ビデオ合成タスクを作成し、task_id を返します"""
try:
resp = requests.post(
f"{BASE_URL}/services/aigc/video-generation/video-synthesis",
headers={
"X-DashScope-Async": "enable",
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "wan2.1-vace-plus",
"input": {
"function": "image_reference",
"prompt": "In the video, a girl walks out from the depths of an ancient, misty forest. Her steps are light, and the camera captures her every graceful moment. When she stops and looks around at the lush trees, a smile of surprise and joy blossoms on her face. This scene, frozen in a moment of intertwined light and shadow, records her wonderful encounter with nature.",
"ref_images_url": [
"http://wanx.alicdn.com/material/20250318/image_reference_2_5_16.png",
"http://wanx.alicdn.com/material/20250318/image_reference_1_5_16.png"
]
},
"parameters": {"prompt_extend": True, "obj_or_bg": ["obj", "bg"], "size": "1280*720"}
},
timeout=30
)
resp.raise_for_status()
return resp.json()["output"]["task_id"]
except requests.RequestException as e:
raise RuntimeError(f"タスクの作成に失敗しました:{e}")
def poll_result(task_id):
while True:
try:
resp = requests.get(
f"{BASE_URL}/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10
)
resp.raise_for_status()
data = resp.json()["output"]
status = data["task_status"]
print(f"ステータス:{status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"タスクが失敗しました:{data.get('message', '不明なエラー')}")
time.sleep(15)
except requests.RequestException as e:
print(f"ポーリング例外:{e}。15 秒後に再試行します…")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"タスク ID:{task_id}")
video_url = poll_result(task_id)
print(f"\nビデオが正常に生成されました:{video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoSynthesis {
// 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1";
// API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
private static final Map<String, String> COMMON_HEADERS = new HashMap<>();
static {
if (API_KEY == null || API_KEY.isEmpty()) {
throw new IllegalStateException("DASHSCOPE_API_KEY が設定されていません");
}
COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
// HTTP keep-alive を有効化(JVM ではデフォルトで有効ですが、明示的な設定の方が信頼性が高い)
System.setProperty("http.keepAlive", "true");
System.setProperty("http.maxConnections", "20");
}
public static boolean isValidUserUrl(String urlString) {
try {
URL url = new URL(urlString);
// プロトコルが安全かどうかを確認
String protocol = url.getProtocol();
if (!"https".equalsIgnoreCase(protocol) && !"http".equalsIgnoreCase(protocol)) {
return false;
}
return true;
} catch (Exception e) {
System.err.println("無効な URL:" + e.getMessage());
return false;
}
}
// 一般 HTTP POST リクエスト
private static String httpPost(String path, JSONObject body) throws Exception {
HttpURLConnection conn = createConnection(path, "POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(body.toString().getBytes("UTF-8"));
}
return readResponse(conn);
}
// 一般 HTTP GET リクエスト
private static String httpGet(String path) throws Exception {
HttpURLConnection conn = createConnection(path, "GET");
return readResponse(conn);
}
// 接続の作成(接続パラメーターを再利用)
private static HttpURLConnection createConnection(String path, String method) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 接続プロパティの設定
conn.setRequestMethod(method);
conn.setConnectTimeout(30000); // 30 秒の接続タイムアウト
conn.setReadTimeout(60000); // 60 秒の読み取りタイムアウト
conn.setInstanceFollowRedirects(true); // リダイレクトを許可
// 共通ヘッダーの設定
for (Map.Entry<String, String> entry : COMMON_HEADERS.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// 非同期タスク用のヘッダー
if (path.contains("video-synthesis")) {
conn.setRequestProperty("X-DashScope-Async", "enable");
}
// コンテンツタイプと受け入れタイプの設定
conn.setRequestProperty("Accept", "application/json");
return conn;
}
// 応答の読み取り(エラー ストリームを自動的に処理)
private static String readResponse(HttpURLConnection conn) throws IOException {
InputStream is = (conn.getResponseCode() >= 200 && conn.getResponseCode() < 400)
? conn.getInputStream()
: conn.getErrorStream();
if (is == null) {
throw new IOException("応答ストリームを取得できません。応答コード:" + conn.getResponseCode());
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n"); // 元のフォーマットを維持するために改行を追加
}
return sb.toString();
}
}
// ステップ 1:タスクの作成
public static String createTask() throws Exception {
JSONObject body = new JSONObject()
.put("model", "wan2.1-vace-plus")
.put("input", new JSONObject()
.put("function", "image_reference")
.put("prompt", "In the video, a girl walks out from the depths of an ancient, misty forest. Her steps are light, and the camera captures her every graceful moment. When she stops and looks around at the lush trees, a smile of surprise and joy blossoms on her face. This scene, frozen in a moment of intertwined light and shadow, records her wonderful encounter with nature.")
.put("ref_images_url", new JSONArray()
.put("http://wanx.alicdn.com/material/20250318/image_reference_2_5_16.png")
.put("http://wanx.alicdn.com/material/20250318/image_reference_1_5_16.png")))
.put("parameters", new JSONObject()
.put("prompt_extend", true)
.put("obj_or_bg", new JSONArray().put("obj").put("bg"))
.put("size", "1280*720"));
String resp = httpPost("/services/aigc/video-generation/video-synthesis", body);
JSONObject jsonResponse = new JSONObject(resp);
// 応答にエラーメッセージが含まれているかを確認
if (jsonResponse.has("code") && jsonResponse.getInt("code") != 200) {
String errorMessage = jsonResponse.optString("message", "不明なエラー");
throw new RuntimeException("タスクの作成に失敗しました:" + errorMessage + "、詳細:" + resp);
}
JSONObject output = jsonResponse.getJSONObject("output");
return output.getString("task_id");
}
// ステップ 2:結果のポーリング(15 秒間隔、リトライ回数に制限なし)
public static String pollResult(String taskId) throws Exception {
while (true) {
String resp = httpGet("/tasks/" + taskId);
JSONObject responseJson = new JSONObject(resp);
// 応答構造の検証
if (!responseJson.has("output")) {
throw new RuntimeException("API 応答に 'output' フィールドがありません:" + resp);
}
JSONObject output = responseJson.getJSONObject("output");
String status = output.getString("task_status");
System.out.println("ステータス:" + status);
if ("SUCCEEDED".equals(status)) {
return output.getString("video_url");
} else if ("FAILED".equals(status) || "CANCELLED".equals(status)) {
String message = output.optString("message", "不明なエラー");
throw new RuntimeException("タスクが失敗しました:" + message + "、タスク ID:" + taskId + "、詳細:" + resp);
}
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("ビデオ合成タスクを作成しています…");
String taskId = createTask();
System.out.println("タスクが正常に作成されました。タスク ID:" + taskId);
System.out.println("タスク結果をポーリングしています…");
String videoUrl = pollResult(taskId);
System.out.println("ビデオ URL:" + videoUrl);
} catch (Exception e) {
System.err.println("エラーが発生しました:" + e.getMessage());
e.printStackTrace(); // デバッグ用にスタックトレースを出力
}
}
}ビデオ再ペイント
説明:入力ビデオから被写体のポーズおよび動き、構図および動きの輪郭、またはスケッチ構造を抽出します。その後、この情報をテキストプロンプトと組み合わせて、同じ動的特徴を持つ新しいビデオを生成します。また、リファレンス画像を使用して被写体を置き換えることもできます。
パラメーター設定:
function:必須。値はvideo_repaintingである必要があります。video_url:必須。入力ビデオの URL。MP4 形式で、サイズは 50 MB 以下、再生時間は 5 秒以内である必要があります。control_condition:必須。ビデオ特徴抽出方法。元のビデオから保持する特徴を決定します:posebodyface:表情および身体の動きを抽出。表情の詳細を保持します。posebody:身体の動きのみを抽出(顔を含まない)。身体の動きのみを制御します。depth:構図および動きの輪郭を抽出。シーン構造を保持します。scribble:スケッチ構造を抽出。スケッチのエッジ詳細を保持します。
strength:任意。特徴抽出の強さを制御します。範囲:0.0~1.0。デフォルト:1.0。値が大きいほど出力が元のビデオに近くなり、小さいほど創造的な自由度が高まります。ref_images_url:任意。入力ビデオ内の被写体を置き換えるためのリファレンス画像の URL。
入力プロンプト | 入力ビデオ | 出力ビデオ |
ビデオには、ギアと銅管で装飾された黒いスチームパンク風の車が映り、紳士が運転しています。背景は、レトロな要素を取り入れた蒸気動力のキャンディ工場で、ヴィンテージで遊び心のあるシーンを演出しています。 |
curl
ステップ 1:タスク ID を取得するためのタスクを作成
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "wan2.1-vace-plus",
"input": {
"function": "video_repainting",
"prompt": "The video shows a black steampunk-style car driven by a gentleman. The car is decorated with gears and copper pipes. The background features a steam-powered candy factory and retro elements, creating a vintage and playful scene.",
"video_url": "http://wanx.alicdn.com/material/20250318/video_repainting_1.mp4"
},
"parameters": {
"prompt_extend": false,
"control_condition": "depth"
}
}'ステップ 2:タスク ID を使用して結果を取得
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1"
# API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
def create_task():
"""ビデオ再ペイントタスクを作成し、task_id を返します"""
try:
resp = requests.post(
f"{BASE_URL}/services/aigc/video-generation/video-synthesis",
headers={
"X-DashScope-Async": "enable",
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "wan2.1-vace-plus",
"input": {
"function": "video_repainting",
"prompt": "The video shows a black steampunk-style car driven by a gentleman, adorned with gears and copper pipes. The background is a steam-powered candy factory with retro elements, creating a vintage and playful scene.",
"video_url": "http://wanx.alicdn.com/material/20250318/video_repainting_1.mp4"
},
"parameters": {
"prompt_extend": False, # ビデオ再ペイントでは、プロンプトの書き換えを無効化することを推奨します。
"control_condition": "depth" # 任意:posebodyface、posebody、depth、scribble
}
},
timeout=30
)
resp.raise_for_status()
return resp.json()["output"]["task_id"]
except requests.RequestException as e:
raise RuntimeError(f"タスクの作成に失敗しました:{e}")
def poll_result(task_id):
while True:
try:
resp = requests.get(
f"{BASE_URL}/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10
)
resp.raise_for_status()
data = resp.json()["output"]
status = data["task_status"]
print(f"ステータス:{status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"タスクが失敗しました:{data.get('message', '不明なエラー')}")
time.sleep(15)
except requests.RequestException as e:
print(f"ポーリング例外:{e}。15 秒後に再試行します…")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"タスク ID:{task_id}")
video_url = poll_result(task_id)
print(f"\nビデオが正常に生成されました:{video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoRepainting {
// 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1";
// API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
private static final Map<String, String> COMMON_HEADERS = new HashMap<>();
static {
if (API_KEY == null || API_KEY.isEmpty()) {
throw new IllegalStateException("DASHSCOPE_API_KEY が設定されていません");
}
COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
System.setProperty("http.keepAlive", "true");
System.setProperty("http.maxConnections", "20");
}
// 一般 HTTP POST リクエスト
private static String httpPost(String path, JSONObject body) throws Exception {
HttpURLConnection conn = createConnection(path, "POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(body.toString().getBytes("UTF-8"));
}
return readResponse(conn);
}
// 一般 HTTP GET リクエスト
private static String httpGet(String path) throws Exception {
HttpURLConnection conn = createConnection(path, "GET");
return readResponse(conn);
}
// 接続の作成
private static HttpURLConnection createConnection(String path, String method) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(30000);
conn.setReadTimeout(60000);
conn.setInstanceFollowRedirects(true);
for (Map.Entry<String, String> entry : COMMON_HEADERS.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
if (path.contains("video-synthesis")) {
conn.setRequestProperty("X-DashScope-Async", "enable");
}
conn.setRequestProperty("Accept", "application/json");
return conn;
}
// 応答の読み取り
private static String readResponse(HttpURLConnection conn) throws IOException {
InputStream is = (conn.getResponseCode() >= 200 && conn.getResponseCode() < 400)
? conn.getInputStream()
: conn.getErrorStream();
if (is == null) throw new IOException("応答ストリームを取得できません。応答コード:" + conn.getResponseCode());
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
}
// ステップ 1:ビデオ再ペイントタスクの作成
public static String createTask() throws Exception {
JSONObject body = new JSONObject()
.put("model", "wan2.1-vace-plus")
.put("input", new JSONObject()
.put("function", "video_repainting")
.put("prompt", "The video shows a black steampunk-style car driven by a gentleman, adorned with gears and copper pipes. The background is a steam-powered candy factory with retro elements, creating a vintage and playful scene.")
.put("video_url", "http://wanx.alicdn.com/material/20250318/video_repainting_1.mp4"))
.put("parameters", new JSONObject()
.put("prompt_extend", false)
.put("control_condition", "depth"));
String resp = httpPost("/services/aigc/video-generation/video-synthesis", body);
JSONObject jsonResponse = new JSONObject(resp);
if (jsonResponse.has("code") && jsonResponse.getInt("code") != 200) {
String errorMessage = jsonResponse.optString("message", "不明なエラー");
throw new RuntimeException("タスクの作成に失敗しました:" + errorMessage);
}
return jsonResponse.getJSONObject("output").getString("task_id");
}
// ステップ 2:結果のポーリング
public static String pollResult(String taskId) throws Exception {
while (true) {
String resp = httpGet("/tasks/" + taskId);
JSONObject output = new JSONObject(resp).getJSONObject("output");
String status = output.getString("task_status");
System.out.println("ステータス:" + status);
if ("SUCCEEDED".equals(status)) {
return output.getString("video_url");
} else if ("FAILED".equals(status) || "CANCELLED".equals(status)) {
throw new RuntimeException("タスクが失敗しました:" + output.optString("message", "不明なエラー"));
}
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("ビデオ再ペイントタスクを作成しています…");
String taskId = createTask();
System.out.println("タスクが正常に作成されました。タスク ID:" + taskId);
System.out.println("タスク結果をポーリングしています…");
String videoUrl = pollResult(taskId);
System.out.println("ビデオ URL:" + videoUrl);
} catch (Exception e) {
System.err.println("エラーが発生しました:" + e.getMessage());
e.printStackTrace();
}
}
}ローカル編集
説明:指定したビデオ領域に対して細かい編集を行います。要素の追加・削除・変更、または被写体および背景の置き換えをサポートします。編集領域を指定するにはマスク画像をアップロードします。モデルは対象を自動的に追跡し、生成されたコンテンツをブレンドします。
パラメーター設定:
function:必須。値はvideo_editである必要があります。video_url:必須。元の入力ビデオの URL。mask_image_url:任意。このパラメーターまたはmask_video_urlのいずれかを指定します。このパラメーターの使用を推奨します。マスク画像の URL。マスクの白い部分が編集対象となり、黒い部分は変更されません。mask_frame_id:任意。mask_image_urlと共に使用し、マスクが対応するビデオフレームを指定します。デフォルト:最初のフレーム。mask_type:任意。編集領域の動作を指定します:tracking(デフォルト):編集領域が対象の動きの軌跡に自動的に従います。fixed:編集領域が固定位置に留まります。
expand_ratio:任意。mask_typeがtrackingの場合にのみ有効です。マスク領域を外側に拡大する比率。範囲:0.0~1.0。デフォルト:0.05。
値が小さいほど対象に密着し、大きいほどマスク領域が拡大されます。
ref_images_url:任意。リファレンス画像の URL。編集領域のコンテンツは、リファレンス画像のコンテンツに置き換えられます。
入力プロンプト | 入力ビデオ | 入力マスク画像 | 出力ビデオ |
ビデオには、スーツを着たライオンが優雅にコーヒーを飲んでいるパリスタイルのフランスカフェが映っています。ライオンは片手にコーヒーカップを持ち、リラックスした表情でそっと一口飲んでいます。カフェは洗練された装飾で、柔らかなトーンと暖かい照明がライオンのいるエリアを照らしています。 |
白い領域は編集領域を示します。 |
curl
ステップ 1:タスク ID を取得するためのタスクを作成
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "wan2.1-vace-plus",
"input": {
"function": "video_edit",
"prompt": "The video shows a Parisian-style French cafe where a lion in a suit is elegantly sipping coffee. It holds a coffee cup in one hand, taking a gentle sip with a relaxed expression. The cafe is tastefully decorated, with soft hues and warm lighting illuminating the area where the lion is.",
"mask_image_url": "http://wanx.alicdn.com/material/20250318/video_edit_1_mask.png",
"video_url": "http://wanx.alicdn.com/material/20250318/video_edit_2.mp4",
"mask_frame_id": 1
},
"parameters": {
"prompt_extend": false,
"mask_type": "tracking",
"expand_ratio": 0.05
}
}'ステップ 2:タスク ID を使用して結果を取得
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1"
# API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
def create_task():
"""ローカル編集タスクを作成し、task_id を返します"""
try:
resp = requests.post(
f"{BASE_URL}/services/aigc/video-generation/video-synthesis",
headers={
"X-DashScope-Async": "enable",
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "wan2.1-vace-plus",
"input": {
"function": "video_edit",
"prompt": "The video shows a Parisian-style French cafe where a lion in a suit is elegantly sipping coffee. It holds a coffee cup in one hand, taking a gentle sip with a relaxed expression. The cafe is tastefully decorated, with soft tones and warm lighting illuminating the area where the lion is.",
"mask_image_url": "http://wanx.alicdn.com/material/20250318/video_edit_1_mask.png",
"video_url": "http://wanx.alicdn.com/material/20250318/video_edit_2.mp4",
"mask_frame_id": 1 # マスクが対応するフレームのインデックス
},
"parameters": {
"prompt_extend": False,
"mask_type": "tracking", # トラッキングモード
"expand_ratio": 0.05
}
},
timeout=30
)
resp.raise_for_status()
return resp.json()["output"]["task_id"]
except requests.RequestException as e:
raise RuntimeError(f"タスクの作成に失敗しました:{e}")
def poll_result(task_id):
while True:
try:
resp = requests.get(
f"{BASE_URL}/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10
)
resp.raise_for_status()
data = resp.json()["output"]
status = data["task_status"]
print(f"ステータス:{status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"タスクが失敗しました:{data.get('message', '不明なエラー')}")
time.sleep(15)
except requests.RequestException as e:
print(f"ポーリング例外:{e}。15 秒後に再試行します…")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"タスク ID:{task_id}")
video_url = poll_result(task_id)
print(f"\nビデオが正常に生成されました:{video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoRegionalEdit {
// 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1";
// API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
private static final Map<String, String> COMMON_HEADERS = new HashMap<>();
static {
if (API_KEY == null || API_KEY.isEmpty()) {
throw new IllegalStateException("DASHSCOPE_API_KEY が設定されていません");
}
COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
System.setProperty("http.keepAlive", "true");
}
private static String httpPost(String path, JSONObject body) throws Exception {
HttpURLConnection conn = createConnection(path, "POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(body.toString().getBytes("UTF-8"));
}
return readResponse(conn);
}
private static String httpGet(String path) throws Exception {
HttpURLConnection conn = createConnection(path, "GET");
return readResponse(conn);
}
private static HttpURLConnection createConnection(String path, String method) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(30000);
conn.setReadTimeout(60000);
for (Map.Entry<String, String> entry : COMMON_HEADERS.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
if (path.contains("video-synthesis")) {
conn.setRequestProperty("X-DashScope-Async", "enable");
}
return conn;
}
private static String readResponse(HttpURLConnection conn) throws IOException {
InputStream is = (conn.getResponseCode() >= 200 && conn.getResponseCode() < 400) ? conn.getInputStream() : conn.getErrorStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append("\n");
return sb.toString();
}
}
// ステップ 1:ローカル編集タスクの作成
public static String createTask() throws Exception {
JSONObject body = new JSONObject()
.put("model", "wan2.1-vace-plus")
.put("input", new JSONObject()
.put("function", "video_edit")
.put("prompt", "The video shows a Parisian-style French cafe where a lion in a suit is elegantly sipping coffee. It holds a coffee cup in one hand, taking a gentle sip with a relaxed expression. The cafe is tastefully decorated, with soft tones and warm lighting illuminating the area where the lion is.")
.put("mask_image_url", "http://wanx.alicdn.com/material/20250318/video_edit_1_mask.png")
.put("video_url", "http://wanx.alicdn.com/material/20250318/video_edit_2.mp4")
.put("mask_frame_id", 1))
.put("parameters", new JSONObject()
.put("prompt_extend", false)
.put("mask_type", "tracking")
.put("expand_ratio", 0.05));
String resp = httpPost("/services/aigc/video-generation/video-synthesis", body);
JSONObject jsonResponse = new JSONObject(resp);
if (jsonResponse.has("code") && jsonResponse.getInt("code") != 200) {
String errorMessage = jsonResponse.optString("message", "不明なエラー");
throw new RuntimeException("タスクの作成に失敗しました:" + errorMessage);
}
return jsonResponse.getJSONObject("output").getString("task_id");
}
// ステップ 2:結果のポーリング
public static String pollResult(String taskId) throws Exception {
while (true) {
String resp = httpGet("/tasks/" + taskId);
JSONObject output = new JSONObject(resp).getJSONObject("output");
String status = output.getString("task_status");
System.out.println("ステータス:" + status);
if ("SUCCEEDED".equals(status)) return output.getString("video_url");
else if ("FAILED".equals(status) || "CANCELLED".equals(status))
throw new RuntimeException("タスクが失敗しました:" + output.optString("message"));
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("ローカル編集タスクを作成しています…");
String taskId = createTask();
System.out.println("タスクが正常に作成されました。タスク ID:" + taskId);
String videoUrl = pollResult(taskId);
System.out.println("ビデオ URL:" + videoUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}ビデオ拡張
説明:入力画像またはビデオクリップに基づいて、連続したコンテンツを予測および生成します。最初のフレームまたはクリップから前方へ拡張するか、最後のフレームまたはクリップから後方へ拡張することが可能です。生成されるビデオの長さは 5 秒です。
パラメーター設定:
function:必須。値はvideo_extensionである必要があります。prompt:必須。拡張したいコンテンツの説明。first_clip_url:任意。最初のビデオクリップ(3 秒以内)の URL。モデルはこのクリップに基づいて残りのビデオを生成します。last_clip_url:任意。最後のビデオクリップ(3 秒以内)の URL。モデルはこのクリップに基づいて先行するコンテンツを生成します。first_frame_url:任意。最初のフレーム画像の URL。ビデオはこのフレームから前方へ拡張されます。last_frame_url:任意。最後のフレーム画像の URL。生成はこのフレームから後方へ行われます。以下のいずれか 1 つ以上を指定してください:
first_clip_url、last_clip_url、first_frame_url、またはlast_frame_url。
入力プロンプト | 入力最初のクリップビデオ(1 秒) | 出力ビデオ(拡張ビデオは 5 秒) |
サングラスをかけた犬がスケートボードに乗っているシーン、3D カートゥーン。 |
curl
ステップ 1:タスク ID を取得するためのタスクを作成
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "wan2.1-vace-plus",
"input": {
"function": "video_extension",
"prompt": "A dog wearing sunglasses is skateboarding on the street, 3D cartoon.",
"first_clip_url": "http://wanx.alicdn.com/material/20250318/video_extension_1.mp4"
},
"parameters": {
"prompt_extend": false
}
}'ステップ 2:タスク ID を使用して結果を取得
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1"
# API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
def create_task():
"""ビデオ拡張タスクを作成し、task_id を返します"""
try:
resp = requests.post(
f"{BASE_URL}/services/aigc/video-generation/video-synthesis",
headers={
"X-DashScope-Async": "enable",
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "wan2.1-vace-plus",
"input": {
"function": "video_extension",
"prompt": "A dog wearing sunglasses is skateboarding on the street, 3D cartoon.",
"first_clip_url": "http://wanx.alicdn.com/material/20250318/video_extension_1.mp4"
},
"parameters": {
"prompt_extend": False
}
},
timeout=30
)
resp.raise_for_status()
return resp.json()["output"]["task_id"]
except requests.RequestException as e:
raise RuntimeError(f"タスクの作成に失敗しました:{e}")
def poll_result(task_id):
while True:
try:
resp = requests.get(
f"{BASE_URL}/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10
)
resp.raise_for_status()
data = resp.json()["output"]
status = data["task_status"]
print(f"ステータス:{status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"タスクが失敗しました:{data.get('message', '不明なエラー')}")
time.sleep(15)
except requests.RequestException as e:
print(f"ポーリング例外:{e}。15 秒後に再試行します…")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"タスク ID:{task_id}")
video_url = poll_result(task_id)
print(f"\nビデオが正常に生成されました:{video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoExtension {
// 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1";
// API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
private static final Map<String, String> COMMON_HEADERS = new HashMap<>();
static {
if (API_KEY == null || API_KEY.isEmpty()) {
throw new IllegalStateException("DASHSCOPE_API_KEY が設定されていません");
}
COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
System.setProperty("http.keepAlive", "true");
}
private static String httpPost(String path, JSONObject body) throws Exception {
HttpURLConnection conn = createConnection(path, "POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(body.toString().getBytes("UTF-8"));
}
return readResponse(conn);
}
private static String httpGet(String path) throws Exception {
HttpURLConnection conn = createConnection(path, "GET");
return readResponse(conn);
}
private static HttpURLConnection createConnection(String path, String method) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(30000);
conn.setReadTimeout(60000);
for (Map.Entry<String, String> entry : COMMON_HEADERS.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
if (path.contains("video-synthesis")) {
conn.setRequestProperty("X-DashScope-Async", "enable");
}
return conn;
}
private static String readResponse(HttpURLConnection conn) throws IOException {
InputStream is = (conn.getResponseCode() >= 200 && conn.getResponseCode() < 400) ? conn.getInputStream() : conn.getErrorStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append("\n");
return sb.toString();
}
}
// ステップ 1:ビデオ拡張タスクの作成
public static String createTask() throws Exception {
JSONObject body = new JSONObject()
.put("model", "wan2.1-vace-plus")
.put("input", new JSONObject()
.put("function", "video_extension")
.put("prompt", "A dog wearing sunglasses is skateboarding on the street, 3D cartoon.")
.put("first_clip_url", "http://wanx.alicdn.com/material/20250318/video_extension_1.mp4"))
.put("parameters", new JSONObject()
.put("prompt_extend", false));
String resp = httpPost("/services/aigc/video-generation/video-synthesis", body);
JSONObject jsonResponse = new JSONObject(resp);
if (jsonResponse.has("code") && jsonResponse.getInt("code") != 200) {
String errorMessage = jsonResponse.optString("message", "不明なエラー");
throw new RuntimeException("タスクの作成に失敗しました:" + errorMessage);
}
return jsonResponse.getJSONObject("output").getString("task_id");
}
// ステップ 2:結果のポーリング
public static String pollResult(String taskId) throws Exception {
while (true) {
String resp = httpGet("/tasks/" + taskId);
JSONObject output = new JSONObject(resp).getJSONObject("output");
String status = output.getString("task_status");
System.out.println("ステータス:" + status);
if ("SUCCEEDED".equals(status)) return output.getString("video_url");
else if ("FAILED".equals(status) || "CANCELLED".equals(status))
throw new RuntimeException("タスクが失敗しました:" + output.optString("message"));
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("ビデオ拡張タスクを作成しています…");
String taskId = createTask();
System.out.println("タスクが正常に作成されました。タスク ID:" + taskId);
String videoUrl = pollResult(taskId);
System.out.println("ビデオ URL:" + videoUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}フレーム拡張
説明:プロンプトに基づき、ビデオフレームのコンテンツを上下左右の全方向に比例して拡張します。ビデオの被写体の連続性を維持し、背景との自然なブレンドを保証します。
パラメーター設定:
function:必須。値はvideo_outpaintingである必要があります。video_url:必須。元の入力ビデオの URL。top_scale:任意。上方向への拡張比率。範囲:1.0~2.0。デフォルト:1.0(拡張なし)。bottom_scale:任意。下方向への拡張比率。範囲:1.0~2.0。デフォルト:1.0。left_scale:任意。左方向への拡張比率。範囲:1.0~2.0。デフォルト:1.0。right_scale:任意。右方向への拡張比率。範囲:1.0~2.0。デフォルト:1.0。
例:left_scale を 1.5 に設定すると、フレームの左側が元の幅の 1.5 倍に拡張されます。入力プロンプト | 入力ビデオ | 出力ビデオ |
洗練された女性が情熱的にヴァイオリンを演奏しており、フル・シンフォニー・オーケストラがその背後にいます。 |
curl
ステップ 1:タスク ID を取得するためのタスクを作成
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"model": "wan2.1-vace-plus",
"input": {
"function": "video_outpainting",
"prompt": "An elegant lady is passionately playing the violin, with a full symphony orchestra behind her.",
"video_url": "http://wanx.alicdn.com/material/20250318/video_outpainting_1.mp4"
},
"parameters": {
"prompt_extend": false,
"top_scale": 1.5,
"bottom_scale": 1.5,
"left_scale": 1.5,
"right_scale": 1.5
}
}'ステップ 2:タスク ID を使用して結果を取得
{task_id} を、前の API 呼び出しで返された task_id の値に置き換えます。
curl -X GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1"
# API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
def create_task():
"""ビデオフレーム拡張タスクを作成し、task_id を返します"""
try:
resp = requests.post(
f"{BASE_URL}/services/aigc/video-generation/video-synthesis",
headers={
"X-DashScope-Async": "enable",
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "wan2.1-vace-plus",
"input": {
"function": "video_outpainting",
"prompt": "An elegant lady is passionately playing the violin, with a full symphony orchestra behind her.",
"video_url": "http://wanx.alicdn.com/material/20250318/video_outpainting_1.mp4"
},
"parameters": {
"prompt_extend": False,
"top_scale": 1.5, # 上方向への拡張比率
"bottom_scale": 1.5, # 下方向への拡張比率
"left_scale": 1.5, # 左方向への拡張比率
"right_scale": 1.5 # 右方向への拡張比率
}
},
timeout=30
)
resp.raise_for_status()
return resp.json()["output"]["task_id"]
except requests.RequestException as e:
raise RuntimeError(f"タスクの作成に失敗しました:{e}")
def poll_result(task_id):
while True:
try:
resp = requests.get(
f"{BASE_URL}/tasks/{task_id}",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10
)
resp.raise_for_status()
data = resp.json()["output"]
status = data["task_status"]
print(f"ステータス:{status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"タスクが失敗しました:{data.get('message', '不明なエラー')}")
time.sleep(15)
except requests.RequestException as e:
print(f"ポーリング例外:{e}。15 秒後に再試行します…")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"タスク ID:{task_id}")
video_url = poll_result(task_id)
print(f"\nビデオが正常に生成されました:{video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoOutpainting {
// 以下はシンガポールリージョン向けの URL です。リージョンごとに URL が異なります。URL の詳細については、「https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference」をご参照ください。
static final String BASE_URL = "https://dashscope-intl.aliyuncs.com/api/v1";
// API キーはリージョンごとに異なります。API キーの取得方法については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");
private static final Map<String, String> COMMON_HEADERS = new HashMap<>();
static {
if (API_KEY == null || API_KEY.isEmpty()) {
throw new IllegalStateException("DASHSCOPE_API_KEY が設定されていません");
}
COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
System.setProperty("http.keepAlive", "true");
}
private static String httpPost(String path, JSONObject body) throws Exception {
HttpURLConnection conn = createConnection(path, "POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(body.toString().getBytes("UTF-8"));
}
return readResponse(conn);
}
private static String httpGet(String path) throws Exception {
HttpURLConnection conn = createConnection(path, "GET");
return readResponse(conn);
}
private static HttpURLConnection createConnection(String path, String method) throws Exception {
URL url = new URL(BASE_URL + path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(30000);
conn.setReadTimeout(60000);
for (Map.Entry<String, String> entry : COMMON_HEADERS.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
if (path.contains("video-synthesis")) {
conn.setRequestProperty("X-DashScope-Async", "enable");
}
return conn;
}
private static String readResponse(HttpURLConnection conn) throws IOException {
InputStream is = (conn.getResponseCode() >= 200 && conn.getResponseCode() < 400) ? conn.getInputStream() : conn.getErrorStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append("\n");
return sb.toString();
}
}
// ステップ 1:ビデオフレーム拡張タスクの作成
public static String createTask() throws Exception {
JSONObject body = new JSONObject()
.put("model", "wan2.1-vace-plus")
.put("input", new JSONObject()
.put("function", "video_outpainting")
.put("prompt", "An elegant lady is passionately playing the violin, with a full symphony orchestra behind her.")
.put("video_url", "http://wanx.alicdn.com/material/20250318/video_outpainting_1.mp4"))
.put("parameters", new JSONObject()
.put("prompt_extend", false)
.put("top_scale", 1.5)
.put("bottom_scale", 1.5)
.put("left_scale", 1.5)
.put("right_scale", 1.5));
String resp = httpPost("/services/aigc/video-generation/video-synthesis", body);
JSONObject jsonResponse = new JSONObject(resp);
if (jsonResponse.has("code") && jsonResponse.getInt("code") != 200) {
String errorMessage = jsonResponse.optString("message", "不明なエラー");
throw new RuntimeException("タスクの作成に失敗しました:" + errorMessage);
}
return jsonResponse.getJSONObject("output").getString("task_id");
}
// ステップ 2:結果のポーリング
public static String pollResult(String taskId) throws Exception {
while (true) {
String resp = httpGet("/tasks/" + taskId);
JSONObject output = new JSONObject(resp).getJSONObject("output");
String status = output.getString("task_status");
System.out.println("ステータス:" + status);
if ("SUCCEEDED".equals(status)) return output.getString("video_url");
else if ("FAILED".equals(status) || "CANCELLED".equals(status))
throw new RuntimeException("タスクが失敗しました:" + output.optString("message"));
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("ビデオフレーム拡張タスクを作成しています…");
String taskId = createTask();
System.out.println("タスクが正常に作成されました。タスク ID:" + taskId);
String videoUrl = pollResult(taskId);
System.out.println("ビデオ URL:" + videoUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}入力画像とビデオ
入力画像
画像数:選択した機能で必要な数をご参照ください。
入力方法:
パブリック URL:HTTP および HTTPS プロトコルをサポートします。例:https://xxxx/xxx.png。
入力ビデオ
ビデオ数:選択した機能で必要な数をご参照ください。
入力方法:
パブリック URL:HTTP および HTTPS プロトコルをサポートします。例:https://xxxx/xxx.mp4。
出力ビデオ
ビデオ数:1 つ。
フォーマット:MP4。解像度とディメンションについては、以下のビデオ仕様をご参照ください。
URL の有効期限:24 時間。
ディメンション:選択した機能によって異なります。
複数画像リファレンス / ローカル編集:
出力解像度は 720P に固定されます。
具体的な幅と高さは size パラメーターによって決まります。
ビデオ再ペイント / ビデオ拡張 / フレーム拡張:
入力ビデオの解像度が 720P 以下の場合、出力解像度は入力と一致します。
入力ビデオの解像度が 720P を超える場合、出力は縦横比を維持したまま 720P に縮小されます。
課金とレート制限
無料クォータと価格については、「モデル呼び出しの価格設定」をご参照ください。
レート制限については、「Wan シリーズ」をご参照ください。
課金の詳細:
API リファレンス
よくある質問
Q:複数画像リファレンス機能は最大で何枚の画像をサポートしますか?
A:最大 3 枚のリファレンス画像をサポートします。4 枚以上提供した場合、最初の 3 枚のみが使用されます。最良の結果を得るためには、被写体画像には単色の背景を使用して被写体をより際立たせ、背景画像には被写体オブジェクトが含まれていないことを確認してください。
Q:ビデオ再ペイントでプロンプトの書き換えを無効にするのはどのような場合ですか?
A:テキストの説明が入力ビデオの内容と一致しない場合、モデルがリクエストを誤解する可能性があります。この場合、prompt_extend=false を設定してプロンプトの書き換えを手動で無効にし、プロンプトで明確かつ具体的なシーンの説明を提供することを推奨します。これにより、一貫性と精度が向上します。
Q:ローカル編集機能において、マスク画像とマスクビデオの違いは何ですか?
A:mask_image_url を使用してマスク画像を指定するか、mask_video_url を使用してマスクビデオを指定します。マスク画像の使用を推奨します。なぜなら、単一のフレームで編集領域を指定するだけで、システムが自動的に対象を追跡するためです。


