All Products
Search
Document Center

Alibaba Cloud Model Studio:Referensi API Pengeditan video Wan2.7

Last Updated:Sep 02, 2026

Model pengeditan video Wan 2.7 menerima input multimodal (teks, gambar, dan video) untuk pengeditan berbasis instruksi dan style transfer .

Dokumen terkait: Panduan

Penerapan

Model, URL titik akhir, dan Kunci API harus berada di Wilayah yang sama. Panggilan lintas-wilayah akan gagal.

CatatanKode contoh dalam topik ini menggunakan Singapura.

PentingAlibaba Cloud Model Studio telah merilis domain khusus ruang kerja untuk wilayah China (Beijing) dan Singapura. Domain khusus baru ini memberikan performa lebih unggul dan stabilitas lebih tinggi untuk permintaan inferensi. Kami merekomendasikan migrasi ke domain baru:

  • China (Beijing): dari https://dashscope.aliyuncs.com ke https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapura: dari https://dashscope-intl.aliyuncs.com ke https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

{WorkspaceId} adalah ID ruang kerja Anda, yang dapat ditemukan pada halaman Detail Ruang Kerja di Konsol Alibaba Cloud Model Studio. Domain lama tetap berfungsi penuh.

HTTP

Tugas pengeditan video biasanya memerlukan waktu 1 hingga 5 menit. API menggunakan panggilan asinkron dengan dua langkah utama: Buat tugas → Polling hasilnya.

Langkah 1: Buat tugas

Singapura

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.

Catatan

  • Setelah tugas dibuat, gunakan task_id yang dikembalikan untuk mengkueri hasilnya. task_id berlaku selama 24 jam. Jangan membuat tugas duplikat. Sebagai gantinya, gunakan polling untuk mengambil hasilnya.
  • Untuk panduan pemula, lihat Panggil API dengan Postman atau cURL.

Parameter permintaan

Content-Type string (Wajib)

Tipe konten permintaan. Harus application/json.

Authorization string (Wajib)

Mengautentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

X-DashScope-Async string (Wajib)

Mengaktifkan pemrosesan asinkron. Permintaan HTTP hanya mendukung panggilan asinkron. Harus enable.

PentingJika header permintaan ini tidak ada, kesalahan "current user api does not support synchronous calls" akan dikembalikan.

Isi permintaan

model string (Wajib)

Nama model.

Nilai contoh: wan2.7-videoedit.

input object (Wajib)

Parameter input, termasuk prompt.

Properti

prompt string (Opsional)

Menjelaskan elemen dan fitur visual yang diinginkan dalam video yang dihasilkan.

Bahasa Mandarin dan Inggris didukung. Setiap karakter Mandarin atau huruf Inggris dihitung sebagai satu karakter. Teks yang lebih panjang akan dipotong secara otomatis.

  • wan2.7-videoedit: hingga 5.000 karakter.

Contoh nilai: Ubah pakaian karakter menjadi pakaian keren yang mencolok dan tambahkan topi berdasarkan gambar referensi.

negative_prompt string (Opsional)

Prompt negatif yang menjelaskan konten yang harus dikecualikan dari video, membantu menyempurnakan output.

Bahasa Mandarin dan Inggris didukung. Panjangnya tidak boleh melebihi 500 karakter. Teks yang lebih panjang akan dipotong secara otomatis.

Nilai contoh: low resolution, error, worst quality, low quality, disfigured, extra fingers, bad proportions.

media array (Wajib)

Daftar aset media, seperti gambar dan video, yang digunakan sebagai referensi untuk pembuatan video.

Setiap elemen dalam array adalah objek media yang berisi bidang type dan url.

Properti

type string (Wajib)

Jenis aset media. Nilai yang valid:

  • video: Wajib. Video yang akan diedit.
  • reference_image: Opsional. Gambar referensi.

Batas aset:

  • Hanya satu video yang diperbolehkan.
  • Maksimal empat gambar referensi.

url string (Wajib)

URL, data terenkripsi Base64, atau asset_id Asset Center dari aset media. Aset mencakup video dan gambar.

Video input (type=video)

URL atau asset_id Asset Center dari file video yang akan diedit.

Persyaratan video:

  • Format: MP4, MOV.
  • Durasi: 2–10 detik.
  • Resolusi: Lebar dan tinggi harus antara 240 hingga 4096 piksel.
  • Rasio aspek: 1:8 hingga 8:1.
  • Ukuran file: Maksimal 100 MB.

Format input yang didukung:

  1. URL publik:

  2. asset_id Asset Center

    • Format: ark_asset_vid_xxxxxx.
    • Anda dapat memperolehnya dari Asset Center. Pilih salah satu antara URL atau asset_id.

Gambar input (type=reference_image)

URL, data terenkripsi Base64, atau asset_id Asset Center dari gambar referensi.

Persyaratan gambar:

  • Format: JPEG, JPG, PNG (saluran alfa tidak didukung), BMP, WEBP.
  • Resolusi: Lebar dan tinggi harus antara 240 hingga 8000 piksel.
  • Rasio aspek: 1:8 hingga 8:1.
  • Ukuran file: Maksimal 20 MB.

Format input yang didukung:

  1. URL publik:

  2. String yang dikodekan Base64:

    • Format data: data:{MIME_type};base64,{base64_data}.
    • Nilai contoh: data:image/png;base64,GDU7MtCZzEbTbmRZ...... (Contoh ini dipotong untuk tujuan demonstrasi).

    Format data terenkripsi Base64

    Format: data:{MIME_type};base64,{base64_data} .

    • {base64_data}: String terenkripsi Base64 dari file gambar.
    • {MIME_type}: Jenis media gambar, yang harus sesuai dengan format file.

    Format gambar

    Jenis MIME

    JPEG

    image/jpeg

    JPG

    image/jpeg

    PNG

    image/png

    BMP

    image/bmp

    WEBP

    image/webp

  3. asset_id Asset Center

    • Format: ark_asset_img_xxxxxx.
    • Anda dapat memperolehnya dari Asset Center. Pilih salah satu antara URL, Base64, atau asset_id.

parameters object (Opsional)

Parameter untuk pemrosesan video, seperti resolusi, durasi, penulisan ulang prompt cerdas, dan watermark.

Properti

resolution string (Opsional)

Tingkat resolusi video yang dihasilkan, yang mengontrol kejernihannya (total piksel).

  • wan2.7-videoedit: Nilai yang valid adalah 720P dan 1080P. Nilai default adalah 1080P.

ratio string (Opsional)

Rasio aspek video yang dihasilkan.

Perilaku:

  • Jika Anda tidak menentukan parameter ratio, model akan menghasilkan video dengan rasio aspek yang mirip dengan video input.
  • Jika Anda menentukan parameter ratio, model akan menghasilkan video dengan ratio yang ditentukan.

Nilai yang valid:

  • 16:9
  • 9:16
  • 1:1
  • 4:3
  • 3:4

Lihat tabel di bawah ini untuk resolusi video output (lebar × tinggi) untuk rasio aspek berbeda.

Tingkat resolusi

Rasio aspek

Resolusi video output (lebar*tinggi)

720P

16:9

1280*720

9:16

720*1280

1:1

960*960

4:3

1104*832

3:4

832*1104

1080P

16:9

1920*1080

9:16

1080*1920

1:1

1440*1440

4:3

1648*1248

3:4

1248*1648

duration integer (Opsional)

Durasi video yang dihasilkan, dalam detik.

Rekomendasi: Tetapkan parameter ini hanya untuk memotong video. Untuk mempertahankan durasi yang sama dengan video input, abaikan parameter ini atau berikan nilai default 0.

Aturan penggunaan:

  • Perilaku default: Nilai default adalah 0, artinya durasi video input digunakan tanpa pemotongan.
  • Pemotongan: Saat durasi tertentu diberikan, sistem akan memotong video asli dari 0 detik hingga panjang yang ditentukan oleh durasi.
  • Rentang nilai: Bilangan bulat dalam rentang [2, 10].

audio_setting string (Opsional)

Pengaturan suara video.

  • auto (Default): Model secara cerdas menentukan audio berdasarkan prompt. Jika prompt menggambarkan suara, audio baru mungkin dihasilkan. Jika tidak, audio asli dari aset input mungkin dipertahankan.
  • origin: Memaksa mempertahankan audio asli dari video input tanpa regenerasi.

prompt_extendboolean (Opsional)

Mengaktifkan penulisan ulang prompt cerdas. Saat diaktifkan, model besar akan menulis ulang prompt input, secara signifikan meningkatkan kualitas generasi untuk prompt yang lebih pendek dengan biaya peningkatan waktu pemrosesan.

  • true: Nilai default. Mengaktifkan penulisan ulang cerdas.
  • false: Menonaktifkan penulisan ulang cerdas.

watermark boolean (Opsional)

Apakah akan menambahkan watermark. Watermark berada di pojok kanan bawah video dengan teks "AI Generated".

  • false (default)
  • true

Contoh: false.

seed integer (Opsional)

Bilangan acak seed harus berupa bilangan bulat dalam rentang [0, 2147483647].

Jika tidak ditentukan, seed acak akan dihasilkan. Seed tetap meningkatkan reproduktibilitas.

Karena generasi model bersifat probabilistik, seed yang sama tidak menjamin hasil identik.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.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
        }
    }'
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.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
        }
    }'

Parameter respons

output object

Berisi output tugas.

Properti

task_id string

ID tugas. Berlaku untuk kueri selama 24 jam.

task_status string

Status tugas.

Nilai enumerasi

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

request_id string

Identifier permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode kesalahan. Hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan.

message string

Pesan kesalahan detail. Hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan.

Respons berhasil

Simpan task_id untuk mengkueri status dan hasil tugas.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Respons kesalahan

Pembuatan tugas gagal. Lihat Kode kesalahan.

{
    "code": "InvalidApiKey",
    "message": "Invalid API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

Langkah 2: Kueri hasilnya

Singapura

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Beijing

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.

Catatan

  • Rekomendasi polling: Pembuatan video memerlukan beberapa menit. Gunakan mekanisme polling dengan interval yang masuk akal, misalnya 15 detik.
  • Transisi status tugas: PENDING → RUNNING → SUCCEEDED atau FAILED.
  • Tautan hasil: Setelah tugas berhasil, URL video yang berlaku selama 24 jam dikembalikan. Unduh dan simpan video ke penyimpanan permanen, seperti OSS.
  • task_idmasa berlaku: 24 jam. Setelah periode ini, kueri akan mengembalikan status tugas sebagai UNKNOWN.

Parameter permintaan

Header

Authorization string (Wajib)

Mengautentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

Parameter jalur

task_id string (Wajib)

ID tugas.

Kueri hasil

Ganti {task_id} dengan nilai task_id yang dikembalikan oleh panggilan API sebelumnya. task_id berlaku untuk kueri selama 24 jam, Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.

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

Parameter respons

outputobject

Berisi output tugas.

Properti

task_id string

ID tugas. Berlaku untuk kueri selama 24 jam.

task_status string

Status tugas.

Nilai enumerasi

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.
Transisi status selama polling:
  • PENDING → RUNNING → SUCCEEDED atau FAILED.
  • Status kueri awal biasanya PENDING atau RUNNING.
  • Saat status berubah menjadi SUCCEEDED, respons berisi URL video yang dihasilkan.
  • Jika statusnya FAILED, periksa pesan kesalahan dan coba ulang tugas tersebut.

submit_time string

Waktu saat tugas dikirimkan. Waktu dalam UTC+8 dan formatnya YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

Waktu saat tugas dieksekusi. Waktu dalam UTC+8 dan formatnya YYYY-MM-DD HH:mm:ss.SSS.

end_time string

Waktu saat tugas selesai. Waktu dalam UTC+8 dan formatnya YYYY-MM-DD HH:mm:ss.SSS.

video_url string

URL video yang dihasilkan. Hanya dikembalikan saat task_status bernilai SUCCEEDED.

Berlaku selama 24 jam. Video dalam format MP4 dengan enkode H.264.

orig_prompt string

Prompt input asli, sesuai dengan parameter permintaan prompt.

code string

Kode kesalahan. Hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan.

message string

Pesan kesalahan detail. Hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan.

usage object

Statistik penggunaan untuk penagihan. Hanya ditagih untuk tugas yang berhasil.

Properti

input_video_duration float

Durasi video input, dalam detik.

output_video_duration float

Durasi video output, dalam detik.

duration float

Total durasi video, yang digunakan untuk penagihan.

Rumus penagihan: duration=input_video_duration+output_video_duration.

SR integer

Tingkat resolusi video output. Nilai contoh: 720.

video_count integer

Jumlah video yang dihasilkan. Nilai ini tetap 1.

request_id string

Identifier permintaan unik untuk pelacakan dan troubleshooting.

Tugas berhasil

URL video hanya berlaku selama 24 jam, lalu secara otomatis dihapus. Segera simpan video yang dihasilkan.

{
    "request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
    "output": {
        "task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2026-04-03 00:08:03.576",
        "scheduled_time": "2026-04-03 00:08:13.408",
        "end_time": "2026-04-03 00:11:57.286",
        "orig_prompt": "Ganti pakaian anak perempuan di video dengan pakaian dari gambar",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?xxxx"
    },
    "usage": {
        "duration": 10.04,
        "input_video_duration": 5.02,
        "output_video_duration": 5.02,
        "video_count": 1,
        "SR": 720
    }
}

Tugas gagal

Saat tugas gagal, task_status bernilai FAILED dengan kode dan pesan kesalahan. Lihat Kode kesalahan.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size is not match xxxxxx"
    }
}

Kueri kedaluwarsa

task_id berlaku selama 24 jam. Setelah periode ini, kueri akan mengembalikan kesalahan berikut.

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

DashScope SDK

Nama parameter dalam SDK sebagian besar konsisten dengan API HTTP, tetapi struktur parameternya mengikuti konvensi masing-masing bahasa.

Pengeditan video biasanya memerlukan waktu 1 hingga 5 menit. SDK menangani proses panggilan HTTP asinkron secara internal, mendukung panggilan sinkron maupun asinkron.

Waktu pemrosesan aktual bergantung pada jumlah tugas dalam antrian dan status layanan. Tunggu hingga hasil selesai.

SDK Python

PentingPastikan Anda menggunakan SDK Python DashScope versi 1.25.16 atau lebih baru.

Menggunakan versi lama mungkin memicu kesalahan seperti "url error, please check url!". Lihat Instal SDK untuk memperbarui versi Anda.

Tetapkan base_http_api_url berdasarkan wilayah layanan:

Singapura

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

China (Beijing)

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.

Panggilan sinkron

Contoh permintaan
import base64
import mimetypes
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
import os

# URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Jika variabel lingkungan DASHSCOPE_API_KEY belum disetel, masukkan Kunci API Model Studio Anda di sini: api_key="sk-xxx"
# Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# Format: data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("Format gambar tidak didukung atau tidak dikenali.")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    return f"data:{mime_type};base64,{encoded_string}"

# Parameter reference_image_url mendukung tiga metode input berikut.

# Metode 1: Gunakan URL publik gambar.
reference_image_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"

# Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
# Format: file:// + jalur file
# Contoh (jalur absolut):
# reference_image_url = "file://" + "/path/to/image.png"     # Linux/macOS
# reference_image_url = "file://" + "C:/path/to/image.png"    # Windows
# Contoh (jalur relatif):
# reference_image_url = "file://" + "./image.png"             # Relatif terhadap lokasi skrip saat ini.

# Metode 3: String Base64 terenkripsi.
# reference_image_url = encode_file("/path/to/image.png")

def sample_sync_call_videoedit():
    # Panggil API secara sinkron untuk langsung menerima hasilnya.
    print('Please wait...')
    rsp = VideoSynthesis.call(
        api_key=api_key,
        model='wan2.7-videoedit',
        prompt='Replace the clothes of the girl 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": reference_image_url
            }
        ],
        resolution='720P',
        prompt_extend=True,
        watermark=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_videoedit()
Contoh respons

video_url berlaku selama 24 jam. Segera unduh video tersebut.

{
    "status_code": 200,
    "request_id": "d6c3c865-34e9-98a9-a53d-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "1de7c853-755a-454a-91bc-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxxx",
        "submit_time": "2026-04-10 17:16:30.821",
        "scheduled_time": "2026-04-10 17:16:46.379",
        "end_time": "2026-04-10 17:24:59.352",
        "orig_prompt": "Ganti pakaian gadis dalam video dengan pakaian dari gambar."
    },
    "usage": {
        "video_count": 1,
        "video_duration": 0,
        "video_ratio": "",
        "duration": 10.08,
        "input_video_duration": 5.04,
        "output_video_duration": 5.04,
        "SR": 720
    }
}

Panggilan asinkron

Contoh permintaan
import base64
import mimetypes
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
import os

# URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Jika variabel lingkungan DASHSCOPE_API_KEY belum disetel, masukkan Kunci API Model Studio Anda di sini: api_key="sk-xxx"
# Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

# Format: data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
    mime_type, _ = mimetypes.guess_type(file_path)
    if not mime_type or not mime_type.startswith("image/"):
        raise ValueError("Format gambar tidak didukung atau tidak dikenali.")
    with open(file_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
    return f"data:{mime_type};base64,{encoded_string}"

# Parameter reference_image_url mendukung tiga metode input berikut.

# Metode 1: Gunakan URL publik gambar.
reference_image_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"

# Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
# Format: file:// + jalur file
# Contoh (jalur absolut):
# reference_image_url = "file://" + "/path/to/image.png"     # Linux/macOS
# reference_image_url = "file://" + "C:/path/to/image.png"    # Windows
# Contoh (jalur relatif):
# reference_image_url = "file://" + "./image.png"             # Relatif terhadap lokasi skrip saat ini.

# Metode 3: String Base64 terenkripsi.
# reference_image_url = encode_file("/path/to/image.png")

def sample_async_call_videoedit():
    # Panggil API asinkron, yang mengembalikan informasi tugas.
    # Anda kemudian dapat memeriksa status tugas menggunakan ID tugas yang dikembalikan.
    rsp = VideoSynthesis.async_call(
        api_key=api_key,
        model='wan2.7-videoedit',
        prompt='Replace the clothes of the girl 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": reference_image_url
            }
        ],
        resolution='720P',
        prompt_extend=True,
        watermark=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))

    # Dapatkan informasi tugas, termasuk status tugas.
    status = VideoSynthesis.fetch(task=rsp, api_key=api_key)
    if status.status_code == HTTPStatus.OK:
        print(status.output.task_status)  # Periksa status tugas.
    else:
        print('Failed, status_code: %s, code: %s, message: %s' %
              (status.status_code, status.code, status.message))

    # Tunggu hingga tugas selesai. Metode ini melakukan polling secara berkala hingga tugas selesai.
    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_videoedit()
Contoh respons
  1. Respons pembuatan tugas
{
    "status_code": 200,
    "request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
    "code": "",
    "message": "",
    "output": {
        "task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
        "task_status": "PENDING",
        "video_url": ""
    },
    "usage": null
}
  1. Respons kueri tugas

    video_url berlaku selama 24 jam. Segera unduh video tersebut.

{
    "status_code": 200,
    "request_id": "d6c3c865-34e9-98a9-a53d-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "1de7c853-755a-454a-91bc-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxxx",
        "submit_time": "2026-04-10 17:16:30.821",
        "scheduled_time": "2026-04-10 17:16:46.379",
        "end_time": "2026-04-10 17:24:59.352",
        "orig_prompt": "Ganti pakaian perempuan di dalam video dengan pakaian dari gambar."
    },
    "usage": {
        "video_count": 1,
        "video_duration": 0,
        "video_ratio": "",
        "duration": 10.08,
        "input_video_duration": 5.04,
        "output_video_duration": 5.04,
        "SR": 720
    }
}

SDK Java

PentingPastikan Anda menggunakan SDK Java DashScope versi 2.22.14 atau lebih baru.

Menggunakan versi lama mungkin memicu kesalahan seperti "url error, please check url!". Lihat Instal SDK untuk memperbarui versi Anda.

Tetapkan Constants.baseHttpApiUrl berdasarkan wilayah layanan:

Singapura

Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

China (Beijing)

Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";

Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.

Panggilan sinkron

Contoh permintaan
// Copyright (c) Alibaba, Inc. and its affiliates.

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.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class VideoEdit {

    static {
        // URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika variabel lingkungan DASHSCOPE_API_KEY tidak disetel, masukkan Kunci API Model Studio Anda di sini: apiKey="sk-xxx"
    // Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // Parameter referenceImageUrl mendukung tiga metode input berikut.

    // Metode 1: Gunakan URL publik gambar.
    static String referenceImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png";

    // Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
    // Format: file:// + jalur file
    // Contoh (jalur absolut):
    // static String referenceImageUrl = "file://" + "/path/to/image.png";     // Linux/macOS
    // static String referenceImageUrl = "file://" + "C:/path/to/image.png";   // Windows
    // Contoh (jalur relatif):
    // static String referenceImageUrl = "file://" + "./image.png";             // Relatif terhadap direktori eksekusi saat ini.

    // Metode 3: Gunakan enkode Base64.
    // static String referenceImageUrl = encodeFile("/path/to/image.png");

    // Formatnya adalah data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("File does not exist: " + filePath);
        }
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot detect file type: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("Unsupported or unrecognized image format.");
        }
        byte[] fileBytes = null;
        try {
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read file content: " + filePath);
        }
        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void videoEdit() throws ApiException, NoApiKeyException, InputRequiredException {
        VideoSynthesis vs = new VideoSynthesis();
        List<VideoSynthesisParam.Media> media = new ArrayList<VideoSynthesisParam.Media>(){{
            add(VideoSynthesisParam.Media.builder()
                    .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4")
                    .type("video")
                    .build());
            add(VideoSynthesisParam.Media.builder()
                    .url(referenceImageUrl)
                    .type("reference_image")
                    .build());
        }};
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("resolution", "720P");
        parameters.put("prompt_extend", true);
        parameters.put("watermark", true);

        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.7-videoedit")
                        .prompt("Replace the clothes of the girl in the video with the clothes from the image.")
                        .media(media)
                        .parameters(parameters)
                        .build();
        System.out.println("Please wait...");
        VideoSynthesisResult result = vs.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            videoEdit();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
Contoh respons

video_url berlaku selama 24 jam. Segera unduh video tersebut.

{
    "request_id": "0a15ad3c-cde7-9f7e-b8d2-xxxxxx",
    "output": {
        "task_id": "0025d1e1-009a-4f53-9c27-xxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
        "orig_prompt": "Replace the clothes of the girl in the video with the clothes from the image.",
        "submit_time": "2026-04-10 17:21:01.719",
        "scheduled_time": "2026-04-10 17:21:13.182",
        "end_time": "2026-04-10 17:31:41.286"
    },
    "usage": {
        "video_count": 1,
        "duration": 10,08,
        "input_video_duration": 5,04,
        "output_video_duration": 5,04,
        "SR": "720"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Panggilan asinkron

Contoh permintaan
// Copyright (c) Alibaba, Inc. and its affiliates.

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.aigc.videosynthesis.VideoSynthesisListResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class VideoEdit {

    static {
        // URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika variabel lingkungan DASHSCOPE_API_KEY tidak disetel, masukkan Kunci API Model Studio Anda di sini: apiKey="sk-xxx"
    // Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    // Parameter referenceImageUrl mendukung tiga metode input berikut.

    // Metode 1: Gunakan URL publik gambar.
    static String referenceImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png";

    // Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
    // Format: file:// + jalur file
    // Contoh (jalur absolut):
    // static String referenceImageUrl = "file://" + "/path/to/image.png";     # Linux/macOS
    // static String referenceImageUrl = "file://" + "C:/path/to/image.png";   # Windows
    // Contoh (jalur relatif):
    // static String referenceImageUrl = "file://" + "./image.png";             # Relatif terhadap direktori eksekusi saat ini.

    // Metode 3: Gunakan enkode Base64.
    // static String referenceImageUrl = encodeFile("/path/to/image.png");

    // Formatnya adalah data:{MIME_type};base64,{base64_data}
    public static String encodeFile(String filePath) {
        Path path = Paths.get(filePath);
        if (!Files.exists(path)) {
            throw new IllegalArgumentException("File does not exist: " + filePath);
        }
        String mimeType = null;
        try {
            mimeType = Files.probeContentType(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot detect file type: " + filePath);
        }
        if (mimeType == null || !mimeType.startsWith("image/")) {
            throw new IllegalArgumentException("Unsupported or unrecognized image format.");
        }
        byte[] fileBytes = null;
        try {
            fileBytes = Files.readAllBytes(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read file content: " + filePath);
        }
        String encodedString = Base64.getEncoder().encodeToString(fileBytes);
        return "data:" + mimeType + ";base64," + encodedString;
    }

    public static void videoEdit() throws ApiException, NoApiKeyException, InputRequiredException {
        VideoSynthesis vs = new VideoSynthesis();
        List<VideoSynthesisParam.Media> media = new ArrayList<VideoSynthesisParam.Media>(){{
            add(VideoSynthesisParam.Media.builder()
                    .url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4")
                    .type("video")
                    .build());
            add(VideoSynthesisParam.Media.builder()
                    .url(referenceImageUrl)
                    .type("reference_image")
                    .build());
        }};
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("resolution", "720P");
        parameters.put("prompt_extend", true);
        parameters.put("watermark", true);

        VideoSynthesisParam param =
                VideoSynthesisParam.builder()
                        .apiKey(apiKey)
                        .model("wan2.7-videoedit")
                        .prompt("Replace the clothes of the girl in the video with the clothes from the image.")
                        .media(media)
                        .parameters(parameters)
                        .build();

        // Lakukan panggilan asinkron.
        VideoSynthesisResult task = vs.asyncCall(param);
        System.out.println(JsonUtils.toJson(task));
        System.out.println("Please wait...");

        // Tunggu hingga tugas selesai dan ambil hasil akhirnya.
        VideoSynthesisResult result = vs.wait(task, apiKey);
        System.out.println(JsonUtils.toJson(result));
    }

    // Ambil daftar tugas.
    public static void listTask() throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        param.setApiKey(apiKey);
        VideoSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    // Ambil hasil satu tugas.
    public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        // apiKey bisa null jika variabel lingkungan DASHSCOPE_API_KEY telah disetel.
        VideoSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args) {
        try {
            videoEdit();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
Contoh respons
  1. Respons pembuatan tugas
{
    "request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
    "output": {
        "task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
        "task_status": "PENDING",
        "video_url": ""
    },
    "usage": null,
    "status_code": 200,
    "code": "",
    "message": ""
}
  1. Respons kueri tugas

    video_url berlaku selama 24 jam. Segera unduh video tersebut.

{
    "request_id": "0a15ad3c-cde7-9f7e-b8d2-xxxxxx",
    "output": {
        "task_id": "0025d1e1-009a-4f53-9c27-xxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
        "orig_prompt": "Replace the clothes of the girl in the video with the clothes from the image.",
        "submit_time": "2026-04-10 17:21:01.719",
        "scheduled_time": "2026-04-10 17:21:13.182",
        "end_time": "2026-04-10 17:31:41.286"
    },
    "usage": {
        "video_count": 1,
        "duration": 10,08,
        "input_video_duration": 5,04,
        "output_video_duration": 5,04,
        "SR": "720"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Kode kesalahan

Jika panggilan model gagal, lihat Kode kesalahan untuk troubleshooting.