Wanxiang 汎用ビデオ編集モデルは、マルチモーダル入力 (テキスト、画像、ビデオ) をサポートし、複数画像参照、ビデオリペインティング、局所編集、ビデオ拡張、ビデオアウトペインティングという 5 つのコア機能を提供します。
適用範囲
-
サポートされるモデルはリージョンによって異なります。リソースはリージョン間で分離されています。各リージョンでサポートされているモデルについては、Model Studio コンソールをご参照ください。
-
API を呼び出す際は、モデル、エンドポイント URL、API キーがすべて同じリージョンに属していることを確認してください。リージョンをまたいだ呼び出しは失敗します。
このトピックのサンプルコードは、シンガポールリージョンに適用されます。
コア機能
複数画像参照
機能紹介:最大 3 枚の参照画像をサポートします。これには、主題やバックグラウンド (人物、動物、衣服、シーンなど) を含めることができます。モデルは複数の画像を統合して、一貫性のあるビデオコンテンツを生成します。
パラメーター:
-
function:image_referenceに設定する必要があります。 -
ref_images_url:URL の配列です。1〜3 枚の参照画像を入力できます。 -
obj_or_bg:各画像を主題 (obj) またはバックグラウンド (bg) として識別します。長さはref_images_urlと同じでなければなりません。
|
入力プロンプト |
入力参照画像 1 (参照主題) |
入力参照画像 2 (参照バックグラウンド) |
出力ビデオ |
|
ビデオでは、霧深い古代の森の奥から一人の少女が歩いてきます。彼女の足取りは軽く、カメラは彼女の優雅な一瞬一瞬を捉えます。彼女が立ち止まり、周りの緑豊かな森を見渡すと、驚きと喜びの笑みが彼女の顔に現れます。光と影の交錯の中で捉えられたこの瞬間は、彼女と自然との素晴らしい出会いを記録しています。 |
|
|
呼び出しを行う前に、まずAPI キーを取得し、次にAPI キーを環境変数として設定する必要があります。
curl
ステップ 1:タスクを作成してタスク ID を取得
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.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 emerges from a misty, ancient forest. Her steps are light, and the camera captures her every nimble moment. When she stops to look at the lush woods around her, a smile of surprise and joy blossoms on her face. This scene, frozen in an interplay of 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 の値に置き換えます。task_id は 24 時間クエリに対して有効です。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 woods, a smile of surprise and joy appears on her face. This moment, captured in the interplay of 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"Failed to create the task: {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: {status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"Task failed: {data.get('message', 'Unknown error')}")
time.sleep(15)
except requests.RequestException as e:
print(f"Polling exception: {e}. Retrying in 15 seconds...")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"Task ID: {task_id}")
video_url = poll_result(task_id)
print(f"\nVideo generated successfully: {video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoSynthesis {
// 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
// API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 is not set");
}
COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
// HTTP キープアライブを有効にする (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("Invalid 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("Cannot get response stream. Response code: " + 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 woods, a smile of surprise and joy appears on her face. This moment, captured in the interplay of 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", "Unknown error");
throw new RuntimeException("Failed to create the task: " + errorMessage + ", Details: " + 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("The API response is missing the 'output' field: " + resp);
}
JSONObject output = responseJson.getJSONObject("output");
String status = output.getString("task_status");
System.out.println("Status: " + status);
if ("SUCCEEDED".equals(status)) {
return output.getString("video_url");
} else if ("FAILED".equals(status) || "CANCELLED".equals(status)) {
String message = output.optString("message", "Unknown error");
throw new RuntimeException("Task failed: " + message + ", Task ID: " + taskId + ", Details: " + resp);
}
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("Creating video synthesis task...");
String taskId = createTask();
System.out.println("Task created successfully. Task ID: " + taskId);
System.out.println("Polling for task result...");
String videoUrl = pollResult(taskId);
System.out.println("Video URL: " + videoUrl);
} catch (Exception e) {
System.err.println("An error occurred: " + 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:オプション。入力ビデオの主題を置き換えるために、1 枚の参照画像の URL を指定します。
|
入力プロンプト |
入力ビデオ |
出力ビデオ |
|
ビデオには、紳士が運転する黒いスチームパンクスタイルの車が映っており、歯車や銅管で飾られています。背景はレトロな要素を持つ蒸気動力のキャンディー工場で、ヴィンテージで遊び心のあるシーンを作り出しています。 |
curl
ステップ 1:タスクを作成してタスク ID を取得
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.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, adorned with gears and copper pipes. The background is a steam-powered candy factory with retro elements, creating a vintage and fun 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 の値に置き換えます。task_id は 24 時間クエリに対して有効です。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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"Failed to create the task: {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: {status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"Task failed: {data.get('message', 'Unknown error')}")
time.sleep(15)
except requests.RequestException as e:
print(f"Polling exception: {e}. Retrying in 15 seconds...")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"Task ID: {task_id}")
video_url = poll_result(task_id)
print(f"\nVideo generated successfully: {video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoRepainting {
// 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
// API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 is not set");
}
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("Cannot get response stream. Response code: " + 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", "Unknown error");
throw new RuntimeException("Failed to create the task: " + 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: " + status);
if ("SUCCEEDED".equals(status)) {
return output.getString("video_url");
} else if ("FAILED".equals(status) || "CANCELLED".equals(status)) {
throw new RuntimeException("Task failed: " + output.optString("message", "Unknown error"));
}
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("Creating video repainting task...");
String taskId = createTask();
System.out.println("Task created successfully. Task ID: " + taskId);
System.out.println("Polling for task result...");
String videoUrl = pollResult(taskId);
System.out.println("Video URL: " + videoUrl);
} catch (Exception e) {
System.err.println("An error occurred: " + 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:オプション。編集エリア内のコンテンツを参照画像の内容に置き換えるために、1 枚の参照画像の URL を指定します。
|
入力プロンプト |
入力ビデオ |
入力マスク画像 |
出力ビデオ |
|
ビデオには、パリ風のフレンチカフェで、スーツを着たライオンが優雅にコーヒーを飲んでいる様子が映っています。片手にコーヒーカップを持ち、リラックスした表情で一口飲んでいます。カフェは趣味良く装飾され、柔らかな色調と暖かい照明がライオンのいるエリアを照らしています。 |
白いエリアは編集エリアを示します。 |
curl
ステップ 1:タスクを作成してタスク ID を取得
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.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 elegantly sips 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 lion's area.",
"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 の値に置き換えます。task_id は 24 時間クエリに対して有効です。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
依存関係をインストール:pip install requests。
import os
import requests
import time
# 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 drinking coffee. It holds a coffee cup in one hand, sipping 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"Failed to create the task: {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: {status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"Task failed: {data.get('message', 'Unknown error')}")
time.sleep(15)
except requests.RequestException as e:
print(f"Polling exception: {e}. Retrying in 15 seconds...")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"Task ID: {task_id}")
video_url = poll_result(task_id)
print(f"\nVideo generated successfully: {video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoRegionalEdit {
// 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
// API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 is not set");
}
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 drinking coffee. It holds a coffee cup in one hand, sipping 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", "Unknown error");
throw new RuntimeException("Failed to create the task: " + 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: " + status);
if ("SUCCEEDED".equals(status)) return output.getString("video_url");
else if ("FAILED".equals(status) || "CANCELLED".equals(status))
throw new RuntimeException("Task failed: " + output.optString("message"));
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("Creating local editing task...");
String taskId = createTask();
System.out.println("Task created successfully. Task ID: " + taskId);
String videoUrl = pollResult(taskId);
System.out.println("Video 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 を入力できます。ビデオはこのフレームから後方に拡張されます。注:`first_clip_url`、`last_clip_url`、`first_frame_url`、`last_frame_url` の 4 つのパラメーターのうち、少なくとも 1 つを入力として提供する必要があります。
|
入力プロンプト |
入力最初のクリップ (1 秒) |
出力ビデオ (5 秒に拡張) |
|
サングラスをかけた犬が路上でスケートボードをしている、3D カートゥーン。 |
curl
ステップ 1:タスクを作成してタスク ID を取得
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.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 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 の値に置き換えます。task_id は 24 時間クエリに対して有効です。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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"Failed to create the task: {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: {status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"Task failed: {data.get('message', 'Unknown error')}")
time.sleep(15)
except requests.RequestException as e:
print(f"Polling exception: {e}. Retrying in 15 seconds...")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"Task ID: {task_id}")
video_url = poll_result(task_id)
print(f"\nVideo generated successfully: {video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoExtension {
// 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
// API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 is not set");
}
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", "Unknown error");
throw new RuntimeException("Failed to create the task: " + 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: " + status);
if ("SUCCEEDED".equals(status)) return output.getString("video_url");
else if ("FAILED".equals(status) || "CANCELLED".equals(status))
throw new RuntimeException("Task failed: " + output.optString("message"));
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("Creating video extension task...");
String taskId = createTask();
System.out.println("Task created successfully. Task ID: " + taskId);
String videoUrl = pollResult(taskId);
System.out.println("Video 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://{WorkspaceId}.ap-southeast-1.maas.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 woman passionately plays 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 の値に置き換えます。task_id は 24 時間クエリに対して有効です。
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"Python
import os
import requests
import time
# 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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"Failed to create the task: {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: {status}")
if status == "SUCCEEDED":
return data["video_url"]
elif status in ("FAILED", "CANCELLED"):
raise RuntimeError(f"Task failed: {data.get('message', 'Unknown error')}")
time.sleep(15)
except requests.RequestException as e:
print(f"Polling exception: {e}. Retrying in 15 seconds...")
time.sleep(15)
if __name__ == "__main__":
task_id = create_task()
print(f"Task ID: {task_id}")
video_url = poll_result(task_id)
print(f"\nVideo generated successfully: {video_url}")Java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class VideoOutpainting {
// 以下はシンガポールリージョンの URL です。{WorkspaceId} を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/model-studio/wanx-vace-api-reference をご参照ください。
static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
// API キーはリージョンによって異なります。詳細については、https://www.alibabacloud.com/help/ja/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 is not set");
}
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", "Unknown error");
throw new RuntimeException("Failed to create the task: " + 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: " + status);
if ("SUCCEEDED".equals(status)) return output.getString("video_url");
else if ("FAILED".equals(status) || "CANCELLED".equals(status))
throw new RuntimeException("Task failed: " + output.optString("message"));
Thread.sleep(15000);
}
}
public static void main(String[] args) {
try {
System.out.println("Creating video outpainting task...");
String taskId = createTask();
System.out.println("Task created successfully. Task ID: " + taskId);
String videoUrl = pollResult(taskId);
System.out.println("Video URL: " + videoUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
画像とビデオの入力方法
入力画像
-
画像数:選択した特徴に対応する数の画像を提供できます。
-
入力方法:
-
パブリック URL:HTTP または HTTPS プロトコルをサポートします。例:https://xxxx/xxx.png。
-
入力ビデオ
-
ビデオ数:選択した特徴に対応する数のビデオを提供できます。
-
入力方法:
-
パブリック URL:HTTP または HTTPS プロトコルをサポートします。例:https://xxxx/xxx.mp4。
-
出力ビデオ
-
ビデオ数:1。
-
ビデオ仕様:合計解像度は 720P に固定され、フレームレートは 30 fps、MP4 形式 (H.264 エンコーディング) です。
-
ビデオ URL の有効期間:24 時間。
-
ビデオのディメンション:選択した特徴によって異なります。
-
複数画像参照 / 局所編集:
-
出力解像度は 720P に固定されます。
-
具体的な幅と高さは、size リクエストパラメーターによって決まります。
-
-
ビデオリペインティング / ビデオ拡張 / ビデオアウトペインティング:
-
入力ビデオの解像度が 720P 以下の場合:出力は元の解像度を維持します。
-
入力ビデオの解像度が 720P を超える場合:出力はアスペクト比を維持したまま 720P に縮小されます。
-
-
課金とレート制限
-
モデルの無料クォータと課金レートの詳細については、「モデルの料金」をご参照ください。
-
モデルのレート制限の詳細については、「Wanxiang シリーズ」をご参照ください。
-
課金の説明:
-
入力に対しては課金されません。課金は、正常に生成されたビデオの秒単位の持続時間に基づきます。
-
モデルの呼び出しの失敗や処理エラーは料金が発生せず、新規ユーザーの無料クォータも消費しません。
-
汎用ビデオ編集は節約プランもサポートしています。
-
API ドキュメント
よくある質問
Q:複数画像参照機能は最大で何枚の画像をサポートしますか?
A:最大 3 枚の参照画像をサポートします。3 枚を超えて指定した場合、最初の 3 枚のみが入力として使用されます。主題をより際立たせるために、主題画像には単色のバックグラウンドを使用し、バックグラウンド画像には主題が含まれていないものを使用することを推奨します。
Q:ビデオリペインティングでプロンプトリライトを無効にするのはどのような場合ですか?
A:テキスト記述が入力ビデオの内容と一致しない場合、モデルが誤って解釈する可能性があります。prompt_extend=false を設定して手動でプロンプトリライトを無効にし、プロンプトでシーンを明確かつ具体的に記述して、生成の一貫性と精度を向上させることを推奨します。
Q:局所編集機能において、マスク画像とマスクビデオの違いは何ですか?
A: mask_image_url または mask_video_url のいずれかを指定する必要があります。 マスクイメージの使用を推奨します。 1 フレームの編集エリアを指定するだけで、システムが自動的にターゲットをトラックします。


