Tous les produits
Search
Centre de documentation

Alibaba Cloud Model Studio:Édition vidéo 2.1

Dernière mise à jour :Oct 11, 2026

Le modèle d'édition vidéo universelle Wanxiang prend en charge les entrées multimodales (texte, image et vidéo) et offre cinq capacités principales : référence multi-images, repeinture vidéo, édition locale, extension vidéo et outpainting vidéo .

Périmètre d'application

  • Les modèles pris en charge varient selon la région. Les ressources sont isolées entre les régions. Pour consulter les modèles disponibles dans chaque région, reportez-vous à la console Model Studio.
  • Lors de l'appel, assurez-vous que votre modèle, votre URL d'endpoint et votre clé API appartiennent tous à la même région. Les appels interrégionaux échouent systématiquement.

RemarqueLes exemples de code de cette rubrique s'appliquent à la région Singapour.

Capacités principales

Référence multi-images

Présentation de la fonctionnalité : Prise en charge de 3 images de référence maximum, pouvant inclure des sujets et des arrière-plans (personnes, animaux, vêtements, scènes, etc.). Le modèle fusionne plusieurs images pour générer un contenu vidéo cohérent.

Paramètres :
  • function : Définissez cette valeur sur image_reference.
  • ref_images_url : Tableau d'URL. Fournissez de 1 à 3 images de référence.
  • obj_or_bg : Identifie chaque image comme sujet (obj) ou arrière-plan (bg). La longueur doit correspondre à celle de ref_images_url.
Prompt d'entréeImage de référence 1 (sujet de référence)Image de référence 2 (arrière-plan de référence)Vidéo générée

Dans la vidéo, une jeune fille sort des profondeurs d'une forêt ancienne et brumeuse. Ses pas sont légers et la caméra capture chacun de ses mouvements gracieux. Lorsqu'elle s'arrête pour observer les bois luxuriants qui l'entourent, un sourire de surprise et de joie illumine son visage. Cet instant, figé dans un jeu d'ombre et de lumière, immortalise sa merveilleuse rencontre avec la nature.

imageimage

Avant d'effectuer un appel, vous devez d'abord obtenir une clé API, puis configurer la clé API comme variable d'environnement (à dépublier et fusionner dans Configurer la clé API).

curl

Étape 1 : Créer une tâche pour obtenir un ID de tâche
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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"
    }
}'
Étape 2 : Récupérer le résultat à partir de l'ID de tâche

Remplacez {task_id} par la valeur task_id retournée par l'appel API précédent. L'identifiant task_id reste valide pour les requêtes pendant 24 heures. Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

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

# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see 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():
    """Create a video synthesis task and return the 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": "wanx2.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 the girl 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}")
import os
import requests
import time

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see 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():
    """Create a video synthesis task and return the 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 {
    // The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
    static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    // API keys vary by region. For more information, see 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 is not set");
        }
        COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
        // Enable HTTP keep-alive (enabled by default in JVM, but explicit setting is more reliable)
        System.setProperty("http.keepAlive", "true");
        System.setProperty("http.maxConnections", "20");
    }

    public static boolean isValidUserUrl(String urlString) {
        try {
            URL url = new URL(urlString);
            // Check if the protocol is secure
            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;
        }
    }

    // General HTTP POST request
    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);
    }

    // General HTTP GET request
    private static String httpGet(String path) throws Exception {
        HttpURLConnection conn = createConnection(path, "GET");
        return readResponse(conn);
    }

    // Create a connection (reuse connection parameters)
    private static HttpURLConnection createConnection(String path, String method) throws Exception {
        URL url = new URL(BASE_URL + path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Configure connection properties
        conn.setRequestMethod(method);
        conn.setConnectTimeout(30000);  // 30-second connection timeout
        conn.setReadTimeout(60000);     // 60-second read timeout
        conn.setInstanceFollowRedirects(true);  // Allow redirection

        // Set common headers
        for (Map.Entry<String, String> entry : COMMON_HEADERS.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }

        // Header for asynchronous tasks
        if (path.contains("video-synthesis")) {
            conn.setRequestProperty("X-DashScope-Async", "enable");
        }

        // Set content type and accept type
        conn.setRequestProperty("Accept", "application/json");

        return conn;
    }

    // Read the response (automatically handle error streams)
    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");  // Add a line feed to maintain the original format
            }
            return sb.toString();
        }
    }

    // Step 1: Create a task
    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);

        // Check if the response contains an error message
        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");
    }

    // Step 2: Poll for the result (15-second interval, no limit on retries)
    public static String pollResult(String taskId) throws Exception {
        while (true) {
            String resp = httpGet("/tasks/" + taskId);
            JSONObject responseJson = new JSONObject(resp);

            // Validate the response structure
            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(); // Print the full stack trace for debugging
        }
    }

}

Repeinture vidéo

Présentation de la fonctionnalité : Extrait la pose et les actions du sujet, la composition et les contours de mouvement, ou la structure esquissée d'une vidéo d'entrée. Elle génère ensuite une nouvelle vidéo conservant ces mêmes caractéristiques dynamiques, guidée par un prompt textuel. Il est également possible de remplacer le sujet de la vidéo originale à l'aide d'une image de référence.

Paramètres :
  • function : Définissez cette valeur sur video_repainting.

  • video_url : Obligatoire. URL de la vidéo d'entrée (format MP4, ≤ 50 Mo, ≤ 5 secondes).

  • control_condition : Obligatoire. Définit la méthode d'extraction des caractéristiques vidéo, déterminant ainsi quels éléments de la vidéo originale sont conservés dans la nouvelle vidéo.

    • posebodyface : Extrait les expressions faciales et les mouvements corporels (conserve les détails des expressions faciales).
    • posebody : Extrait uniquement les mouvements corporels, hors visage (contrôle seulement les actions du corps).
    • depth : Extrait la composition et les contours de mouvement (conserve la structure de la scène).
    • scribble : Extrait la structure esquissée (conserve les détails des contours de l'esquisse).
  • strength : Facultatif. Contrôle l'intensité de l'extraction des caractéristiques. Plage : [0,0, 1,0]. Valeur par défaut : 1,0. Une valeur élevée rapproche le résultat de la vidéo originale, tandis qu'une valeur faible offre davantage de liberté créative.

  • ref_images_url : Facultatif. Fournissez l'URL d'une image de référence pour remplacer le sujet de la vidéo d'entrée.

Prompt d'entréeVidéo d'entréeVidéo générée

La vidéo montre une voiture noire de style steampunk conduite par un gentleman, ornée d'engrenages et de tuyaux en cuivre. L'arrière-plan représente une confiserie à vapeur aux éléments rétro, créant une scène vintage et ludique.

curl

Étape 1 : Créer une tâche pour obtenir un ID de tâche
# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.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"
    }
}'
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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"
    }
}'
Étape 2 : Récupérer le résultat à partir de l'ID de tâche

Remplacez {task_id} par la valeur task_id retournée par l'appel API précédent. L'identifiant task_id reste valide pour les requêtes pendant 24 heures. Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

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

# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a video repainting task and return the 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": "wanx2.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, # For video repainting, we recommend disabling prompt rewriting.
                    "control_condition": "depth" # Optional: 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}")
import os
import requests
import time

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a video repainting task and return the 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, # For video repainting, we recommend disabling prompt rewriting.
                    "control_condition": "depth" # Optional: 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 {
    // The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
    static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    // API keys vary by region. For more information, see 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 is not set");
        }
        COMMON_HEADERS.put("Authorization", "Bearer " + API_KEY);
        System.setProperty("http.keepAlive", "true");
        System.setProperty("http.maxConnections", "20");
    }

    // General HTTP POST request
    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);
    }

    // General HTTP GET request
    private static String httpGet(String path) throws Exception {
        HttpURLConnection conn = createConnection(path, "GET");
        return readResponse(conn);
    }

    // Create a connection
    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;
    }

    // Read the response
    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();
        }
    }

    // Step 1: Create a video repainting task
    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");
    }

    // Step 2: Poll for the result
    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();
        }
    }
}

Édition locale

Présentation de la fonctionnalité : Effectue une édition précise sur des zones spécifiques d'une vidéo. Elle permet d'ajouter, supprimer ou modifier des éléments, ainsi que de remplacer des sujets ou des arrière-plans. Téléchargez une image masque pour définir la zone à éditer ; le modèle suit automatiquement la cible et intègre le contenu généré.

Paramètres :
  • function : Définissez cette valeur sur video_edit.

  • video_url : Obligatoire. URL de la vidéo d'entrée originale.

  • mask_image_url : Facultatif. À choisir entre ce paramètre et mask_video_url. Nous recommandons d'utiliser ce paramètre. Fournissez l'URL d'une image masque où la zone blanche correspond à la partie à éditer et la zone noire reste inchangée.

  • mask_frame_id : Facultatif. Utilisé avec mask_image_url pour indiquer à quelle image de la vidéo le masque correspond (par défaut, la première image).

  • mask_type : Facultatif. Spécifie le comportement de la zone d'édition :

    • tracking (par défaut) : La zone d'édition suit automatiquement la trajectoire de mouvement de l'objet cible.
    • fixed : La zone d'édition reste fixe.
  • expand_ratio : Facultatif. Efficace uniquement lorsque mask_type est défini sur tracking.

    • Fonction : Définit le ratio d'expansion vers l'extérieur de la zone masquée. Plage de valeurs : [0,0, 1,0], valeur par défaut : 0,05.
    • Description : Une valeur plus faible ajuste le masque plus étroitement à la cible. Une valeur plus élevée élargit la portée du masque.
  • ref_images_url : Facultatif. Fournissez l'URL d'une image de référence pour remplacer le contenu de la zone d'édition par celui de l'image de référence.

Prompt d'entréeVidéo d'entréeImage masque d'entréeVidéo générée

La vidéo présente un café français de style parisien où un lion en costume déguste élégamment son café. Il tient une tasse d'une main et sirote avec une expression détendue. Le café est décoré avec goût, baigné de tons doux et d'un éclairage chaleureux illuminant l'espace occupé par le lion.

mask

La zone blanche indique la zone d'édition.

curl

Étape 1 : Créer une tâche pour obtenir un ID de tâche
# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.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
    }
}'
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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
    }
}'
Étape 2 : Récupérer le résultat à partir de l'ID de tâche

Remplacez {task_id} par la valeur task_id retournée par l'appel API précédent. L'identifiant task_id reste valide pour les requêtes pendant 24 heures. Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Python

Installez les dépendances : pip install requests.

import os
import requests
import time

# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a local editing task and return the 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": "wanx2.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 # The index of the video frame corresponding to the mask
                },
                "parameters": {
                    "prompt_extend": False,
                    "mask_type": "tracking", # Tracking mode
                    "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}")
import os
import requests
import time

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a local editing task and return the 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 # The index of the video frame corresponding to the mask
                },
                "parameters": {
                    "prompt_extend": False,
                    "mask_type": "tracking", # Tracking mode
                    "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 {
    // The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
    static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    // API keys vary by region. For more information, see 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 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();
        }
    }

    // Step 1: Create a local editing task
    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");
    }

    // Step 2: Poll for the result
    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();
        }
    }
}

Extension vidéo

Présentation de la fonctionnalité : Prédit et génère du contenu continu subséquent à partir d'une image ou d'un clip vidéo d'entrée. Elle permet d'étendre la vidéo vers l'avant depuis la « première image / premier clip » ou vers l'arrière depuis la « dernière image / dernier clip ». La durée totale de la vidéo finale générée est fixée à 5 secondes.

Paramètres :
  • function : Définissez cette valeur sur video_extension.

  • prompt : Obligatoire. Décrit le contenu d'extension souhaité.

  • first_clip_url : Facultatif. Fournissez l'URL du premier clip vidéo (≤ 3 secondes). Le modèle générera le reste de la vidéo en se basant sur ce clip.

  • last_clip_url : Facultatif. Fournissez l'URL du dernier clip vidéo (≤ 3 secondes). Le modèle générera la partie précédente de la vidéo en se basant sur ce clip.

  • first_frame_url : Facultatif. Fournissez l'URL de l'image de la première frame. La vidéo sera étendue vers l'avant à partir de cette image.

  • last_frame_url : Facultatif. Fournissez l'URL de l'image de la dernière frame. La vidéo sera étendue vers l'arrière à partir de cette image.

    Remarque : Vous devez fournir au moins un des quatre paramètres suivants en entrée : first_clip_url, last_clip_url, first_frame_url ou last_frame_url.

Prompt d'entréePremier clip d'entrée (1 seconde)Vidéo générée (étendue à 5 secondes)

Un chien portant des lunettes de soleil fait du skateboard dans la rue, style cartoon 3D.

curl

Étape 1 : Créer une tâche pour obtenir un ID de tâche
# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.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
    }
}'
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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
    }
}'
Étape 2 : Récupérer le résultat à partir de l'ID de tâche

Remplacez {task_id} par la valeur task_id retournée par l'appel API précédent. L'identifiant task_id reste valide pour les requêtes pendant 24 heures. Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

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

# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a video extension task and return the 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": "wanx2.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}")
import os
import requests
import time

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID.  URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a video extension task and return the 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 {
    // The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
    static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    // API keys vary by region. For more information, see 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 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();
        }
    }

    // Step 1: Create a video extension task
    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");
    }

    // Step 2: Poll for the result
    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();
        }
    }
}

Outpainting vidéo

Présentation de la fonctionnalité : Étend le contenu vidéo vers le haut, le bas, la gauche et la droite selon un prompt et un ratio spécifiés, tout en préservant la cohérence du sujet principal et en assurant une intégration naturelle de l'arrière-plan.

Paramètres :
  • function : Définissez cette valeur sur video_outpainting.
  • video_url : Obligatoire. URL de la vidéo d'entrée originale.
  • top_scale : Facultatif. Ratio d'expansion vers le haut. Plage : [1,0, 2,0]. Valeur par défaut : 1,0 (aucune expansion).
  • bottom_scale : Facultatif. Ratio d'expansion vers le bas. Plage : [1,0, 2,0]. Valeur par défaut : 1,0.
  • left_scale : Facultatif. Ratio d'expansion vers la gauche. Plage : [1,0, 2,0]. Valeur par défaut : 1,0.
  • right_scale : Facultatif. Ratio d'expansion vers la droite. Plage : [1,0, 2,0]. Valeur par défaut : 1,0.

Exemple : Définir left_scale sur 1,5 signifie que le côté gauche du cadre sera étendu à 1,5 fois sa largeur d'origine.

Prompt d'entréeVidéo d'entréeVidéo générée

Une dame élégante joue passionnément du violon, accompagnée par un orchestre symphonique complet derrière elle.

curl

Étape 1 : Créer une tâche pour obtenir un ID de tâche
# The URL below is for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
curl --location 'https://{WorkspaceId}.cn-beijing.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": "wanx2.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
    }
}'
# The following URL is for the Singapore region. When calling, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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
    }
}'
Étape 2 : Récupérer le résultat à partir de l'ID de tâche

Remplacez {task_id} par la valeur task_id retournée par l'appel API précédent. L'identifiant task_id reste valide pour les requêtes pendant 24 heures. Remplacez {WorkspaceId} par votre véritable ID d'espace de travail.

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

# The following is the URL for the China (Beijing) region. Replace {WorkspaceId} with your Bailian workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a video outpainting task and return the 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": "wanx2.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,    # Upward expansion ratio
                    "bottom_scale": 1.5, # Downward expansion ratio
                    "left_scale": 1.5,   # Leftward expansion ratio
                    "right_scale": 1.5   # Rightward expansion ratio
                }
            },
            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}")
import os
import requests
import time

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
    """Create a video outpainting task and return the 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,    # Upward expansion ratio
                    "bottom_scale": 1.5, # Downward expansion ratio
                    "left_scale": 1.5,   # Leftward expansion ratio
                    "right_scale": 1.5   # Rightward expansion ratio
                }
            },
            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 {
    // The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/wanx-vace-api-reference
    static final String BASE_URL = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    // API keys vary by region. For more information, see 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 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();
        }
    }

    // Step 1: Create a video outpainting task
    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");
    }

    // Step 2: Poll for the result
    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();
        }
    }
}

Comment fournir des images et des vidéos

Images d'entrée

Vidéos d'entrée

Vidéos générées

  • Nombre de vidéos : 1.

  • Spécifications vidéo : Résolution totale fixe à 720P, fréquence d'images de 30 fps, format MP4 (encodage H.264).

  • Validité de l'URL vidéo : 24 heures.

  • Dimensions vidéo : Variables selon la fonctionnalité choisie.

    • Référence multi-images / Édition locale :

      • Résolution de sortie fixe à 720P.
      • Largeur et hauteur spécifiques déterminées par le paramètre de requête size.
    • Repeinture vidéo / Extension vidéo / Outpainting vidéo :

      • Si la résolution de la vidéo d'entrée est ≤ 720P : La sortie conserve la résolution d'origine.
      • Si la résolution de la vidéo d'entrée est > 720P : La sortie est réduite à 720P tout en conservant le ratio d'aspect.

Facturation et limitations de débit

  • Pour plus d'informations sur le quota gratuit et les tarifs du modèle, consultez la rubrique Tarification des modèles.

  • Pour plus d'informations sur les limites de débit du modèle, consultez la rubrique Série Wanxiang.

  • Détails de facturation :

    • Les entrées ne sont pas facturées. La facturation repose sur la durée en secondes de la vidéo générée avec succès.
    • Les appels de modèle échoués ou les erreurs de traitement n'entraînent aucun frais et ne consomment pas le quota gratuit nouvel utilisateur.
    • L'édition vidéo universelle prend également en charge les plans d'épargne.

Documentation API

Référence de l'API d'édition vidéo universelle

FAQ

Q : Combien d'images la fonctionnalité de référence multi-images prend-elle en charge au maximum ?

R : Elle accepte jusqu'à 3 images de référence. Si vous en fournissez plus de 3, seules les 3 premières seront utilisées. Nous recommandons d'utiliser un arrière-plan uni pour l'image du sujet afin de mieux le mettre en valeur, et une image d'arrière-plan ne contenant aucun sujet.

Q : Quand faut-il désactiver la réécriture de prompt pour la repeinture vidéo ?

R : Lorsque la description textuelle ne correspond pas au contenu de la vidéo d'entrée, le modèle risque de mal l'interpréter. Nous recommandons de désactiver manuellement la réécriture de prompt en définissant prompt_extend=false, et de fournir une description claire et précise de la scène dans le prompt pour améliorer la cohérence et la précision de la génération.

Q : Dans la fonctionnalité d'édition locale, quelle est la différence entre une image masque et une vidéo masque ?

R : Vous devez fournir soit mask_image_url, soit mask_video_url. Nous recommandons d'utiliser une image masque. Il suffit de spécifier la zone d'édition pour une seule image, et le système suivra automatiquement la cible.