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

Wan — Animar do primeiro e do último quadro

Enviar o primeiro e o último quadro

O Wan O modelo kf2v gera uma transição suave de vídeo a partir de uma imagem do primeiro quadro, uma imagem do último quadro e um prompt de texto.

OpenAPI

openapi: 3.1.0
info:
  title: Wan Image-to-Video (First & Last Frames) API
  description: Generate a smoothly transitioning video from a first frame image, a last frame image, and a text prompt using the Wan kf2v model.
  version: 1.0.0
servers:
  - url: https://maas.qwencloudapi.com/api/v1
    description: Singapore
security:
  - BearerAuth: []
paths:
  /services/aigc/image2video/video-synthesis:
    post:
      operationId: createI2VFirstLast
      summary: Create image-to-video task
      description: Create an image-to-video task using first and last frames.
      parameters:
        - name: X-DashScope-Async
          in: header
          required: true
          description: Must be set to `enable` for asynchronous task submission. Returns an error if not included.
          schema:
            type: string
            enum:
              - enable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/I2VFirstLastRequest"
      responses:
        "200":
          description: Task submitted successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AsyncTaskSubmitResponse"
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DashScopeErrorResponse"
      x-codeSamples:
        - lang: curl
          label: cURL - Basic
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/image2video/video-synthesis' \
              -H 'X-DashScope-Async: enable' \
              -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
              -H 'Content-Type: application/json' \
              -d '{
              "model": "wan2.2-kf2v-flash",
              "input": {
                "first_frame_url": "https://wanx.alicdn.com/material/20250318/first_frame.png",
                "last_frame_url": "https://wanx.alicdn.com/material/20250318/last_frame.png",
                "prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view."
              },
              "parameters": {
                "resolution": "480P",
                "prompt_extend": true
              }
            }'
        - lang: curl
          label: cURL - With negative prompt
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/image2video/video-synthesis' \
              -H 'X-DashScope-Async: enable' \
              -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
              -H 'Content-Type: application/json' \
              -d '{
              "model": "wan2.1-kf2v-plus",
              "input": {
                "first_frame_url": "https://wanx.alicdn.com/material/20250318/first_frame.png",
                "last_frame_url": "https://wanx.alicdn.com/material/20250318/last_frame.png",
                "prompt": "Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
                "negative_prompt": "people"
              },
              "parameters": {
                "resolution": "720P",
                "prompt_extend": true
              }
            }'
        - lang: python
          label: Python (Sync)
          source: |-
            import os
            from http import HTTPStatus
            # dashscope sdk >= 1.23.4
            from dashscope import VideoSynthesis
            import dashscope

            dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

            # Get the DashScope API key (API key) from the environment variable
            api_key = os.getenv("DASHSCOPE_API_KEY")

            # ========== Image input method (choose one) ==========
            # [Method 1] Use a public image URL
            first_frame_url = "https://wanx.alicdn.com/material/20250318/first_frame.png"
            last_frame_url = "https://wanx.alicdn.com/material/20250318/last_frame.png"

            # [Method 2] Use a local file path (file:// + file path)
            # Use an absolute path
            # first_frame_url = "file://" + "/path/to/your/first_frame.png"  # Linux/macOS
            # last_frame_url = "file://" + "C:/path/to/your/last_frame.png"  # Windows
            # Or use a relative path
            # first_frame_url = "file://" + "./first_frame.png"              # Use your actual path
            # last_frame_url = "file://" + "./last_frame.png"                # Use your actual path

            def sample_sync_call_kf2v():
              print('please wait...')
              rsp = VideoSynthesis.call(api_key=api_key,
                                          model="wan2.2-kf2v-flash",
                                          prompt="Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
                                          first_frame_url=first_frame_url,
                                          last_frame_url=last_frame_url,
                                          resolution="720P",
                                          prompt_extend=True)
              print(rsp)
              if rsp.status_code == HTTPStatus.OK:
                print(rsp.output.video_url)
              else:
                print('Failed, status_code: %s, code: %s, message: %s' %
                          (rsp.status_code, rsp.code, rsp.message))

            if __name__ == '__main__':
              sample_sync_call_kf2v()
        - lang: python
          label: Python (Async)
          source: |-
            import os
            from http import HTTPStatus
            # dashscope sdk >= 1.23.4
            from dashscope import VideoSynthesis
            import dashscope

            dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

            # Get the DashScope API key (API key) from the environment variable
            api_key = os.getenv("DASHSCOPE_API_KEY")

            # ========== Image input method (choose one) ==========
            # [Method 1] Use a public image URL
            first_frame_url = "https://wanx.alicdn.com/material/20250318/first_frame.png"
            last_frame_url = "https://wanx.alicdn.com/material/20250318/last_frame.png"

            # [Method 2] Use a local file path (file:// + file path)
            # Use an absolute path
            # first_frame_url = "file://" + "/path/to/your/first_frame.png"  # Linux/macOS
            # last_frame_url = "file://" + "C:/path/to/your/last_frame.png"  # Windows
            # Or use a relative path
            # first_frame_url = "file://" + "./first_frame.png"              # Use your actual path
            # last_frame_url = "file://" + "./last_frame.png"                # Use your actual path

            def sample_async_call_kf2v():
              print('please wait...')
              rsp = VideoSynthesis.async_call(api_key=api_key,
                              model="wan2.2-kf2v-flash",
                              prompt="Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.",
                              first_frame_url=first_frame_url,
                              last_frame_url=last_frame_url,
                              resolution="720P",
                              prompt_extend=True)
              print(rsp)
              if rsp.status_code == HTTPStatus.OK:
                print("task_id: %s" % rsp.output.task_id)
              else:
                print('Failed, status_code: %s, code: %s, message: %s' %
                          (rsp.status_code, rsp.code, rsp.message))

              # get the task information include the task status.
              status = VideoSynthesis.fetch(task=rsp, api_key=api_key)
              if status.status_code == HTTPStatus.OK:
                print(status.output.task_status)  # check the task status
              else:
                print('Failed, status_code: %s, code: %s, message: %s' %
                          (status.status_code, status.code, status.message))

              # wait the task complete, will call fetch interval, and check it's in finished status.
              rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
              print(rsp)
              if rsp.status_code == HTTPStatus.OK:
                print(rsp.output.video_url)
              else:
                print('Failed, status_code: %s, code: %s, message: %s' %
                          (rsp.status_code, rsp.code, rsp.message))

            if __name__ == '__main__':
              sample_async_call_kf2v()
        - lang: java
          label: Java (Sync)
          source: |-
            // Copyright (c) Alibaba, Inc. and its affiliates.

            // dashscope sdk >= 2.20.1
            import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
            import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
            import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
            import com.alibaba.dashscope.exception.ApiException;
            import com.alibaba.dashscope.exception.InputRequiredException;
            import com.alibaba.dashscope.exception.NoApiKeyException;
            import com.alibaba.dashscope.utils.Constants;
            import com.alibaba.dashscope.utils.JsonUtils;

            import java.util.HashMap;
            import java.util.Map;

            public class Kf2vSyncIntl {

              static {
                Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
              }

              // Get the DashScope API key (API key) from the environment variable
              static String apiKey = System.getenv("DASHSCOPE_API_KEY");

              /**
                 * Image input method (choose one):
                 *
                 * [Method 1] Public URL
                 */
              static String firstFrameUrl = "https://wanx.alicdn.com/material/20250318/first_frame.png";
              static String lastFrameUrl = "https://wanx.alicdn.com/material/20250318/last_frame.png";

                 /**
                 * [Method 2] Local file path (file:// + absolute path or file:/// + absolute path)
                 */
              // static String firstFrameUrl = "file://" + "/your/path/to/first_frame.png";  // Linux/macOS
              // static String lastFrameUrl = "file:///" + "C:/path/to/your/img.png";        // Windows

              public static void syncCall() {

                Map<String, Object> parameters = new HashMap<>();
                parameters.put("prompt_extend", true);
                parameters.put("resolution", "720P");

                VideoSynthesis videoSynthesis = new VideoSynthesis();
                VideoSynthesisParam param =
                    VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.2-kf2v-flash")
                        .prompt("Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.")
                        .firstFrameUrl(firstFrameUrl)
                        .lastFrameUrl(lastFrameUrl)
                        .parameters(parameters)
                        .build();
                VideoSynthesisResult result = null;
                try {
                  System.out.println("---sync call, please wait a moment----");
                  result = videoSynthesis.call(param);
                } catch (ApiException | NoApiKeyException e){
                  throw new RuntimeException(e.getMessage());
                } catch (InputRequiredException e) {
                  throw new RuntimeException(e);
                }
                System.out.println(JsonUtils.toJson(result));
              }

              public static void main(String[] args) {
                syncCall();
              }
            }
        - lang: java
          label: Java (Async)
          source: |-
            // Copyright (c) Alibaba, Inc. and its affiliates.

            // dashscope sdk >= 2.20.1
            import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
            import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
            import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
            import com.alibaba.dashscope.exception.ApiException;
            import com.alibaba.dashscope.exception.InputRequiredException;
            import com.alibaba.dashscope.exception.NoApiKeyException;
            import com.alibaba.dashscope.utils.Constants;
            import com.alibaba.dashscope.utils.JsonUtils;
            import java.util.HashMap;
            import java.util.Map;

            public class Kf2vAsync {

              static {
                Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
              }

              // Get the DashScope API key (API key) from the environment variable
              static String apiKey = System.getenv("DASHSCOPE_API_KEY");

              /**
                 * Image input method (choose one)
                 *
                 * [Method 1] Public URL
                 */
              static String firstFrameUrl = "https://wanx.alicdn.com/material/20250318/first_frame.png";
              static String lastFrameUrl = "https://wanx.alicdn.com/material/20250318/last_frame.png";

              /**
                 * [Method 2] Local file path (file:// + absolute path or file:/// + absolute path)
                 */
              // static String firstFrameUrl = "file://" + "/your/path/to/first_frame.png";   // Linux/macOS
              // static String lastFrameUrl = "file:///" + "C:/path/to/your/img.png";        // Windows

              public static void asyncCall(){

                // Set parameters
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("prompt_extend", true);
                parameters.put("resolution", "720P");

                VideoSynthesis videoSynthesis = new VideoSynthesis();
                VideoSynthesisParam param =
                    VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.2-kf2v-flash")
                        .prompt("Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.")
                        .firstFrameUrl(firstFrameUrl)
                        .lastFrameUrl(lastFrameUrl)
                        .parameters(parameters)
                        .build();
                VideoSynthesisResult result = null;
                try {
                  System.out.println("---async call, please wait a moment----");
                  result = videoSynthesis.asyncCall(param);
                } catch (ApiException | NoApiKeyException e){
                  throw new RuntimeException(e.getMessage());
                } catch (InputRequiredException e) {
                  throw new RuntimeException(e);
                }
                System.out.println(JsonUtils.toJson(result));

                String taskId = result.getOutput().getTaskId();

                System.out.println("taskId=" + taskId);

                try {
                  result = videoSynthesis.wait(taskId, apiKey);
                } catch (ApiException | NoApiKeyException e){
                  throw new RuntimeException(e.getMessage());
                }
                System.out.println(JsonUtils.toJson(result));
                System.out.println(JsonUtils.toJson(result.getOutput()));
              }

              public static void main(String[] args){
                asyncCall();
              }
            }
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: DashScope API Key. Create one in the [QwenCloud console](https://home.qwencloud.com/api-keys).
  schemas:
    I2VFirstLastRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: Model name.
          enum:
            - wan2.2-kf2v-flash
            - wan2.1-kf2v-plus
          example: wan2.2-kf2v-flash
        input:
          type: object
          required:
            - first_frame_url
            - last_frame_url
          description: Input data including frame images and optional prompt.
          properties:
            prompt:
              type: string
              description: Text prompt describing the desired video content. Supports Chinese and English. Maximum 800 characters; excess is auto-truncated. If the subject or scene changes between the first and last frames, describe the transition (e.g., camera movement or subject movement).
              maxLength: 800
              example: Realistic style, a small black cat looks up at the sky curiously, the camera gradually rises from eye level, and finally captures its curious gaze from a top-down view.
            negative_prompt:
              type: string
              description: Describes content you do NOT want in the video. Supports Chinese and English. Maximum 500 characters; excess is auto-truncated.
              maxLength: 500
              example: low resolution, error, worst quality, low quality, deformed, extra fingers, bad proportions
            first_frame_url:
              type: string
              description: "URL of the first frame image. The output video aspect ratio matches this image. Must be publicly accessible (HTTP or HTTPS). **Image requirements**: Format: JPEG, JPG, PNG (no alpha), BMP, or WEBP. Resolution: 240-8000 px per side. Max file size: 10 MB."
              example: https://wanx.alicdn.com/material/20250318/first_frame.png
            last_frame_url:
              type: string
              description: "URL of the last frame image. Must be publicly accessible (HTTP or HTTPS). Resolution may differ from the first frame; alignment is not required. **Image requirements**: Format: JPEG, JPG, PNG (no alpha), BMP, or WEBP. Resolution: 240-8000 px per side. Max file size: 10 MB."
              example: https://wanx.alicdn.com/material/20250318/last_frame.png
        parameters:
          $ref: "#/components/schemas/I2VFirstLastParameters"
    I2VFirstLastParameters:
      type: object
      description: Video generation parameters.
      properties:
        resolution:
          type: string
          description: "Resolution tier for the generated video. Adjusts definition (total pixels) without changing aspect ratio. The video aspect ratio matches the first frame image. **Resolution affects cost**: 1080P > 720P > 480P. Available values depend on the model: `wan2.2-kf2v-flash`: 480P, 720P, 1080P (default: 720P). `wan2.1-kf2v-plus`: 480P, 720P (default: 720P)."
          enum:
            - 480P
            - 720P
            - 1080P
          default: 720P
          example: 720P
        duration:
          type: integer
          description: Duration of the generated video in seconds. Fixed at 5; cannot be changed.
          enum:
            - 5
          default: 5
        prompt_extend:
          type: boolean
          description: "Enable prompt rewriting. When enabled, a large language model rewrites the input prompt to improve results for short prompts, but increases processing time. Default: `true`."
          default: true
        watermark:
          type: boolean
          description: 'Add an "AI-generated" watermark to the bottom-right corner of the video. Default: `false`.'
          default: false
        seed:
          type: integer
          description: "Random number seed for reproducibility. Range: [0, 2147483647]. If omitted, a random seed is used. Results may still vary due to model randomness."
          minimum: 0
          maximum: 2147483647
    AsyncTaskSubmitResponse:
      type: object
      description: Response from an asynchronous task submission.
      properties:
        request_id:
          type: string
          description: Unique request identifier for tracing and troubleshooting.
          example: 4909100c-7b5a-9f92-bfe5-xxxxxx
        output:
          type: object
          properties:
            task_id:
              type: string
              description: Task ID for polling status. Use with `GET /tasks/{task_id}`. Valid for 24 hours.
              example: 0385dc79-5ff8-4d82-bcb6-xxxxxx
            task_status:
              type: string
              description: Initial task status, typically `PENDING`.
              enum:
                - PENDING
                - RUNNING
                - SUCCEEDED
                - FAILED
                - CANCELED
                - UNKNOWN
    TaskStatusResponse:
      type: object
      description: Response from querying task status.
      properties:
        request_id:
          type: string
          description: Unique request identifier for tracing and troubleshooting.
          example: ec016349-6b14-9ad6-8009-xxxxxx
        output:
          type: object
          description: Task output information.
          properties:
            task_id:
              type: string
              description: The ID of the task.
              example: 3f21a745-9f4b-4588-b643-xxxxxx
            task_status:
              type: string
              description: "Current task status. Transitions: PENDING -> RUNNING -> SUCCEEDED or FAILED. UNKNOWN means the task does not exist or has expired."
              enum:
                - PENDING
                - RUNNING
                - SUCCEEDED
                - FAILED
                - CANCELED
                - UNKNOWN
            submit_time:
              type: string
              description: "Time when the task was submitted (UTC+8). Format: YYYY-MM-DD HH:mm:ss.SSS."
              example: 2025-04-18 10:36:58.394
            scheduled_time:
              type: string
              description: "Time when the task started running (UTC+8). Format: YYYY-MM-DD HH:mm:ss.SSS."
              example: 2025-04-18 10:37:13.802
            end_time:
              type: string
              description: "Time when the task completed (UTC+8). Format: YYYY-MM-DD HH:mm:ss.SSS."
              example: 2025-04-18 10:45:23.004
            video_url:
              type: string
              description: URL of the generated video (MP4, H.264). Returned only when `task_status` is `SUCCEEDED`. Valid for 24 hours.
              example: https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.mp4?xxxxx
            orig_prompt:
              type: string
              description: The original input prompt.
            actual_prompt:
              type: string
              description: The optimized prompt used when prompt rewriting is enabled. Not returned when prompt rewriting is disabled.
            code:
              type: string
              description: Error code. Returned only when the task fails.
            message:
              type: string
              description: Detailed error message. Returned only when the task fails.
        usage:
          type: object
          description: Usage statistics. Only returned for successful tasks.
          properties:
            video_duration:
              type: integer
              description: "Video duration in seconds. Value: 5. Billing formula: Cost = Video duration (seconds) x Unit price."
              example: 5
            video_count:
              type: integer
              description: Number of videos generated. Fixed at 1.
              example: 1
            video_ratio:
              type: string
              description: Video aspect ratio. Returned only by wan2.1 models. Fixed at `standard`.
              example: standard
            SR:
              type: integer
              description: "Video resolution tier. Returned only by wan2.2 models. Values: 480, 720, or 1080."
              enum:
                - 480
                - 720
                - 1080
              example: 480
    DashScopeErrorResponse:
      type: object
      description: DashScope API error response.
      properties:
        request_id:
          type: string
          description: Unique request identifier.
        code:
          type: string
          description: Error code (e.g., `InvalidParameter`, `InvalidApiKey`, `Throttling`).
          example: InvalidApiKey
        message:
          type: string
          description: Human-readable error message.
          example: No API-key provided.