QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Edição geral de vídeo

Repintar, estender e editar

Tradução:wan2.7](/api-reference/video-generation/wan27-video-editing/create-task), wan2.1

Wan 2.7 Edição de vídeo

Edita vídeos até 1080P usando avisos de texto e imagens de referência opcionais -- mudar estilos, substituir objetos, ou transferir conteúdo de imagens de referência para o vídeo fonte. Usa um único modelo unificado sem function parâmetro.

Antes de executar os exemplos SDK abaixo, certifique-se de que seu DashScope SDK está atualizado: Python 1.25.16 Ou depois, Java. 2.22.14 Ou mais tarde.

Parâmetros (wan2.7)

Exemplo: mudar o estilo de vídeo

curl

 Passo 1: Criar uma tarefa

```bash
curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
  -H 'X-DashScope-Async: enable' \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "wan2.7-videoedit",
  "input": {
    "prompt": "Convert the entire scene to a claymation style",
    "media": [
      {
        "type": "video",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/ldnfdf/wan2.7-videoedit-style-change.mp4"
      }
    ]
  },
  "parameters": {
    "resolution": "720P",
    "prompt_extend": true,
    "watermark": true
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET 'https://maas.qwencloudapi.com/api/v1/tasks/{task_id}' \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python

```python
import os
import time
import requests

API_KEY = os.environ.get("DASHSCOPE_API_KEY")
BASE_URL = "https://maas.qwencloudapi.com/api/v1"

# Step 1: Submit the task
response = requests.post(
  f"{BASE_URL}/services/aigc/video-generation/video-synthesis",
  headers={
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
    "X-DashScope-Async": "enable",
  },
  json={
    "model": "wan2.7-videoedit",
    "input": {
      "prompt": "Convert the entire scene to a claymation style",
      "media": [
        {
          "type": "video",
          "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/ldnfdf/wan2.7-videoedit-style-change.mp4",
        }
      ],
    },
    "parameters": {
      "resolution": "720P",
      "prompt_extend": True,
      "watermark": True,
    },
  },
)
task_id = response.json()["output"]["task_id"]
print(f"Task submitted: {task_id}")

# Step 2: Poll for the result
while True:
  status_resp = requests.get(
    f"{BASE_URL}/tasks/{task_id}",
    headers={"Authorization": f"Bearer {API_KEY}"},
  )
  status = status_resp.json()["output"]["task_status"]
  if status == "SUCCEEDED":
    print(f"Video ready: {status_resp.json()['output']['video_url']}")
    break
  elif status == "FAILED":
    print(f"Failed: {status_resp.json()['output'].get('message')}")
    break
  print(f"Status: {status} -- waiting 10s...")
  time.sleep(10)
```

Exemplo: Edit with referencial image

Substituir objetos em um vídeo usando uma imagem de referência:

curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
  -H 'X-DashScope-Async: enable' \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "wan2.7-videoedit",
  "input": {
    "prompt": "Replace the girl'\''s clothes in the video with the clothes from the image",
    "media": [
      {
        "type": "video",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4"
      },
      {
        "type": "reference_image",
        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"
      }
    ]
  },
  "parameters": {
    "resolution": "720P",
    "prompt_extend": true,
    "watermark": true
  }
}'

Wan 2.1 Edição de vídeo

O wan2.1-vace-plus O modelo suporta 5 funções de edição especializadas, cada uma selecionada através do function parâmetro.

Capacidades principais.

Referência de multi-imagem

Descrição: Suporta até 3 imagens de referência, incluindo assuntos e fundos (pessoas, animais, roupas, cenas). O modelo funde as imagens para gerar conteúdo de vídeo coerente.

** Configurações do parâmetro:**

<table style={{width: "100%", borderCollapse: "separate", borderSpacing: "8px 0", tableLayout: "fixed"}}> <tr> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>? Prompt de entrada ?</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>**Input referência imagem 1 (sujeito a referência)</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>Input referência imagem 2 (referência de fundo)</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}> Vídeo de saída **</th> </tr>

<tr> <td style={{verticalAlign: "top"}}> No vídeo, uma garota sai das profundezas de uma floresta antiga e enevoada. Seus passos são leves, e a câmera a captura a cada momento gracioso. Quando ela para e olha em volta para as árvores exuberantes, um sorriso de surpresa e alegria floresce em seu rosto. Esta cena, congelada em um momento de luz e sombra entrelaçadas, registra seu maravilhoso encontro com a natureza. </td>

<td style={{verticalAlign: "top"}}>
  ![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/1007461571/p955656.png)
</td>

<td style={{verticalAlign: "top"}}>
  ![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/1007461571/p955657.png)
</td>

<td style={{verticalAlign: "top"}}>
  [Vídeo de saída] (https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/en-US/20250704/agazky/20250506150137950398164_52_29_29.mp4)
</td>

</tr> </table>

Antes de chamar a API, [obtenha uma chave de API] (/api-reference/preparation/api-key). Então [defina sua chave API como uma variável de ambiente] (/api-reference/preparation/api-key).

curl

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wan2.1-vace-plus",
  "input": {
    "function": "image_reference",
    "prompt": "In the video, a girl gracefully walks out from a misty, ancient forest. Her steps are light, and the camera captures her every nimble moment. When she stops and looks around at the lush woods, a smile of surprise and joy blossoms on her face. This scene, frozen in a moment of interplay between light and shadow, records her wonderful encounter with nature.",
    "ref_images_url": [
      "http://wanx.alicdn.com/material/20250318/image_reference_2_5_16.png",
      "http://wanx.alicdn.com/material/20250318/image_reference_1_5_16.png"
    ]
  },
  "parameters": {
    "prompt_extend": true,
    "obj_or_bg": ["obj","bg"],
    "size": "1280*720"
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python

```python
import os
import requests
import time

BASE_URL = "https://maas.qwencloudapi.com/api/v1"
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 trees, a smile of surprise and joy blossoms on her face. This scene, frozen in a moment of intertwined light and shadow, records her wonderful encounter with nature.",
          "ref_images_url": [
            "http://wanx.alicdn.com/material/20250318/image_reference_2_5_16.png",
            "http://wanx.alicdn.com/material/20250318/image_reference_1_5_16.png"
          ]
        },
        "parameters": {"prompt_extend": True, "obj_or_bg": ["obj", "bg"], "size": "1280*720"}
      },
      timeout=30
    )
    resp.raise_for_status()
    return resp.json()["output"]["task_id"]
  except requests.RequestException as e:
    raise RuntimeError(f"Failed to create 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

```java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class VideoSynthesis {
  static final String BASE_URL = "https://maas.qwencloudapi.com/api/v1";
  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 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 response (automatically handle error stream)
  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 trees, a smile of surprise and joy blossoms on her face. This scene, frozen in a moment of intertwined light and shadow, records her wonderful encounter with nature.")
            .put("ref_images_url", new JSONArray()
                .put("http://wanx.alicdn.com/material/20250318/image_reference_2_5_16.png")
                .put("http://wanx.alicdn.com/material/20250318/image_reference_1_5_16.png")))
        .put("parameters", new JSONObject()
            .put("prompt_extend", true)
            .put("obj_or_bg", new JSONArray().put("obj").put("bg"))
            .put("size", "1280*720"));

    String resp = httpPost("/services/aigc/video-generation/video-synthesis", body);
    JSONObject jsonResponse = new JSONObject(resp);

    // 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 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("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
    }
  }

}
```

Vídeo repintando

Descrição: Extrai a pose e movimento do sujeito, composição e contornos de movimento, ou estrutura de esboço de um vídeo de entrada. Então combina isso com um aviso de texto para gerar um novo vídeo com as mesmas características dinâmicas. Você também pode substituir o sujeito por uma imagem de referência.

** Configurações do parâmetro:**

Prompt de entrada # Vídeo de entrada # Vídeo de saída

Ver a tabela estruturada nos quadros de referência desta página ↓

curl

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wan2.1-vace-plus",
  "input": {
    "function": "video_repainting",
    "prompt": "The video shows a black steampunk-style car driven by a gentleman. The car is decorated with gears and copper pipes. The background features a steam-powered candy factory and retro elements, creating a vintage and playful scene.",
    "video_url": "http://wanx.alicdn.com/material/20250318/video_repainting_1.mp4"
  },
  "parameters": {
    "prompt_extend": false,
    "control_condition": "depth"
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python

```python
import os
import requests
import time

BASE_URL = "https://maas.qwencloudapi.com/api/v1"
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, # We recommend disabling prompt rewriting for video repainting.
          "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 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

```java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class VideoRepainting {
  static final String BASE_URL = "https://maas.qwencloudapi.com/api/v1";
  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 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 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 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();
    }
  }
}
```

Edição local

Descrição: Realiza edição de finos grãos em áreas de vídeo especificadas. Suporta adicionar, deletar e modificar elementos, ou substituir assuntos e antecedentes. Envie uma imagem de máscara para especificar a área de edição -- o modelo automaticamente rastreia o alvo e mistura o conteúdo gerado.

** Configurações do parâmetro:**

<table style={{width: "100%", borderCollapse: "separate", borderSpacing: "8px 0", tableLayout: "fixed"}}> <tr> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>? Prompt de entrada ?</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}> Vídeo de entrada</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}> Imagem da máscara de entrada</th> <th style={{textAlign: "left", width: "25%", paddingBottom: "8px"}}>** Vídeo de saída **</th> </tr>

<tr> <td style={{verticalAlign: "top"}}> O vídeo mostra um café francês estilo parisiense onde O leão de terno. É elegantemente beber café. Segura uma xícara de café em uma mão, tomando um gole suave com uma expressão relaxada. O café é decorado com bom gosto, com tons suaves e iluminação quente iluminando a área onde o leão está. </td>

<td style={{verticalAlign: "top"}}>
  [Video de entrada] (https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/en-US/20250703/cckalc/Inpainting_src_2_new.mp4)
</td>

<td style={{verticalAlign: "top"}}>
  ![](https://help-static-aliyun-doc.aliyuncs.com/assets/img/en-US/3160651571/p955179.png) A área branca indica a área de edição.
</td>

<td style={{verticalAlign: "top"}}>
  [Vídeo de saída] (https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/en-US/20250703/egunuc/Inpainting_res_2_new.mp4)
</td>

</tr> </table>

curl

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wan2.1-vace-plus",
  "input": {
    "function": "video_edit",
    "prompt": "The video shows a Parisian-style French cafe where a lion in a suit is elegantly sipping coffee. It holds a coffee cup in one hand, taking a gentle sip with a relaxed expression. The cafe is tastefully decorated, with soft hues and warm lighting illuminating the area where the lion is.",
    "mask_image_url": "http://wanx.alicdn.com/material/20250318/video_edit_1_mask.png",
    "video_url": "http://wanx.alicdn.com/material/20250318/video_edit_2.mp4",
    "mask_frame_id": 1
  },
  "parameters": {
    "prompt_extend": false,
    "mask_type": "tracking",
    "expand_ratio": 0.05,
    "size": "1280*720"
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python

```python
import os
import requests
import time

BASE_URL = "https://maas.qwencloudapi.com/api/v1"
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 sipping coffee. It holds a coffee cup in one hand, taking a gentle sip with a relaxed expression. The cafe is tastefully decorated, with soft tones and warm lighting illuminating the area where the lion is.",
          "mask_image_url": "http://wanx.alicdn.com/material/20250318/video_edit_1_mask.png",
          "video_url": "http://wanx.alicdn.com/material/20250318/video_edit_2.mp4",
          "mask_frame_id": 1 # Frame index to which the mask corresponds
        },
        "parameters": {
          "prompt_extend": False,
          "mask_type": "tracking", # Tracking mode
          "expand_ratio": 0.05,
          "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 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

```java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class VideoRegionalEdit {
  static final String BASE_URL = "https://maas.qwencloudapi.com/api/v1";
  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 sipping coffee. It holds a coffee cup in one hand, taking a gentle sip with a relaxed expression. The cafe is tastefully decorated, with soft tones and warm lighting illuminating the area where the lion is.")
            .put("mask_image_url", "http://wanx.alicdn.com/material/20250318/video_edit_1_mask.png")
            .put("video_url", "http://wanx.alicdn.com/material/20250318/video_edit_2.mp4")
            .put("mask_frame_id", 1))
        .put("parameters", new JSONObject()
            .put("prompt_extend", false)
            .put("mask_type", "tracking")
            .put("expand_ratio", 0.05)
            .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 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();
    }
  }
}
```

Extensão de vídeo

Descrição: Prediz e gera conteúdo contínuo baseado em uma imagem de entrada ou vídeo. Suporta estender um vídeo para frente do primeiro quadro ou clipe, ou para trás do último quadro ou clipe. O vídeo gerado tem 5 segundos de duração.

** Configurações do parâmetro:**

Ver a tabela estruturada nos quadros de referência desta página ↓

curl

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wan2.1-vace-plus",
  "input": {
    "function": "video_extension",
    "prompt": "A dog wearing sunglasses is skateboarding on the street, 3D cartoon.",
    "first_clip_url": "http://wanx.alicdn.com/material/20250318/video_extension_1.mp4"
  },
  "parameters": {
    "prompt_extend": false
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python

```python
import os
import requests
import time

BASE_URL = "https://maas.qwencloudapi.com/api/v1"
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 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

```java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class VideoExtension {
  static final String BASE_URL = "https://maas.qwencloudapi.com/api/v1";
  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 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();
    }
  }
}
```

Expansão de molduras

Descrição: Expande o conteúdo do vídeo proporcionalmente em todas as direções (topo, inferior, esquerda, direita) baseado em um prompt. Mantém a continuidade do assunto de vídeo e garante uma mistura natural com o fundo.

** Configurações do parâmetro:**

Prompt de entrada # Vídeo de entrada # Vídeo de saída

Ver a tabela estruturada nos quadros de referência desta página ↓

curl

 Passo 1: Crie uma tarefa para obter a identificação da tarefa

```bash
curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/video-generation/video-synthesis' \
--header 'X-DashScope-Async: enable' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "wan2.1-vace-plus",
  "input": {
    "function": "video_outpainting",
    "prompt": "An elegant lady is passionately playing the violin, with a full symphony orchestra behind her.",
    "video_url": "http://wanx.alicdn.com/material/20250318/video_outpainting_1.mp4"
  },
  "parameters": {
    "prompt_extend": false,
    "top_scale": 1.5,
    "bottom_scale": 1.5,
    "left_scale": 1.5,
    "right_scale": 1.5
  }
}'
```

 Passo 2: Obtenha o resultado usando a identificação da tarefa

 Substituir `{task_id}` com o `task_id` O valor retornado pela chamada anterior da API.

```bash
curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
```

Python

```python
import os
import requests
import time

BASE_URL = "https://maas.qwencloudapi.com/api/v1"
API_KEY = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")

def create_task():
  """Create a video frame expansion 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 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

```java
import org.json.*;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

public class VideoOutpainting {
  static final String BASE_URL = "https://maas.qwencloudapi.com/api/v1";
  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 frame expansion 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 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 frame expansion 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();
    }
  }
}
```

Imagens e vídeos de entrada

Imagens de entrada

Vídeos de entrada

Vídeo de saída

Referência da API

FAQ

Imagens máximas para referência de múltiplas imagens?

Suporta um máximo de 3 imagens de referência. Se você fornecer mais de 3, apenas os três primeiros são usados. Para melhores resultados, use um fundo sólido para a imagem do sujeito para destacar melhor o assunto, e garantir que a imagem de fundo não contenha objetos sujeitos.

Quando devo desativar a reescrita para repintura de vídeo?

Se a descrição do texto é inconsistente com o conteúdo do vídeo de entrada, o modelo pode interpretar mal seu pedido. Neste caso, recomendamos que desativar a reescrita rápida, definindo prompt_extend=false e fornecendo uma descrição clara e específica da cena no prompt. Isso melhora a consistência e precisão.

Imagem da máscara vs vídeo da máscara na edição local

Especifique uma imagem de máscara usando mask_image_url ou um vídeo de máscara usando mask_video_url** Recomendamos usar uma imagem de máscara** porque você só precisa especificar a área de edição em um único quadro, e o sistema automaticamente rastreia o alvo.

Quadros de referência

Tabelas restauradas a partir da referência original; a ordem das colunas e os valores técnicos foram preservados.

Quadro 1

Parâmetro Tipo Obrigatório Descrição
model string Sim "wan2.7-videoedit"
input.prompt string Não Até 5.000 caracteres. Descreva a edição desejada.
input.negative_prompt string Não Até 500 caracteres. Contente em excluir.
input.media array Sim Deve incluir um.videoitem. Opcionalmente, incluir até 4reference_imageItens.
parameters.resolution string Não "720P"or"1080P"(padrão).
parameters.ratio string Não "16:9","9:16","1:1","4:3","3:4". Por padrão para a relação de entrada de vídeo.
parameters.duration inteiro Não 0= duração total de entrada (padrão).2-10= truncar vídeo de entrada.
parameters.audio_setting string Não "auto"(padrão, modelo decide) ou"origin"(Mantenha o áudio original).
parameters.prompt_extend boolean Não Predefinição:true.
parameters.watermark boolean Não Predefinição:false.

Quadro 2

Prompt de entrada Vídeo de entrada Vídeo de saída
O vídeo mostra um preto Carro estilo steampunk Dirigido por um cavalheiro, adornado com engrenagens e tubos de cobre. O fundo é uma fábrica de doces a vapor com elementos retro, criando uma cena vintage e brincalhão. Vídeo de entrada Vídeo de saída

Quadro 3

Prompt de entrada Primeiro vídeo de entrada (1 segundo) Vídeo de saída (Vídeo estendido é de 5 segundos)
ACão usando óculos escuros é skateNa rua, desenho animado 3D. Vídeo de entrada Vídeo de saída

Quadro 4

Prompt de entrada Vídeo de entrada Vídeo de saída
Uma senhora elegante está apaixonadamente tocando violino, com Uma orquestra sinfônica completa atrás dela.. Vídeo de entrada Vídeo de saída