From 4a61c5aeb7a2b4cb54b297d8726c9ea6c3484439 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Tue, 24 Nov 2026 19:54:28 +0800 Subject: [PATCH 1/2] feat: add video portrait, style, and retouch commands --- packages/cli/src/commands.ts | 6 + .../commands/src/commands/video/download.ts | 4 +- .../commands/src/commands/video/portrait.ts | 196 ++++ .../commands/src/commands/video/retouch.ts | 848 ++++++++++++++++++ .../src/commands/video/specialized-shared.ts | 164 ++++ packages/commands/src/commands/video/style.ts | 176 ++++ .../commands/src/commands/video/task-get.ts | 3 + packages/commands/src/index.ts | 3 + packages/commands/tests/e2e/topic-routes.ts | 21 + .../tests/e2e/video-portrait.e2e.test.ts | 384 ++++++++ .../tests/e2e/video-retouch.e2e.test.ts | 382 ++++++++ .../tests/e2e/video-style.e2e.test.ts | 343 +++++++ packages/core/src/types/api.ts | 86 +- packages/core/src/types/index.ts | 4 + skills/bailian-gen/SKILL.md | 7 +- skills/bailian-gen/reference/index.md | 5 +- skills/bailian-gen/reference/video.md | 142 +++ 17 files changed, 2770 insertions(+), 4 deletions(-) create mode 100644 packages/commands/src/commands/video/portrait.ts create mode 100644 packages/commands/src/commands/video/retouch.ts create mode 100644 packages/commands/src/commands/video/specialized-shared.ts create mode 100644 packages/commands/src/commands/video/style.ts create mode 100644 packages/commands/tests/e2e/video-portrait.e2e.test.ts create mode 100644 packages/commands/tests/e2e/video-retouch.e2e.test.ts create mode 100644 packages/commands/tests/e2e/video-style.e2e.test.ts diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 0de5e76f..38950f81 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -21,6 +21,9 @@ import { videoGenerate, videoEdit, videoRef, + videoPortrait, + videoStyle, + videoRetouch, videoTaskGet, videoDownload, visionDescribe, @@ -414,6 +417,9 @@ export const commands: Record = { "video generate": videoGenerate, "video edit": videoEdit, "video ref": videoRef, + "video portrait": videoPortrait, + "video style": videoStyle, + "video retouch": videoRetouch, "video task get": videoTaskGet, "video download": videoDownload, "vision describe": visionDescribe, diff --git a/packages/commands/src/commands/video/download.ts b/packages/commands/src/commands/video/download.ts index 9ceaa316..407d03c8 100644 --- a/packages/commands/src/commands/video/download.ts +++ b/packages/commands/src/commands/video/download.ts @@ -62,7 +62,9 @@ export default defineCommand({ } const downloadUrl = - taskInfo.output.video_url || (taskInfo.output.results && taskInfo.output.results[0]?.url); + taskInfo.output.video_url || + taskInfo.output.output_video_url || + (taskInfo.output.results && taskInfo.output.results[0]?.url); if (!downloadUrl) { throw new BailianError("No download URL available for this task.", ExitCode.GENERAL); diff --git a/packages/commands/src/commands/video/portrait.ts b/packages/commands/src/commands/video/portrait.ts new file mode 100644 index 00000000..dce3ad3d --- /dev/null +++ b/packages/commands/src/commands/video/portrait.ts @@ -0,0 +1,196 @@ +import { + defineCommand, + image2videoPath, + ASYNC_FLAG, + stripUndefined, + type DashScopeVideoRetalkRequest, + type FlagsDef, +} from "bailian-cli-core"; +import { + extractVideoUrlField, + mediaInputError, + previewMediaUrl, + resolveMediaUrl, + runSpecializedVideoLifecycle, +} from "./specialized-shared.ts"; + +const MODEL = "videoretalk"; + +const PORTRAIT_FLAGS = { + video: { + type: "string", + valueHint: "", + description: { + "en-US": "Input video URL or local file (mp4/avi/mov)", + "zh-CN": "输入视频 URL 或本地文件(mp4/avi/mov)", + }, + required: true, + }, + audio: { + type: "string", + valueHint: "", + description: { + "en-US": "Driving audio URL or local file (wav/mp3/aac)", + "zh-CN": "驱动音频 URL 或本地文件(wav/mp3/aac)", + }, + required: true, + }, + refImage: { + type: "string", + valueHint: "", + description: { + "en-US": "Optional reference face image when the video has multiple people", + "zh-CN": "多人视频中可选的参考人脸图", + }, + }, + videoExtension: { + type: "boolean", + valueHint: "", + description: { + "en-US": + "Extend video by alternating reverse/forward playback when audio is longer (default: false)", + "zh-CN": "音频长于视频时是否倒放/正放交替延展(默认 false)", + }, + }, + faceThreshold: { + type: "number", + valueHint: "", + description: { + "en-US": "Face match threshold 120–200 (default: 170; only with --ref-image)", + "zh-CN": "人脸匹配阈值 120–200(默认 170;仅与 --ref-image 联用)", + }, + }, + download: { + type: "string", + valueHint: "", + description: { + "en-US": "Save video to file on completion (default: output dir)", + "zh-CN": "完成后将视频保存到文件(默认输出目录)", + }, + }, + ...ASYNC_FLAG, + pollInterval: { + type: "number", + valueHint: "", + description: { + "en-US": "Polling interval when waiting (default: 15)", + "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", + }, + }, +} satisfies FlagsDef; + +export default defineCommand({ + description: { + "en-US": "Drive a talking-head video with audio (VideoRetalk / videoretalk)", + "zh-CN": "用音频驱动人像口型视频(VideoRetalk / videoretalk)", + }, + auth: "apiKey", + usageArgs: "--video --audio [flags]", + flags: PORTRAIT_FLAGS, + exampleArgs: [ + { + "en-US": + "--video https://example.com/face.mp4 --audio https://example.com/speech.wav --download out.mp4", + "zh-CN": + "--video https://example.com/face.mp4 --audio https://example.com/speech.wav --download out.mp4", + }, + { + "en-US": + "--video ./face.mp4 --audio ./speech.wav --ref-image ./person.jpg --face-threshold 170", + "zh-CN": + "--video ./face.mp4 --audio ./speech.wav --ref-image ./person.jpg --face-threshold 170", + }, + ], + notes: [ + { + "en-US": + "Fixed model videoretalk (Beijing). Supports temporary OSS upload for local media. Requires model access on the account.", + "zh-CN": "固定模型 videoretalk(北京)。本地媒体支持临时 OSS 上传。需账号已开通该模型权限。", + }, + ], + validate: (flags) => { + if ( + flags.pollInterval !== undefined && + (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) + ) { + return { + "en-US": "--poll-interval must be a positive number.", + "zh-CN": "--poll-interval 必须为正数。", + }; + } + if (flags.faceThreshold !== undefined) { + if ( + !Number.isInteger(flags.faceThreshold) || + flags.faceThreshold < 120 || + flags.faceThreshold > 200 + ) { + return { + "en-US": "--face-threshold must be an integer between 120 and 200.", + "zh-CN": "--face-threshold 必须是 120–200 的整数。", + }; + } + if (!flags.refImage) { + return { + "en-US": "--face-threshold requires --ref-image.", + "zh-CN": "--face-threshold 需要同时提供 --ref-image。", + }; + } + } + const videoError = mediaInputError(flags.video, "--video", { allowLocal: true }); + if (videoError) return videoError; + const audioError = mediaInputError(flags.audio, "--audio", { allowLocal: true }); + if (audioError) return audioError; + if (flags.refImage !== undefined) { + const refError = mediaInputError(flags.refImage, "--ref-image", { allowLocal: true }); + if (refError) return refError; + } + return undefined; + }, + async run(ctx) { + const { flags } = ctx; + + function buildRequest(media: { + videoUrl: string; + audioUrl: string; + refImageUrl?: string; + }): DashScopeVideoRetalkRequest { + const parameters = stripUndefined({ + video_extension: flags.videoExtension, + query_face_threshold: flags.faceThreshold, + }); + return { + model: MODEL, + input: stripUndefined({ + video_url: media.videoUrl, + audio_url: media.audioUrl, + ref_image_url: media.refImageUrl, + }) as DashScopeVideoRetalkRequest["input"], + parameters: Object.keys(parameters).length > 0 ? parameters : undefined, + }; + } + + const previewRequest = buildRequest({ + videoUrl: previewMediaUrl(flags.video), + audioUrl: previewMediaUrl(flags.audio), + refImageUrl: flags.refImage !== undefined ? previewMediaUrl(flags.refImage) : undefined, + }); + + await runSpecializedVideoLifecycle(ctx, { + endpointPath: image2videoPath(), + previewRequest, + resolveLiveRequest: async () => { + const videoUrl = await resolveMediaUrl(ctx.client, flags.video, MODEL); + const audioUrl = await resolveMediaUrl(ctx.client, flags.audio, MODEL); + const refImageUrl = + flags.refImage !== undefined + ? await resolveMediaUrl(ctx.client, flags.refImage, MODEL) + : undefined; + return buildRequest({ videoUrl, audioUrl, refImageUrl }); + }, + extractVideoUrl: extractVideoUrlField, + pollInterval: flags.pollInterval, + download: flags.download, + async: flags.async, + }); + }, +}); diff --git a/packages/commands/src/commands/video/retouch.ts b/packages/commands/src/commands/video/retouch.ts new file mode 100644 index 00000000..597252d8 --- /dev/null +++ b/packages/commands/src/commands/video/retouch.ts @@ -0,0 +1,848 @@ +import { + defineCommand, + videoGeneratePath, + ASYNC_FLAG, + stripUndefined, + type DashScopeVideoVaceRequest, + type FlagsDef, + type LocalizedText, + type WanxVaceFunction, +} from "bailian-cli-core"; +import { BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_WATERMARK } from "bailian-cli-runtime"; +import { + extractVideoUrlField, + mediaInputError, + previewMediaUrl, + resolveMediaUrl, + runSpecializedVideoLifecycle, +} from "./specialized-shared.ts"; + +const MODEL = "wanx2.1-vace-plus"; +const DEFAULT_FUNCTION: WanxVaceFunction = "video_repainting"; + +const VACE_FUNCTIONS = new Set([ + "video_repainting", + "video_edit", + "video_extension", + "video_outpainting", + "image_reference", +]); + +const REPAINT_CONTROL = new Set(["posebodyface", "posebody", "depth", "scribble"]); +const EDIT_CONTROL = new Set(["", "posebodyface", "depth"]); +const EXTENSION_CONTROL = new Set(["posebodyface", "depth"]); +const MASK_TYPES = new Set(["tracking", "fixed"]); +const EXPAND_MODES = new Set(["hull", "bbox", "original"]); +const ALLOWED_SIZES = new Set(["1280*720", "720*1280", "960*960", "832*1088", "1088*832"]); + +const RETOUCH_FLAGS = { + prompt: { + type: "string", + valueHint: "", + description: { + "en-US": "Edit / generation prompt (max 800 characters; server may truncate)", + "zh-CN": "编辑/生成提示词(最多 800 字符;服务端可能截断)", + }, + required: true, + }, + function: { + type: "string", + valueHint: "", + description: { + "en-US": + "VACE function: video_repainting (default), video_edit, video_extension, video_outpainting, image_reference", + "zh-CN": + "VACE 模式:video_repainting(默认)、video_edit、video_extension、video_outpainting、image_reference", + }, + choices: [ + "video_repainting", + "video_edit", + "video_extension", + "video_outpainting", + "image_reference", + ] as const, + }, + video: { + type: "string", + valueHint: "", + description: { + "en-US": "Input video URL or local file (required for most functions)", + "zh-CN": "输入视频 URL 或本地文件(多数模式必填)", + }, + }, + refImage: { + type: "array", + valueHint: "", + description: { + "en-US": + "Reference image(s): image_reference 1–3; video_repainting/video_edit at most 1; unsupported for video_extension/video_outpainting", + "zh-CN": + "参考图:image_reference 1–3 张;video_repainting/video_edit 最多 1 张;video_extension/video_outpainting 不支持", + }, + }, + controlCondition: { + type: "string", + valueHint: "", + description: { + "en-US": + "Control condition (required for video_repainting; posebodyface/posebody/depth/scribble)", + "zh-CN": "控制条件(video_repainting 必填;posebodyface/posebody/depth/scribble)", + }, + }, + strength: { + type: "number", + valueHint: "", + description: { + "en-US": "Repaint strength in [0, 1]", + "zh-CN": "重绘强度,范围 [0, 1]", + }, + }, + seed: { + type: "number", + valueHint: "", + description: { + "en-US": "Random seed", + "zh-CN": "随机种子", + }, + }, + promptExtend: { + type: "boolean", + valueHint: "", + description: BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, + }, + watermark: { + type: "boolean", + valueHint: "", + description: BOOL_FLAG_WATERMARK, + }, + maskImage: { + type: "string", + valueHint: "", + description: { + "en-US": "Mask image for video_edit (mutually exclusive with --mask-video)", + "zh-CN": "video_edit 的掩码图(与 --mask-video 二选一)", + }, + }, + maskVideo: { + type: "string", + valueHint: "", + description: { + "en-US": "Mask video for video_edit (mutually exclusive with --mask-image)", + "zh-CN": "video_edit 的掩码视频(与 --mask-image 二选一)", + }, + }, + maskFrameId: { + type: "number", + valueHint: "", + description: { + "en-US": "Mask frame id starting at 1 (video_edit)", + "zh-CN": "掩码帧序号,从 1 起(video_edit)", + }, + }, + maskType: { + type: "string", + valueHint: "", + description: { + "en-US": "Mask type: tracking or fixed (video_edit)", + "zh-CN": "掩码类型:tracking 或 fixed(video_edit)", + }, + choices: ["tracking", "fixed"] as const, + }, + expandRatio: { + type: "number", + valueHint: "", + description: { + "en-US": "Expand ratio in [0, 1] (video_edit)", + "zh-CN": "扩展比例 [0, 1](video_edit)", + }, + }, + expandMode: { + type: "string", + valueHint: "", + description: { + "en-US": "Expand mode hull/bbox/original (image mask + tracking only)", + "zh-CN": "扩展模式 hull/bbox/original(仅图像掩码 + tracking)", + }, + choices: ["hull", "bbox", "original"] as const, + }, + firstFrame: { + type: "string", + valueHint: "", + description: { + "en-US": "First-frame image for video_extension (extends forward)", + "zh-CN": "video_extension 首帧图(向后延展)", + }, + }, + lastFrame: { + type: "string", + valueHint: "", + description: { + "en-US": "Last-frame image for video_extension (extends backward)", + "zh-CN": "video_extension 尾帧图(向前延展)", + }, + }, + firstClip: { + type: "string", + valueHint: "", + description: { + "en-US": "First clip for video_extension (extends forward)", + "zh-CN": "video_extension 首片段(向后延展)", + }, + }, + lastClip: { + type: "string", + valueHint: "", + description: { + "en-US": "Last clip for video_extension (extends backward)", + "zh-CN": "video_extension 尾片段(向前延展)", + }, + }, + topScale: { + type: "number", + valueHint: "", + description: { + "en-US": "Outpainting top scale in [1, 2] (1 = no expand)", + "zh-CN": "画面扩展上边比例 [1, 2](1 不扩展)", + }, + }, + bottomScale: { + type: "number", + valueHint: "", + description: { + "en-US": "Outpainting bottom scale in [1, 2]", + "zh-CN": "画面扩展下边比例 [1, 2]", + }, + }, + leftScale: { + type: "number", + valueHint: "", + description: { + "en-US": "Outpainting left scale in [1, 2]", + "zh-CN": "画面扩展左边比例 [1, 2]", + }, + }, + rightScale: { + type: "number", + valueHint: "", + description: { + "en-US": "Outpainting right scale in [1, 2]", + "zh-CN": "画面扩展右边比例 [1, 2]", + }, + }, + refRole: { + type: "array", + valueHint: "", + description: { + "en-US": "Per-image role for image_reference (obj or bg; at most one bg)", + "zh-CN": "image_reference 每张图的角色(obj 或 bg;最多一个 bg)", + }, + }, + size: { + type: "string", + valueHint: "", + description: { + "en-US": + "Output size for image_reference / video_edit (1280*720, 720*1280, 960*960, 832*1088, 1088*832)", + "zh-CN": + "image_reference / video_edit 输出尺寸(1280*720、720*1280、960*960、832*1088、1088*832)", + }, + }, + download: { + type: "string", + valueHint: "", + description: { + "en-US": "Save video to file on completion (default: output dir)", + "zh-CN": "完成后将视频保存到文件(默认输出目录)", + }, + }, + ...ASYNC_FLAG, + pollInterval: { + type: "number", + valueHint: "", + description: { + "en-US": "Polling interval when waiting (default: 15)", + "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", + }, + }, +} satisfies FlagsDef; + +type RetouchFlags = { + prompt: string; + function?: WanxVaceFunction; + video?: string; + refImage?: string[]; + controlCondition?: string; + strength?: number; + seed?: number; + promptExtend?: boolean; + watermark?: boolean; + maskImage?: string; + maskVideo?: string; + maskFrameId?: number; + maskType?: string; + expandRatio?: number; + expandMode?: string; + firstFrame?: string; + lastFrame?: string; + firstClip?: string; + lastClip?: string; + topScale?: number; + bottomScale?: number; + leftScale?: number; + rightScale?: number; + refRole?: string[]; + size?: string; + download?: string; + async?: boolean; + pollInterval?: number; +}; + +function resolveFunction(flags: RetouchFlags): WanxVaceFunction { + return flags.function ?? DEFAULT_FUNCTION; +} + +function rejectFlagsError( + present: Array<[string, unknown]>, + mode: WanxVaceFunction, +): LocalizedText | undefined { + const used = present.filter(([, value]) => value !== undefined); + if (used.length === 0) return undefined; + const names = used.map(([name]) => name).join(", "); + return { + "en-US": `Flags not applicable to --function ${mode}: ${names}.`, + "zh-CN": `以下参数不适用于 --function ${mode}:${names}。`, + }; +} + +function scaleError(value: number | undefined, flagName: string): LocalizedText | undefined { + if (value === undefined) return undefined; + if (!(value >= 1 && value <= 2) || !Number.isFinite(value)) { + return { + "en-US": `${flagName} must be in [1, 2].`, + "zh-CN": `${flagName} 必须在 [1, 2] 范围内。`, + }; + } + return undefined; +} + +/** Mode / media / cross-flag checks for validate (before auth). */ +function validateRetouchFlags(flags: RetouchFlags): LocalizedText | undefined { + if ( + flags.pollInterval !== undefined && + (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) + ) { + return { + "en-US": "--poll-interval must be a positive number.", + "zh-CN": "--poll-interval 必须为正数。", + }; + } + + const mode = resolveFunction(flags); + if (!VACE_FUNCTIONS.has(mode)) { + return { + "en-US": `Unsupported --function "${String(flags.function)}".`, + "zh-CN": `不支持的 --function "${String(flags.function)}"。`, + }; + } + + const refImages = flags.refImage ?? []; + for (const image of refImages) { + const refError = mediaInputError(image, "--ref-image", { allowLocal: true }); + if (refError) return refError; + } + + const mediaFlags: Array<[string, string | undefined]> = [ + ["--video", flags.video], + ["--mask-image", flags.maskImage], + ["--mask-video", flags.maskVideo], + ["--first-frame", flags.firstFrame], + ["--last-frame", flags.lastFrame], + ["--first-clip", flags.firstClip], + ["--last-clip", flags.lastClip], + ]; + for (const [name, value] of mediaFlags) { + if (value !== undefined) { + const mediaError = mediaInputError(value, name, { allowLocal: true }); + if (mediaError) return mediaError; + } + } + + switch (mode) { + case "video_repainting": { + const rejected = rejectFlagsError( + [ + ["--mask-image", flags.maskImage], + ["--mask-video", flags.maskVideo], + ["--mask-frame-id", flags.maskFrameId], + ["--mask-type", flags.maskType], + ["--expand-ratio", flags.expandRatio], + ["--expand-mode", flags.expandMode], + ["--first-frame", flags.firstFrame], + ["--last-frame", flags.lastFrame], + ["--first-clip", flags.firstClip], + ["--last-clip", flags.lastClip], + ["--top-scale", flags.topScale], + ["--bottom-scale", flags.bottomScale], + ["--left-scale", flags.leftScale], + ["--right-scale", flags.rightScale], + ["--ref-role", flags.refRole], + ["--size", flags.size], + ], + mode, + ); + if (rejected) return rejected; + if (!flags.video) { + return { + "en-US": "--video is required for video_repainting.", + "zh-CN": "video_repainting 需要 --video。", + }; + } + if (!flags.controlCondition || !REPAINT_CONTROL.has(flags.controlCondition)) { + return { + "en-US": + "--control-condition is required for video_repainting (posebodyface/posebody/depth/scribble).", + "zh-CN": + "video_repainting 需要 --control-condition(posebodyface/posebody/depth/scribble)。", + }; + } + if (refImages.length > 1) { + return { + "en-US": "video_repainting accepts at most one --ref-image.", + "zh-CN": "video_repainting 最多一张 --ref-image。", + }; + } + if ( + flags.strength !== undefined && + (!(flags.strength >= 0 && flags.strength <= 1) || !Number.isFinite(flags.strength)) + ) { + return { + "en-US": "--strength must be in [0, 1].", + "zh-CN": "--strength 必须在 [0, 1] 范围内。", + }; + } + return undefined; + } + case "video_edit": { + const rejected = rejectFlagsError( + [ + ["--first-frame", flags.firstFrame], + ["--last-frame", flags.lastFrame], + ["--first-clip", flags.firstClip], + ["--last-clip", flags.lastClip], + ["--top-scale", flags.topScale], + ["--bottom-scale", flags.bottomScale], + ["--left-scale", flags.leftScale], + ["--right-scale", flags.rightScale], + ["--ref-role", flags.refRole], + ["--strength", flags.strength], + ], + mode, + ); + if (rejected) return rejected; + if (!flags.video) { + return { + "en-US": "--video is required for video_edit.", + "zh-CN": "video_edit 需要 --video。", + }; + } + const hasMaskImage = flags.maskImage !== undefined; + const hasMaskVideo = flags.maskVideo !== undefined; + if (hasMaskImage === hasMaskVideo) { + return { + "en-US": "video_edit requires exactly one of --mask-image or --mask-video.", + "zh-CN": "video_edit 需要在 --mask-image 与 --mask-video 中二选一。", + }; + } + if (refImages.length > 1) { + return { + "en-US": "video_edit accepts at most one --ref-image.", + "zh-CN": "video_edit 最多一张 --ref-image。", + }; + } + if (flags.controlCondition !== undefined && !EDIT_CONTROL.has(flags.controlCondition)) { + return { + "en-US": "--control-condition for video_edit must be empty, posebodyface, or depth.", + "zh-CN": "video_edit 的 --control-condition 只能是空、posebodyface 或 depth。", + }; + } + if (flags.maskType !== undefined && !MASK_TYPES.has(flags.maskType)) { + return { + "en-US": "--mask-type must be tracking or fixed.", + "zh-CN": "--mask-type 必须是 tracking 或 fixed。", + }; + } + if ( + flags.expandRatio !== undefined && + (!(flags.expandRatio >= 0 && flags.expandRatio <= 1) || !Number.isFinite(flags.expandRatio)) + ) { + return { + "en-US": "--expand-ratio must be in [0, 1].", + "zh-CN": "--expand-ratio 必须在 [0, 1] 范围内。", + }; + } + if (flags.expandMode !== undefined) { + if (!EXPAND_MODES.has(flags.expandMode)) { + return { + "en-US": "--expand-mode must be hull, bbox, or original.", + "zh-CN": "--expand-mode 必须是 hull、bbox 或 original。", + }; + } + if (!(hasMaskImage && flags.maskType === "tracking")) { + return { + "en-US": "--expand-mode is only valid with --mask-image and --mask-type tracking.", + "zh-CN": "--expand-mode 仅在 --mask-image 且 --mask-type tracking 时可用。", + }; + } + } + if ( + flags.maskFrameId !== undefined && + (!Number.isInteger(flags.maskFrameId) || flags.maskFrameId < 1) + ) { + return { + "en-US": "--mask-frame-id must be an integer >= 1.", + "zh-CN": "--mask-frame-id 必须是大于等于 1 的整数。", + }; + } + if (flags.size !== undefined && !ALLOWED_SIZES.has(flags.size)) { + return { + "en-US": "--size must be one of 1280*720, 720*1280, 960*960, 832*1088, 1088*832.", + "zh-CN": "--size 必须是 1280*720、720*1280、960*960、832*1088、1088*832 之一。", + }; + } + return undefined; + } + case "video_extension": { + const rejected = rejectFlagsError( + [ + ["--mask-image", flags.maskImage], + ["--mask-video", flags.maskVideo], + ["--mask-frame-id", flags.maskFrameId], + ["--mask-type", flags.maskType], + ["--expand-ratio", flags.expandRatio], + ["--expand-mode", flags.expandMode], + ["--top-scale", flags.topScale], + ["--bottom-scale", flags.bottomScale], + ["--left-scale", flags.leftScale], + ["--right-scale", flags.rightScale], + ["--ref-role", flags.refRole], + ["--size", flags.size], + ["--strength", flags.strength], + ["--ref-image", flags.refImage], + ], + mode, + ); + if (rejected) return rejected; + const mediaCount = [ + flags.video, + flags.firstFrame, + flags.lastFrame, + flags.firstClip, + flags.lastClip, + ].filter((value) => value !== undefined).length; + if (mediaCount < 1) { + return { + "en-US": + "video_extension requires at least one of --video, --first-frame, --last-frame, --first-clip, --last-clip.", + "zh-CN": + "video_extension 需要在 --video / --first-frame / --last-frame / --first-clip / --last-clip 中至少提供一项。", + }; + } + if (flags.video) { + if (!flags.controlCondition || !EXTENSION_CONTROL.has(flags.controlCondition)) { + return { + "en-US": + "When --video is set for video_extension, --control-condition must be posebodyface or depth.", + "zh-CN": + "video_extension 提供 --video 时,--control-condition 必须是 posebodyface 或 depth。", + }; + } + } else if (flags.controlCondition !== undefined) { + if (!EXTENSION_CONTROL.has(flags.controlCondition)) { + return { + "en-US": "--control-condition for video_extension must be posebodyface or depth.", + "zh-CN": "video_extension 的 --control-condition 必须是 posebodyface 或 depth。", + }; + } + } + return undefined; + } + case "video_outpainting": { + const rejected = rejectFlagsError( + [ + ["--mask-image", flags.maskImage], + ["--mask-video", flags.maskVideo], + ["--mask-frame-id", flags.maskFrameId], + ["--mask-type", flags.maskType], + ["--expand-ratio", flags.expandRatio], + ["--expand-mode", flags.expandMode], + ["--first-frame", flags.firstFrame], + ["--last-frame", flags.lastFrame], + ["--first-clip", flags.firstClip], + ["--last-clip", flags.lastClip], + ["--ref-role", flags.refRole], + ["--size", flags.size], + ["--strength", flags.strength], + ["--control-condition", flags.controlCondition], + ["--ref-image", flags.refImage], + ], + mode, + ); + if (rejected) return rejected; + if (!flags.video) { + return { + "en-US": "--video is required for video_outpainting.", + "zh-CN": "video_outpainting 需要 --video。", + }; + } + return ( + scaleError(flags.topScale, "--top-scale") || + scaleError(flags.bottomScale, "--bottom-scale") || + scaleError(flags.leftScale, "--left-scale") || + scaleError(flags.rightScale, "--right-scale") + ); + } + case "image_reference": { + const rejected = rejectFlagsError( + [ + ["--video", flags.video], + ["--mask-image", flags.maskImage], + ["--mask-video", flags.maskVideo], + ["--mask-frame-id", flags.maskFrameId], + ["--mask-type", flags.maskType], + ["--expand-ratio", flags.expandRatio], + ["--expand-mode", flags.expandMode], + ["--first-frame", flags.firstFrame], + ["--last-frame", flags.lastFrame], + ["--first-clip", flags.firstClip], + ["--last-clip", flags.lastClip], + ["--top-scale", flags.topScale], + ["--bottom-scale", flags.bottomScale], + ["--left-scale", flags.leftScale], + ["--right-scale", flags.rightScale], + ["--strength", flags.strength], + ["--control-condition", flags.controlCondition], + ], + mode, + ); + if (rejected) return rejected; + if (refImages.length < 1 || refImages.length > 3) { + return { + "en-US": "image_reference requires 1–3 --ref-image values.", + "zh-CN": "image_reference 需要 1–3 张 --ref-image。", + }; + } + if (flags.refRole !== undefined) { + if (flags.refRole.length !== refImages.length) { + return { + "en-US": "--ref-role count must match --ref-image count.", + "zh-CN": "--ref-role 数量必须与 --ref-image 一致。", + }; + } + let bgCount = 0; + for (const role of flags.refRole) { + if (role !== "obj" && role !== "bg") { + return { + "en-US": '--ref-role values must be "obj" or "bg".', + "zh-CN": '--ref-role 取值必须是 "obj" 或 "bg"。', + }; + } + if (role === "bg") bgCount += 1; + } + if (bgCount > 1) { + return { + "en-US": "At most one --ref-role bg is allowed.", + "zh-CN": "--ref-role 最多只能有一个 bg。", + }; + } + } + if (flags.size !== undefined && !ALLOWED_SIZES.has(flags.size)) { + return { + "en-US": "--size must be one of 1280*720, 720*1280, 960*960, 832*1088, 1088*832.", + "zh-CN": "--size 必须是 1280*720、720*1280、960*960、832*1088、1088*832 之一。", + }; + } + return undefined; + } + default: { + const _exhaustive: never = mode; + return { + "en-US": `Unsupported --function "${String(_exhaustive)}".`, + "zh-CN": `不支持的 --function "${String(_exhaustive)}"。`, + }; + } + } +} + +function buildVaceRequest( + flags: RetouchFlags, + mode: WanxVaceFunction, + media: { + videoUrl?: string; + refImages?: string[]; + maskImageUrl?: string; + maskVideoUrl?: string; + firstFrameUrl?: string; + lastFrameUrl?: string; + firstClipUrl?: string; + lastClipUrl?: string; + }, +): DashScopeVideoVaceRequest { + const input = stripUndefined({ + function: mode, + prompt: flags.prompt, + video_url: media.videoUrl, + ref_images_url: media.refImages, + mask_image_url: media.maskImageUrl, + mask_video_url: media.maskVideoUrl, + mask_frame_id: flags.maskFrameId, + first_frame_url: media.firstFrameUrl, + last_frame_url: media.lastFrameUrl, + first_clip_url: media.firstClipUrl, + last_clip_url: media.lastClipUrl, + }) as DashScopeVideoVaceRequest["input"]; + + const objOrBg = flags.refRole === undefined ? undefined : (flags.refRole as Array<"obj" | "bg">); + + const parameters = stripUndefined({ + control_condition: flags.controlCondition === "" ? undefined : flags.controlCondition, + strength: flags.strength, + prompt_extend: flags.promptExtend, + watermark: flags.watermark, + seed: flags.seed, + mask_type: flags.maskType, + expand_ratio: flags.expandRatio, + expand_mode: flags.expandMode, + size: flags.size, + top_scale: flags.topScale, + bottom_scale: flags.bottomScale, + left_scale: flags.leftScale, + right_scale: flags.rightScale, + obj_or_bg: objOrBg, + }); + + return { + model: MODEL, + input, + parameters: Object.keys(parameters).length > 0 ? parameters : undefined, + }; +} + +export default defineCommand({ + description: { + "en-US": + "Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference)", + "zh-CN": "万相 2.1 VACE 统一视频编辑(重绘/局部编辑/延展/画面扩展/多图参考)", + }, + auth: "apiKey", + usageArgs: "--prompt [--function ] [flags]", + flags: RETOUCH_FLAGS, + exampleArgs: [ + { + "en-US": + '--prompt "Convert the scene to claymation" --function video_repainting --video https://example.com/in.mp4 --control-condition depth --strength 0.8', + "zh-CN": + '--prompt "将场景转为黏土风格" --function video_repainting --video https://example.com/in.mp4 --control-condition depth --strength 0.8', + }, + { + "en-US": + '--prompt "Extend the shot" --function video_extension --first-frame https://example.com/first.png', + "zh-CN": + '--prompt "延展镜头" --function video_extension --first-frame https://example.com/first.png', + }, + { + "en-US": + '--prompt "Generate from references" --function image_reference --ref-image https://example.com/a.png --ref-image https://example.com/b.png --ref-role obj --ref-role bg --size 1280*720', + "zh-CN": + '--prompt "参考图生成" --function image_reference --ref-image https://example.com/a.png --ref-image https://example.com/b.png --ref-role obj --ref-role bg --size 1280*720', + }, + ], + notes: [ + { + "en-US": + "Fixed model wanx2.1-vace-plus (Beijing/Singapore). Distinct from `video edit` (happyhorse). Output is silent MP4. video_extension: first-frame/clip extends forward, last-frame/clip extends backward; total output is 5s. Requires model access. Do not use a boolean --video-extension alias.", + "zh-CN": + "固定模型 wanx2.1-vace-plus(北京/新加坡)。与 `video edit`(happyhorse)不同。输出为无声 MP4。video_extension:首帧/首片段向后延展,尾帧/尾片段向前延展;完整输出共 5 秒。需账号已开通该模型权限。不要使用布尔 --video-extension 别名。", + }, + ], + validate: (flags) => validateRetouchFlags(flags as RetouchFlags), + async run(ctx) { + const flags = ctx.flags as RetouchFlags; + const mode = resolveFunction(flags); + + if (flags.prompt.length > 800) { + ctx.output.info({ + "en-US": + "Prompt exceeds 800 characters; the server may truncate it. The CLI does not modify the text.", + "zh-CN": "提示词超过 800 字符,服务端可能截断;CLI 不会改写原文。", + }); + } + + const previewMedia = { + videoUrl: flags.video !== undefined ? previewMediaUrl(flags.video) : undefined, + refImages: flags.refImage?.map((image) => previewMediaUrl(image)), + maskImageUrl: flags.maskImage !== undefined ? previewMediaUrl(flags.maskImage) : undefined, + maskVideoUrl: flags.maskVideo !== undefined ? previewMediaUrl(flags.maskVideo) : undefined, + firstFrameUrl: flags.firstFrame !== undefined ? previewMediaUrl(flags.firstFrame) : undefined, + lastFrameUrl: flags.lastFrame !== undefined ? previewMediaUrl(flags.lastFrame) : undefined, + firstClipUrl: flags.firstClip !== undefined ? previewMediaUrl(flags.firstClip) : undefined, + lastClipUrl: flags.lastClip !== undefined ? previewMediaUrl(flags.lastClip) : undefined, + }; + + const previewRequest = buildVaceRequest(flags, mode, previewMedia); + + await runSpecializedVideoLifecycle(ctx, { + endpointPath: videoGeneratePath(), + previewRequest, + resolveLiveRequest: async () => { + const videoUrl = + flags.video !== undefined + ? await resolveMediaUrl(ctx.client, flags.video, MODEL) + : undefined; + const refImages = + flags.refImage !== undefined + ? await Promise.all( + flags.refImage.map((image) => resolveMediaUrl(ctx.client, image, MODEL)), + ) + : undefined; + const maskImageUrl = + flags.maskImage !== undefined + ? await resolveMediaUrl(ctx.client, flags.maskImage, MODEL) + : undefined; + const maskVideoUrl = + flags.maskVideo !== undefined + ? await resolveMediaUrl(ctx.client, flags.maskVideo, MODEL) + : undefined; + const firstFrameUrl = + flags.firstFrame !== undefined + ? await resolveMediaUrl(ctx.client, flags.firstFrame, MODEL) + : undefined; + const lastFrameUrl = + flags.lastFrame !== undefined + ? await resolveMediaUrl(ctx.client, flags.lastFrame, MODEL) + : undefined; + const firstClipUrl = + flags.firstClip !== undefined + ? await resolveMediaUrl(ctx.client, flags.firstClip, MODEL) + : undefined; + const lastClipUrl = + flags.lastClip !== undefined + ? await resolveMediaUrl(ctx.client, flags.lastClip, MODEL) + : undefined; + return buildVaceRequest(flags, mode, { + videoUrl, + refImages, + maskImageUrl, + maskVideoUrl, + firstFrameUrl, + lastFrameUrl, + firstClipUrl, + lastClipUrl, + }); + }, + extractVideoUrl: extractVideoUrlField, + pollInterval: flags.pollInterval, + download: flags.download, + async: flags.async, + }); + }, +}); diff --git a/packages/commands/src/commands/video/specialized-shared.ts b/packages/commands/src/commands/video/specialized-shared.ts new file mode 100644 index 00000000..07b1bee1 --- /dev/null +++ b/packages/commands/src/commands/video/specialized-shared.ts @@ -0,0 +1,164 @@ +import { + BailianError, + ExitCode, + resolveOutputDir, + type Client, + type CommandContext, + type DashScopeAsyncResponse, + type DashScopeTaskResponse, + type FlagsDef, + type LocalizedText, +} from "bailian-cli-core"; +import { join } from "path"; +import { existsSync, statSync } from "fs"; +import { downloadDashScopeTaskResult, pollDashScopeTask } from "../shared/dashscope-task.ts"; +import { hasNonAscii, isHttpUrl } from "../shared/translation.ts"; + +/** Floor aligned with video edit/ref long-running tasks. */ +export const SPECIALIZED_VIDEO_TIMEOUT_FLOOR_SEC = 600; + +export function pendingUploadMarker(localPath: string): string { + return ``; +} + +export function previewMediaUrl(value: string): string { + return isHttpUrl(value) ? value : pendingUploadMarker(value); +} + +/** Usage error for media flags; safe for command.validate (auth-independent). */ +export function mediaInputError( + value: string | undefined, + flagName: string, + options?: { allowLocal?: boolean }, +): LocalizedText | undefined { + if (value === undefined || value === "") { + return { + "en-US": `${flagName} must not be empty.`, + "zh-CN": `${flagName} 不能为空。`, + }; + } + if (isHttpUrl(value)) { + if (hasNonAscii(value)) { + return { + "en-US": `${flagName} URL must not contain non-ASCII characters.`, + "zh-CN": `${flagName} URL 不能包含非 ASCII 字符。`, + }; + } + return undefined; + } + if (options?.allowLocal === false) { + return { + "en-US": `${flagName} must be a public http(s) URL (local paths are not supported in v1).`, + "zh-CN": `${flagName} 必须是公网 http(s) URL(v1 不支持本地路径)。`, + }; + } + if (!existsSync(value)) { + return { + "en-US": `File not found: ${value}`, + "zh-CN": `文件不存在:${value}`, + }; + } + if (!statSync(value).isFile()) { + return { + "en-US": `Not a file: ${value}`, + "zh-CN": `不是文件:${value}`, + }; + } + return undefined; +} + +export async function resolveMediaUrl( + client: Client, + value: string, + model: string, +): Promise { + if (isHttpUrl(value)) return value; + return client.uploadFile(value, model); +} + +export type SpecializedVideoUrlExtractor = (task: DashScopeTaskResponse) => string | undefined; + +export function extractVideoUrlField(task: DashScopeTaskResponse): string | undefined { + return task.output.video_url || task.output.results?.[0]?.url; +} + +export function extractStyleOutputVideoUrl(task: DashScopeTaskResponse): string | undefined { + return task.output.output_video_url || extractVideoUrlField(task); +} + +type SpecializedLifecycleOptions = { + endpointPath: string; + previewRequest: unknown; + /** Build the live body after any uploads; skipped on dry-run. */ + resolveLiveRequest: () => Promise; + extractVideoUrl: SpecializedVideoUrlExtractor; + pollInterval?: number; + download?: string; + async?: boolean; +}; + +/** Submit / poll / download lifecycle shared by portrait, style, and retouch. */ +export async function runSpecializedVideoLifecycle( + ctx: CommandContext, + options: SpecializedLifecycleOptions, +): Promise { + const { settings } = ctx; + const localize = ctx.localize; + const endpoint = ctx.client.url(options.endpointPath); + + if (settings.dryRun) { + ctx.output.result({ endpoint, request: options.previewRequest }); + return; + } + + const liveRequest = await options.resolveLiveRequest(); + const submitted = await ctx.client.requestJson({ + path: options.endpointPath, + method: "POST", + body: liveRequest, + async: true, + }); + + const taskId = submitted.output.task_id; + if (options.async) { + ctx.output.result({ task_id: taskId, request_id: submitted.request_id }); + return; + } + + const pollTimeoutSec = Math.max(settings.timeout, SPECIALIZED_VIDEO_TIMEOUT_FLOOR_SEC); + const taskResponse = await pollDashScopeTask( + { + ...ctx, + settings: { ...settings, timeout: pollTimeoutSec }, + }, + taskId, + { pollInterval: options.pollInterval ?? 15 }, + ); + + const videoUrl = options.extractVideoUrl(taskResponse); + if (!videoUrl) { + throw new BailianError( + localize({ + "en-US": "Task succeeded but no video URL was returned.", + "zh-CN": "任务成功但未返回视频 URL。", + }), + ExitCode.GENERAL, + ); + } + + const destPath = + options.download || join(resolveOutputDir(settings, { subDir: "videos" }), `${taskId}.mp4`); + await downloadDashScopeTaskResult(ctx, taskId, videoUrl, destPath); + + const result: Record = { + ...taskResponse, + task_id: taskId, + video_url: videoUrl, + saved: destPath, + }; + if (taskResponse.output.output_video_url) { + result.output_video_url = taskResponse.output.output_video_url; + } + + ctx.output.result(result); +} diff --git a/packages/commands/src/commands/video/style.ts b/packages/commands/src/commands/video/style.ts new file mode 100644 index 00000000..62726ed6 --- /dev/null +++ b/packages/commands/src/commands/video/style.ts @@ -0,0 +1,176 @@ +import { + defineCommand, + videoGeneratePath, + ASYNC_FLAG, + stripUndefined, + type DashScopeVideoStyleTransformRequest, + type FlagsDef, +} from "bailian-cli-core"; +import { + extractStyleOutputVideoUrl, + mediaInputError, + runSpecializedVideoLifecycle, +} from "./specialized-shared.ts"; + +const MODEL = "video-style-transform"; + +const STYLE_FLAGS = { + video: { + type: "string", + valueHint: "", + description: { + "en-US": "Input video public URL (local paths not supported in v1)", + "zh-CN": "输入视频公网 URL(v1 不支持本地路径)", + }, + required: true, + }, + style: { + type: "number", + valueHint: "", + description: { + "en-US": + "Style ID 0–7 (default: 0). 0 Japanese comic, 1 American comic, 2 fresh comic, 3 3D cartoon, 4 Chinese cartoon, 5 paper art, 6 simple illustration, 7 Chinese ink", + "zh-CN": + "风格编号 0–7(默认 0)。0 日式漫画、1 美式漫画、2 清新漫画、3 3D 卡通、4 国风卡通、5 纸艺、6 简易插画、7 国风水墨", + }, + }, + fps: { + type: "number", + valueHint: "", + description: { + "en-US": "Output video FPS 15–25 (maps to video_fps)", + "zh-CN": "输出视频帧率 15–25(映射为 video_fps)", + }, + }, + animateEmotion: { + type: "boolean", + valueHint: "", + description: { + "en-US": "Animate facial emotion (server default: true)", + "zh-CN": "是否动画化表情(服务端默认 true)", + }, + }, + minLen: { + type: "number", + valueHint: "", + description: { + "en-US": "Short-side length 540 or 720 (server default: 720)", + "zh-CN": "短边长度 540 或 720(服务端默认 720)", + }, + }, + superResolution: { + type: "boolean", + valueHint: "", + description: { + "en-US": "Enable super-resolution (maps to use_SR; server default: false)", + "zh-CN": "是否启用超分(映射为 use_SR;服务端默认 false)", + }, + }, + download: { + type: "string", + valueHint: "", + description: { + "en-US": "Save video to file on completion (default: output dir)", + "zh-CN": "完成后将视频保存到文件(默认输出目录)", + }, + }, + ...ASYNC_FLAG, + pollInterval: { + type: "number", + valueHint: "", + description: { + "en-US": "Polling interval when waiting (default: 15)", + "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", + }, + }, +} satisfies FlagsDef; + +export default defineCommand({ + description: { + "en-US": "Restyle a video (video-style-transform)", + "zh-CN": "视频风格重绘(video-style-transform)", + }, + auth: "apiKey", + usageArgs: "--video [flags]", + flags: STYLE_FLAGS, + exampleArgs: [ + { + "en-US": "--video https://example.com/clip.mp4 --style 0 --download styled.mp4", + "zh-CN": "--video https://example.com/clip.mp4 --style 0 --download styled.mp4", + }, + { + "en-US": + "--video https://example.com/clip.mp4 --style 4 --fps 15 --min-len 540 --super-resolution true", + "zh-CN": + "--video https://example.com/clip.mp4 --style 4 --fps 15 --min-len 540 --super-resolution true", + }, + ], + notes: [ + { + "en-US": + "Fixed model video-style-transform (Beijing only). Success field is output.output_video_url. Local paths are rejected until temporary OSS support is verified. Requires model access.", + "zh-CN": + "固定模型 video-style-transform(仅北京)。成功字段为 output.output_video_url。在临时 OSS 验证前拒绝本地路径。需账号已开通该模型权限。", + }, + ], + validate: (flags) => { + if ( + flags.pollInterval !== undefined && + (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) + ) { + return { + "en-US": "--poll-interval must be a positive number.", + "zh-CN": "--poll-interval 必须为正数。", + }; + } + if (flags.style !== undefined) { + if (!Number.isInteger(flags.style) || flags.style < 0 || flags.style > 7) { + return { + "en-US": "--style must be an integer between 0 and 7.", + "zh-CN": "--style 必须是 0–7 的整数。", + }; + } + } + if (flags.fps !== undefined) { + if (!Number.isInteger(flags.fps) || flags.fps < 15 || flags.fps > 25) { + return { + "en-US": "--fps must be an integer between 15 and 25.", + "zh-CN": "--fps 必须是 15–25 的整数。", + }; + } + } + if (flags.minLen !== undefined && flags.minLen !== 540 && flags.minLen !== 720) { + return { + "en-US": "--min-len must be 540 or 720.", + "zh-CN": "--min-len 必须是 540 或 720。", + }; + } + return mediaInputError(flags.video, "--video", { allowLocal: false }); + }, + async run(ctx) { + const { flags } = ctx; + + const parameters = stripUndefined({ + style: flags.style, + video_fps: flags.fps, + animate_emotion: flags.animateEmotion, + min_len: flags.minLen, + use_SR: flags.superResolution, + }); + const request: DashScopeVideoStyleTransformRequest = { + model: MODEL, + input: { video_url: flags.video }, + parameters: Object.keys(parameters).length > 0 ? parameters : undefined, + }; + + await runSpecializedVideoLifecycle(ctx, { + endpointPath: videoGeneratePath(), + previewRequest: request, + resolveLiveRequest: async () => request, + extractVideoUrl: extractStyleOutputVideoUrl, + pollInterval: flags.pollInterval, + download: flags.download, + async: flags.async, + }); + }, +}); diff --git a/packages/commands/src/commands/video/task-get.ts b/packages/commands/src/commands/video/task-get.ts index 513a795f..df454d0a 100644 --- a/packages/commands/src/commands/video/task-get.ts +++ b/packages/commands/src/commands/video/task-get.ts @@ -40,6 +40,9 @@ export default defineCommand({ task_id: response.output.task_id, task_status: response.output.task_status, video_url: response.output.video_url, + output_video_url: response.output.output_video_url, + orig_prompt: response.output.orig_prompt, + actual_prompt: response.output.actual_prompt, image_url: response.output.image_url, results: response.output.results, Success: response.output.Success, diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index e6f26885..947a9ce0 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -23,6 +23,9 @@ export { default as imageTranslate } from "./commands/image/translate.ts"; export { default as videoGenerate } from "./commands/video/generate.ts"; export { default as videoEdit } from "./commands/video/edit.ts"; export { default as videoRef } from "./commands/video/ref.ts"; +export { default as videoPortrait } from "./commands/video/portrait.ts"; +export { default as videoStyle } from "./commands/video/style.ts"; +export { default as videoRetouch } from "./commands/video/retouch.ts"; export { default as videoTaskGet } from "./commands/video/task-get.ts"; export { default as videoDownload } from "./commands/video/download.ts"; export { default as visionDescribe } from "./commands/vision/describe.ts"; diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index a70c8e6e..b3d103b9 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -135,11 +135,32 @@ export const VIDEO_ROUTES: E2eRouteExports = { "video generate": "videoGenerate", "video edit": "videoEdit", "video ref": "videoRef", + "video portrait": "videoPortrait", + "video style": "videoStyle", + "video retouch": "videoRetouch", "video task get": "videoTaskGet", "video download": "videoDownload", "speech synthesize": "speechSynthesize", }; +export const VIDEO_PORTRAIT_ROUTES: E2eRouteExports = { + "video portrait": "videoPortrait", + "video task get": "videoTaskGet", + "video download": "videoDownload", +}; + +export const VIDEO_STYLE_ROUTES: E2eRouteExports = { + "video style": "videoStyle", + "video task get": "videoTaskGet", + "video download": "videoDownload", +}; + +export const VIDEO_RETOUCH_ROUTES: E2eRouteExports = { + "video retouch": "videoRetouch", + "video task get": "videoTaskGet", + "video download": "videoDownload", +}; + export const VISION_ROUTES: E2eRouteExports = { "vision describe": "visionDescribe", }; diff --git a/packages/commands/tests/e2e/video-portrait.e2e.test.ts b/packages/commands/tests/e2e/video-portrait.e2e.test.ts new file mode 100644 index 00000000..c5191ebd --- /dev/null +++ b/packages/commands/tests/e2e/video-portrait.e2e.test.ts @@ -0,0 +1,384 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vite-plus/test"; +import { + isBailianE2EVideoEnabled, + isDashScopeE2EReady, + makeE2eOutputDir, + parseStdoutJson, + runCommandHelp, + runCommandE2e, + runCommandInProcess, +} from "./helpers.ts"; +import { VIDEO_PORTRAIT_ROUTES } from "./topic-routes.ts"; + +const servers: Server[] = []; +const tempDirs: string[] = []; + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }), + ), + ); + for (const tempDir of tempDirs.splice(0)) { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +async function startServer( + handler: (request: IncomingMessage, response: ServerResponse, body: string) => void, +): Promise<{ + origin: string; + requests: Array<{ + method?: string; + path: string; + headers: IncomingMessage["headers"]; + body: string; + }>; +}> { + const requests: Array<{ + method?: string; + path: string; + headers: IncomingMessage["headers"]; + body: string; + }> = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => chunks.push(chunk)); + request.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + requests.push({ + method: request.method, + path: url.pathname, + headers: request.headers, + body, + }); + handler(request, response, body); + }); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + servers.push(server); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP address"); + return { origin: `http://127.0.0.1:${address.port}`, requests }; +} + +describe("e2e: video portrait", () => { + test("help shows bilingual flags and fixed model", async () => { + const { stderr, exitCode } = await runCommandHelp(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--video/); + expect(stderr).toMatch(/--audio/); + expect(stderr).toMatch(/face|阈值|170/); + expect(stderr).toMatch(/videoretalk/); + expect(stderr).not.toMatch(/--model/); + expect(stderr).not.toMatch(/--concurrent/); + }); + + test("missing required flags → 2", async () => { + const missingVideo = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--audio", + "https://example.com/a.wav", + ]); + expect(missingVideo.exitCode).toBe(2); + expect(missingVideo.stderr).toMatch(/--video/i); + + const missingAudio = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--video", + "https://example.com/v.mp4", + ]); + expect(missingAudio.exitCode).toBe(2); + expect(missingAudio.stderr).toMatch(/--audio/i); + }); + + test("face-threshold without ref-image → 2", async () => { + const { stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--face-threshold", + "170", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/face-threshold|ref-image/i); + }); + + test("non-ASCII public URL → 2", async () => { + const { stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--video", + "https://example.com/视频.mp4", + "--audio", + "https://example.com/a.wav", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/non-ASCII|非 ASCII/i); + }); + + test("dry-run builds image2video body with pending local markers", async () => { + const fixtureDir = makeE2eOutputDir("video-portrait-dry"); + tempDirs.push(fixtureDir); + const videoPath = join(fixtureDir, "face.mp4"); + const audioPath = join(fixtureDir, "speech.wav"); + writeFileSync(videoPath, "fake-video"); + writeFileSync(audioPath, "fake-audio"); + + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--video", + videoPath, + "--audio", + audioPath, + "--video-extension", + "false", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ + endpoint?: string; + request?: { + model?: string; + input?: { video_url?: string; audio_url?: string }; + parameters?: { video_extension?: boolean; query_face_threshold?: number }; + }; + }>(stdout); + expect(body.endpoint).toMatch(/\/api\/v1\/services\/aigc\/image2video\/video-synthesis$/); + expect(body.request?.model).toBe("videoretalk"); + expect(body.request?.input?.video_url).toContain("pending-upload"); + expect(body.request?.input?.audio_url).toContain("pending-upload"); + expect(body.request?.parameters?.video_extension).toBe(false); + expect(body.request?.parameters?.query_face_threshold).toBeUndefined(); + }); + + test("async loopback posts Bearer async enable on image2video", async () => { + const { origin, requests } = await startServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-portrait-1", task_status: "PENDING" }, + request_id: "req-portrait-1", + }), + ); + }); + + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--base-url", + origin, + "--api-key", + "sk-test", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--async", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ task_id?: string; request_id?: string }>(stdout); + expect(body.task_id).toBe("task-portrait-1"); + expect(body.request_id).toBe("req-portrait-1"); + expect(requests).toHaveLength(1); + expect(requests[0]?.method).toBe("POST"); + expect(requests[0]?.path).toBe("/api/v1/services/aigc/image2video/video-synthesis"); + expect(requests[0]?.headers["x-dashscope-async"]).toBe("enable"); + expect(requests[0]?.headers.authorization).toMatch(/^Bearer /); + }); + + test("wait mode continues through PRE-PROCESSING then downloads", async () => { + let pollCount = 0; + const mp4Bytes = Buffer.from("fake-mp4-bytes"); + const { origin } = await startServer((request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (request.method === "POST") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-portrait-2", task_status: "PENDING" }, + request_id: "req-2", + }), + ); + return; + } + if (url.pathname === "/api/v1/tasks/task-portrait-2") { + pollCount += 1; + if (pollCount === 1) { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-portrait-2", task_status: "PRE-PROCESSING" }, + request_id: "req-2", + }), + ); + return; + } + if (pollCount === 2) { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-portrait-2", task_status: "POST-PROCESSING" }, + request_id: "req-2", + }), + ); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { + task_id: "task-portrait-2", + task_status: "SUCCEEDED", + video_url: `${origin}/out.mp4`, + }, + request_id: "req-2", + }), + ); + return; + } + if (url.pathname === "/out.mp4") { + response.writeHead(200, { "content-type": "video/mp4" }); + response.end(mp4Bytes); + return; + } + response.writeHead(404); + response.end(); + }); + + const outDir = makeE2eOutputDir("video-portrait-wait"); + tempDirs.push(outDir); + const dest = join(outDir, "portrait.mp4"); + + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--base-url", + origin, + "--api-key", + "sk-test", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--poll-interval", + "0.05", + "--timeout", + "10", + "--download", + dest, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ task_id?: string; video_url?: string; saved?: string }>(stdout); + expect(body.task_id).toBe("task-portrait-2"); + expect(body.video_url).toMatch(/out\.mp4$/); + expect(body.saved).toBe(dest); + expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); + }); + + test("FAILED returns server message without Task failed prefix", async () => { + const { origin } = await startServer((request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (request.method === "POST") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-portrait-fail", task_status: "PENDING" }, + request_id: "req-fail", + }), + ); + return; + } + if (url.pathname === "/api/v1/tasks/task-portrait-fail") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { + task_id: "task-portrait-fail", + task_status: "FAILED", + code: "InvalidParameter", + message: "face not detected", + }, + request_id: "req-fail", + }), + ); + return; + } + response.writeHead(404); + response.end(); + }); + + const { stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--base-url", + origin, + "--api-key", + "sk-test", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--poll-interval", + "0.05", + "--timeout", + "10", + ]); + expect(exitCode).toBe(1); + expect(stderr).toMatch(/face not detected/); + expect(stderr).not.toMatch(/Task failed:/); + }); +}); + +const portraitLiveVideo = process.env.BAILIAN_E2E_VIDEORETALK_VIDEO_URL?.trim(); +const portraitLiveAudio = process.env.BAILIAN_E2E_VIDEORETALK_AUDIO_URL?.trim(); + +describe.skipIf( + !isBailianE2EVideoEnabled() || !isDashScopeE2EReady() || !portraitLiveVideo || !portraitLiveAudio, +)("e2e: video portrait(DashScope live)", () => { + test("videoretalk live portrait drive", async () => { + const outDir = makeE2eOutputDir("video-portrait-live"); + const { stdout, stderr, exitCode } = await runCommandE2e(VIDEO_PORTRAIT_ROUTES, [ + "video", + "portrait", + "--video", + portraitLiveVideo!, + "--audio", + portraitLiveAudio!, + "--download", + join(outDir, "portrait-live.mp4"), + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ video_url?: string; saved?: string }>(stdout); + expect(body.video_url?.startsWith("https://")).toBe(true); + expect(body.saved).toBeTruthy(); + }, 3_600_000); +}); diff --git a/packages/commands/tests/e2e/video-retouch.e2e.test.ts b/packages/commands/tests/e2e/video-retouch.e2e.test.ts new file mode 100644 index 00000000..6db1c71c --- /dev/null +++ b/packages/commands/tests/e2e/video-retouch.e2e.test.ts @@ -0,0 +1,382 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vite-plus/test"; +import { + isBailianE2EVideoEnabled, + isDashScopeE2EReady, + makeE2eOutputDir, + parseStdoutJson, + runCommandHelp, + runCommandE2e, + runCommandInProcess, +} from "./helpers.ts"; +import { VIDEO_RETOUCH_ROUTES } from "./topic-routes.ts"; + +const servers: Server[] = []; +const tempDirs: string[] = []; + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }), + ), + ); + for (const tempDir of tempDirs.splice(0)) { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +async function startServer( + handler: (request: IncomingMessage, response: ServerResponse, body: string) => void, +): Promise<{ origin: string; requests: Array<{ method?: string; path: string; body: string }> }> { + const requests: Array<{ method?: string; path: string; body: string }> = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => chunks.push(chunk)); + request.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + requests.push({ method: request.method, path: url.pathname, body }); + handler(request, response, body); + }); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + servers.push(server); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP address"); + return { origin: `http://127.0.0.1:${address.port}`, requests }; +} + +describe("e2e: video retouch", () => { + test("help distinguishes VACE from happyhorse edit", async () => { + const { stderr, exitCode } = await runCommandHelp(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/VACE|万相/); + expect(stderr).toMatch(/wanx2\.1-vace-plus/); + expect(stderr).toMatch(/--function/); + expect(stderr).not.toMatch(/--model/); + expect(stderr).not.toMatch(/--concurrent/); + }); + + test("video_repainting requires control-condition and video", async () => { + const missingControl = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "clay", + "--video", + "https://example.com/in.mp4", + ]); + expect(missingControl.exitCode).toBe(2); + expect(missingControl.stderr).toMatch(/control-condition/i); + + const missingVideo = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "clay", + "--control-condition", + "depth", + ]); + expect(missingVideo.exitCode).toBe(2); + expect(missingVideo.stderr).toMatch(/--video/i); + }); + + test("video_edit requires exactly one mask", async () => { + const none = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "edit", + "--function", + "video_edit", + "--video", + "https://example.com/in.mp4", + ]); + expect(none.exitCode).toBe(2); + expect(none.stderr).toMatch(/mask/i); + + const both = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "edit", + "--function", + "video_edit", + "--video", + "https://example.com/in.mp4", + "--mask-image", + "https://example.com/mask.png", + "--mask-video", + "https://example.com/mask.mp4", + ]); + expect(both.exitCode).toBe(2); + expect(both.stderr).toMatch(/mask/i); + }); + + test("video_extension requires >=1 media source", async () => { + const { stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "extend", + "--function", + "video_extension", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/first-frame|video_extension|至少/i); + }); + + test("rejects flags not applicable to mode", async () => { + const { stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "clay", + "--video", + "https://example.com/in.mp4", + "--control-condition", + "depth", + "--mask-image", + "https://example.com/mask.png", + ]); + expect(exitCode).toBe(2); + expect(stderr).toMatch(/not applicable|不适用于|--mask-image/i); + }); + + test("image_reference dry-run and role count", async () => { + const badRoles = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "refs", + "--function", + "image_reference", + "--ref-image", + "https://example.com/a.png", + "--ref-image", + "https://example.com/b.png", + "--ref-role", + "obj", + ]); + expect(badRoles.exitCode).toBe(2); + expect(badRoles.stderr).toMatch(/ref-role|ref-image/i); + + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "refs", + "--function", + "image_reference", + "--ref-image", + "https://example.com/a.png", + "--ref-image", + "https://example.com/b.png", + "--ref-role", + "obj", + "--ref-role", + "bg", + "--size", + "1280*720", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ + request?: { + model?: string; + input?: { function?: string; video_url?: string; ref_images_url?: string[] }; + parameters?: { obj_or_bg?: string[]; size?: string }; + }; + }>(stdout); + expect(body.request?.model).toBe("wanx2.1-vace-plus"); + expect(body.request?.input?.function).toBe("image_reference"); + expect(body.request?.input?.video_url).toBeUndefined(); + expect(body.request?.input?.ref_images_url).toEqual([ + "https://example.com/a.png", + "https://example.com/b.png", + ]); + expect(body.request?.parameters?.obj_or_bg).toEqual(["obj", "bg"]); + expect(body.request?.parameters?.size).toBe("1280*720"); + }); + + test("repainting dry-run keeps strength=0 and omits unset params", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "clay", + "--video", + "https://example.com/in.mp4", + "--control-condition", + "depth", + "--strength", + "0", + "--prompt-extend", + "false", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ + endpoint?: string; + request?: { + input?: { function?: string; prompt?: string; video_url?: string }; + parameters?: { + control_condition?: string; + strength?: number; + prompt_extend?: boolean; + watermark?: boolean; + }; + }; + }>(stdout); + expect(body.endpoint).toMatch(/video-generation\/video-synthesis$/); + expect(body.request?.input?.function).toBe("video_repainting"); + expect(body.request?.parameters?.control_condition).toBe("depth"); + expect(body.request?.parameters?.strength).toBe(0); + expect(body.request?.parameters?.prompt_extend).toBe(false); + expect(body.request?.parameters?.watermark).toBeUndefined(); + }); + + test("wait mode downloads video_url for repainting", async () => { + let pollCount = 0; + const mp4Bytes = Buffer.from("vace-mp4"); + const { origin, requests } = await startServer((request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (request.method === "POST") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-vace-1", task_status: "PENDING" }, + request_id: "req-vace-1", + }), + ); + return; + } + if (url.pathname === "/api/v1/tasks/task-vace-1") { + pollCount += 1; + if (pollCount < 2) { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-vace-1", task_status: "RUNNING" }, + request_id: "req-vace-1", + }), + ); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { + task_id: "task-vace-1", + task_status: "SUCCEEDED", + video_url: `${origin}/vace.mp4`, + orig_prompt: "clay", + actual_prompt: "clay style", + }, + request_id: "req-vace-1", + }), + ); + return; + } + if (url.pathname === "/vace.mp4") { + response.writeHead(200, { "content-type": "video/mp4" }); + response.end(mp4Bytes); + return; + } + response.writeHead(404); + response.end(); + }); + + const outDir = makeE2eOutputDir("video-retouch-wait"); + tempDirs.push(outDir); + const dest = join(outDir, "vace.mp4"); + + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--base-url", + origin, + "--api-key", + "sk-test", + "--prompt", + "clay", + "--video", + "https://example.com/in.mp4", + "--control-condition", + "depth", + "--strength", + "0.8", + "--poll-interval", + "0.05", + "--timeout", + "10", + "--download", + dest, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const post = requests.find((entry) => entry.method === "POST"); + expect(post?.path).toBe("/api/v1/services/aigc/video-generation/video-synthesis"); + const posted = JSON.parse(post!.body) as { + input?: { function?: string }; + parameters?: { control_condition?: string; strength?: number }; + }; + expect(posted.input?.function).toBe("video_repainting"); + expect(posted.parameters?.control_condition).toBe("depth"); + expect(posted.parameters?.strength).toBe(0.8); + + const body = parseStdoutJson<{ task_id?: string; video_url?: string; saved?: string }>(stdout); + expect(body.task_id).toBe("task-vace-1"); + expect(body.saved).toBe(dest); + expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); + }); +}); + +const vaceLiveVideo = process.env.BAILIAN_E2E_VACE_VIDEO_URL?.trim(); + +describe.skipIf(!isBailianE2EVideoEnabled() || !isDashScopeE2EReady() || !vaceLiveVideo)( + "e2e: video retouch(DashScope live)", + () => { + test("VACE live video_repainting only (other functions unverified)", async () => { + const outDir = makeE2eOutputDir("video-retouch-live"); + const { stdout, stderr, exitCode } = await runCommandE2e(VIDEO_RETOUCH_ROUTES, [ + "video", + "retouch", + "--prompt", + "Convert the scene to claymation style", + "--function", + "video_repainting", + "--video", + vaceLiveVideo!, + "--control-condition", + "depth", + "--strength", + "0.8", + "--download", + join(outDir, "vace-live.mp4"), + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ video_url?: string }>(stdout); + expect(body.video_url?.startsWith("https://")).toBe(true); + }, 3_600_000); + }, +); diff --git a/packages/commands/tests/e2e/video-style.e2e.test.ts b/packages/commands/tests/e2e/video-style.e2e.test.ts new file mode 100644 index 00000000..4d87f800 --- /dev/null +++ b/packages/commands/tests/e2e/video-style.e2e.test.ts @@ -0,0 +1,343 @@ +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "vite-plus/test"; +import { + isBailianE2EVideoEnabled, + isDashScopeE2EReady, + makeE2eOutputDir, + parseStdoutJson, + runCommandHelp, + runCommandE2e, + runCommandInProcess, +} from "./helpers.ts"; +import { VIDEO_STYLE_ROUTES } from "./topic-routes.ts"; + +const servers: Server[] = []; +const tempDirs: string[] = []; + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }), + ), + ); + for (const tempDir of tempDirs.splice(0)) { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +async function startServer( + handler: (request: IncomingMessage, response: ServerResponse, body: string) => void, +): Promise<{ + origin: string; + requests: Array<{ + method?: string; + path: string; + headers: IncomingMessage["headers"]; + body: string; + }>; +}> { + const requests: Array<{ + method?: string; + path: string; + headers: IncomingMessage["headers"]; + body: string; + }> = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk) => chunks.push(chunk)); + request.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + requests.push({ + method: request.method, + path: url.pathname, + headers: request.headers, + body, + }); + handler(request, response, body); + }); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + servers.push(server); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected TCP address"); + return { origin: `http://127.0.0.1:${address.port}`, requests }; +} + +describe("e2e: video style", () => { + test("help shows bilingual flags and fixed model", async () => { + const { stderr, exitCode } = await runCommandHelp(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--help", + ]); + expect(exitCode, stderr).toBe(0); + expect(stderr).toMatch(/--video/); + expect(stderr).toMatch(/Style ID|风格编号/); + expect(stderr).toMatch(/video-style-transform/); + expect(stderr).not.toMatch(/--model/); + expect(stderr).not.toMatch(/--concurrent/); + }); + + test("missing video / local path / non-ASCII → 2", async () => { + const missing = await runCommandInProcess(VIDEO_STYLE_ROUTES, ["video", "style", "--quiet"]); + expect(missing.exitCode).toBe(2); + expect(missing.stderr).toMatch(/--video/i); + + const localPath = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--video", + "./clip.mp4", + ]); + expect(localPath.exitCode).toBe(2); + expect(localPath.stderr).toMatch(/public|公网|local|本地/i); + + const nonAscii = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--video", + "https://example.com/风格.mp4", + ]); + expect(nonAscii.exitCode).toBe(2); + expect(nonAscii.stderr).toMatch(/non-ASCII|非 ASCII/i); + }); + + test("dry-run preserves style=0 and boolean false", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--video", + "https://example.com/clip.mp4", + "--style", + "0", + "--fps", + "15", + "--animate-emotion", + "false", + "--min-len", + "540", + "--super-resolution", + "true", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ + endpoint?: string; + request?: { + model?: string; + input?: { video_url?: string }; + parameters?: { + style?: number; + video_fps?: number; + animate_emotion?: boolean; + min_len?: number; + use_SR?: boolean; + }; + }; + }>(stdout); + expect(body.endpoint).toMatch(/\/api\/v1\/services\/aigc\/video-generation\/video-synthesis$/); + expect(body.request?.model).toBe("video-style-transform"); + expect(body.request?.input?.video_url).toBe("https://example.com/clip.mp4"); + expect(body.request?.parameters?.style).toBe(0); + expect(body.request?.parameters?.video_fps).toBe(15); + expect(body.request?.parameters?.animate_emotion).toBe(false); + expect(body.request?.parameters?.min_len).toBe(540); + expect(body.request?.parameters?.use_SR).toBe(true); + }); + + test("wait mode continues through SUSPENDED and reads output_video_url", async () => { + let pollCount = 0; + const mp4Bytes = Buffer.from("style-mp4"); + const { origin } = await startServer((request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (request.method === "POST") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-style-1", task_status: "PENDING" }, + request_id: "req-style-1", + }), + ); + return; + } + if (url.pathname === "/api/v1/tasks/task-style-1") { + pollCount += 1; + if (pollCount < 2) { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { task_id: "task-style-1", task_status: "SUSPENDED" }, + request_id: "req-style-1", + }), + ); + return; + } + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { + task_id: "task-style-1", + task_status: "SUCCEEDED", + output_video_url: `${origin}/styled.mp4`, + }, + usage: { SR: 720 }, + request_id: "req-style-1", + }), + ); + return; + } + if (url.pathname === "/styled.mp4") { + response.writeHead(200, { "content-type": "video/mp4" }); + response.end(mp4Bytes); + return; + } + response.writeHead(404); + response.end(); + }); + + const outDir = makeE2eOutputDir("video-style-wait"); + tempDirs.push(outDir); + const dest = join(outDir, "styled.mp4"); + + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--base-url", + origin, + "--api-key", + "sk-test", + "--video", + "https://example.com/clip.mp4", + "--style", + "0", + "--poll-interval", + "0.05", + "--timeout", + "10", + "--download", + dest, + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ + task_id?: string; + video_url?: string; + output_video_url?: string; + saved?: string; + usage?: { SR?: number }; + }>(stdout); + expect(body.task_id).toBe("task-style-1"); + expect(body.video_url).toMatch(/styled\.mp4$/); + expect(body.output_video_url).toMatch(/styled\.mp4$/); + expect(body.usage?.SR).toBe(720); + expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); + }); + + test("task-get and download see output_video_url", async () => { + const mp4Bytes = Buffer.from("download-style"); + const { origin } = await startServer((request, response) => { + const url = new URL(request.url ?? "/", "http://127.0.0.1"); + if (url.pathname === "/api/v1/tasks/task-style-dl") { + response.writeHead(200, { "content-type": "application/json" }); + response.end( + JSON.stringify({ + output: { + task_id: "task-style-dl", + task_status: "SUCCEEDED", + output_video_url: `${origin}/styled.mp4`, + }, + request_id: "req-dl", + }), + ); + return; + } + if (url.pathname === "/styled.mp4") { + response.writeHead(200, { "content-type": "video/mp4" }); + response.end(mp4Bytes); + return; + } + response.writeHead(404); + response.end(); + }); + + const getResult = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "task", + "get", + "--base-url", + origin, + "--api-key", + "sk-test", + "--task-id", + "task-style-dl", + "--output", + "json", + ]); + expect(getResult.exitCode, getResult.stderr).toBe(0); + const getBody = parseStdoutJson<{ output_video_url?: string; task_status?: string }>( + getResult.stdout, + ); + expect(getBody.task_status).toBe("SUCCEEDED"); + expect(getBody.output_video_url).toMatch(/styled\.mp4$/); + + const outDir = makeE2eOutputDir("video-style-download"); + tempDirs.push(outDir); + const dest = join(outDir, "from-task.mp4"); + const dl = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "download", + "--base-url", + origin, + "--api-key", + "sk-test", + "--task-id", + "task-style-dl", + "--out", + dest, + "--output", + "json", + ]); + expect(dl.exitCode, dl.stderr).toBe(0); + expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); + }); +}); + +const styleLiveUrl = process.env.BAILIAN_E2E_VIDEO_STYLE_URL?.trim(); + +describe.skipIf(!isBailianE2EVideoEnabled() || !isDashScopeE2EReady() || !styleLiveUrl)( + "e2e: video style(DashScope live)", + () => { + test("video-style-transform live", async () => { + const outDir = makeE2eOutputDir("video-style-live"); + const { stdout, stderr, exitCode } = await runCommandE2e(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--video", + styleLiveUrl!, + "--style", + "0", + "--download", + join(outDir, "style-live.mp4"), + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ video_url?: string; output_video_url?: string }>(stdout); + expect( + body.output_video_url?.startsWith("https://") || body.video_url?.startsWith("https://"), + ).toBe(true); + }, 3_600_000); + }, +); diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts index 95c6f91f..3c3817ff 100644 --- a/packages/core/src/types/api.ts +++ b/packages/core/src/types/api.ts @@ -281,6 +281,76 @@ export interface DashScopeVideoEditRequest { }; } +/** VideoRetalk (bl video portrait) request body. */ +export interface DashScopeVideoRetalkRequest { + model: string; + input: { + video_url: string; + audio_url: string; + ref_image_url?: string; + }; + parameters?: { + video_extension?: boolean; + query_face_threshold?: number; + }; +} + +/** Video style transform (bl video style) request body. */ +export interface DashScopeVideoStyleTransformRequest { + model: string; + input: { + video_url: string; + }; + parameters?: { + style?: number; + video_fps?: number; + animate_emotion?: boolean; + min_len?: number; + use_SR?: boolean; + }; +} + +export type WanxVaceFunction = + | "video_repainting" + | "video_edit" + | "video_extension" + | "video_outpainting" + | "image_reference"; + +/** Wanx 2.1 VACE (bl video retouch) request body. */ +export interface DashScopeVideoVaceRequest { + model: string; + input: { + function: WanxVaceFunction; + prompt?: string; + video_url?: string; + ref_images_url?: string[]; + mask_image_url?: string; + mask_video_url?: string; + mask_frame_id?: number; + first_frame_url?: string; + last_frame_url?: string; + first_clip_url?: string; + last_clip_url?: string; + }; + parameters?: { + control_condition?: string; + strength?: number; + prompt_extend?: boolean; + watermark?: boolean; + seed?: number; + mask_type?: string; + expand_ratio?: number; + expand_mode?: string; + size?: string; + top_scale?: number; + bottom_scale?: number; + left_scale?: number; + right_scale?: number; + obj_or_bg?: Array<"obj" | "bg">; + }; +} + // ---- Application (Agent / Workflow) ---- export interface AppCompletionRequest { @@ -962,7 +1032,16 @@ export interface QwenMtUniOutputData { export interface DashScopeTaskResponse { output: { task_id: string; - task_status: "PENDING" | "RUNNING" | "SUCCEEDED" | "FAILED" | "UNKNOWN" | "CANCELED"; + task_status: + | "PENDING" + | "RUNNING" + | "SUCCEEDED" + | "FAILED" + | "UNKNOWN" + | "CANCELED" + | "PRE-PROCESSING" + | "POST-PROCESSING" + | "SUSPENDED"; finished?: boolean; task_metrics?: { TOTAL?: number; @@ -981,6 +1060,11 @@ export interface DashScopeTaskResponse { results?: Array<{ url: string }>; // Video generation returns video_url video_url?: string; + // video-style-transform returns output_video_url + output_video_url?: string; + // VACE / edit prompt echoes + orig_prompt?: string; + actual_prompt?: string; // Image translation (qwen-mt-image) returns image_url image_url?: string; // qwen-mt-uni business envelope (exact casing) diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 316b7d9c..38eeffb7 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -68,6 +68,10 @@ export type { DashScopeVideoEditRequest, DashScopeVideoRefRequest, DashScopeVideoRequest, + DashScopeVideoRetalkRequest, + DashScopeVideoStyleTransformRequest, + DashScopeVideoVaceRequest, + WanxVaceFunction, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 79b5ab10..1704d742 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -43,7 +43,10 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Image text translation (layout-preserving) | `bl image translate` | Default `qwen-mt-image` (async); optional `qwen-mt-image-2.0`. Not image edit. | | File multimodal translation | `bl omni translate` | `qwen-mt-uni` (async file→file). Keep `bl omni --message` for multimodal chat. | | Text-to-video / image-to-video | `bl video generate` | `wan3.0-video` | -| Video edit / style transfer | `bl video edit` | `happyhorse-1.0-video-edit` | +| Video edit (happyhorse) | `bl video edit` | `happyhorse-1.0-video-edit` — not VACE | +| Talking-head / lip sync | `bl video portrait` | Fixed `videoretalk` (no `--model`) | +| Video style transform | `bl video style` | Fixed `video-style-transform` (Beijing; public URL only in v1) | +| VACE unified video edit | `bl video retouch` | Fixed `wanx2.1-vace-plus` — five `--function` modes; distinct from `bl video edit` | | Reference-to-video + voice | `bl video ref` | `wan3.0-video` | | Speech synthesis (TTS / voiceover) | `bl speech synthesize` | `cosyvoice-v3-flash` | | Voice clone / manage | `bl speech voice clone/list/get/update/delete/preview` | CosyVoice/Qwen-Audio: `voice-enrollment` → `speech synthesize --model`. Omni (non-realtime flash/plus only): `qwen-voice-enrollment` create/list/delete → `omni --model --voice` | @@ -53,6 +56,8 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Image describe | `bl vision describe` | `qwen3-vl-plus`;宿主能做且未点名 → host-first | | Video / A-V understand | `bl vision describe --video` 或 `bl omni` | 视频理解默认走百炼;`omni` 默认 `qwen3.8-omni-flash`,省略 `--model` 且无 `--text-only` 时自动切换 `qwen3.5-omni-plus` | +`bl video edit` vs `bl video retouch`: edit uses happyhorse for general style/object edits; retouch is Wan 2.1 VACE with `--function` (`video_repainting` / `video_edit` / `video_extension` / `video_outpainting` / `image_reference`). They are not interchangeable. `bl video portrait` is lip-sync (videoretalk); `bl video style` is comic/ink style transform. VACE / style outputs are silent MP4. Portrait and style do not expose `--model`. + Unless the user explicitly specifies a model, omit `--model` and let the CLI use the active Profile’s default. For ASR model selection, keep `fun-asr` (or other `*-filetrans`) for long recordings, repeated files, speaker diarization, or asynchronous task IDs. For one local or remote audio file up to about five minutes when the user asks for low-latency Flash models, use `--model fun-asr-flash-2026-06-15`, `--model qwen-audio-3.0-asr-flash`, or `--model qwen3-asr-flash`. Flash recognition is synchronous and accepts exactly one file per call. diff --git a/skills/bailian-gen/reference/index.md b/skills/bailian-gen/reference/index.md index 85758739..b23bd94e 100644 --- a/skills/bailian-gen/reference/index.md +++ b/skills/bailian-gen/reference/index.md @@ -34,7 +34,10 @@ Use this index for the skill-scoped quick index and global flags. | `bl video download` | API Key | Download a completed video by task ID | [video.md](video.md) | | `bl video edit` | API Key | Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.) | [video.md](video.md) | | `bl video generate` | API Key | Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v) | [video.md](video.md) | +| `bl video portrait` | API Key | Drive a talking-head video with audio (VideoRetalk / videoretalk) | [video.md](video.md) | | `bl video ref` | API Key | Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice | [video.md](video.md) | +| `bl video retouch` | API Key | Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference) | [video.md](video.md) | +| `bl video style` | API Key | Restyle a video (video-style-transform) | [video.md](video.md) | | `bl video task get` | API Key | Query async task status | [video.md](video.md) | | `bl vision describe` | API Key | Describe an image or video using Qwen-VL | [vision.md](vision.md) | @@ -45,7 +48,7 @@ Use this index for the skill-scoped quick index and global flags. | `image` | `edit`, `generate`, `translate` | [image.md](image.md) | | `omni` | `(root)`, `translate` | [omni.md](omni.md) | | `speech` | `generate`, `recognize`, `synthesize`, `vocabulary create`, `vocabulary delete`, `vocabulary get`, `vocabulary list`, `vocabulary update`, `voice clone`, `voice delete`, `voice design`, `voice get`, `voice list`, `voice preview`, `voice update` | [speech.md](speech.md) | -| `video` | `download`, `edit`, `generate`, `ref`, `task get` | [video.md](video.md) | +| `video` | `download`, `edit`, `generate`, `portrait`, `ref`, `retouch`, `style`, `task get` | [video.md](video.md) | | `vision` | `describe` | [vision.md](vision.md) | ## Global flags diff --git a/skills/bailian-gen/reference/video.md b/skills/bailian-gen/reference/video.md index 6ea7e423..4b49ef77 100644 --- a/skills/bailian-gen/reference/video.md +++ b/skills/bailian-gen/reference/video.md @@ -12,7 +12,10 @@ Index: [index.md](index.md) | `bl video download` | API Key | Download a completed video by task ID | | `bl video edit` | API Key | Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.) | | `bl video generate` | API Key | Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v) | +| `bl video portrait` | API Key | Drive a talking-head video with audio (VideoRetalk / videoretalk) | | `bl video ref` | API Key | Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice | +| `bl video retouch` | API Key | Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference) | +| `bl video style` | API Key | Restyle a video (video-style-transform) | | `bl video task get` | API Key | Query async task status | ## Command details @@ -161,6 +164,44 @@ bl video generate --prompt "A cat playing with a ball" --watermark false bl video generate --prime --workspace-id --model wan3.0-video-prime --prompt "Ocean waves at sunset" ``` +### `bl video portrait` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------------- | +| **Name** | `video portrait` | +| **Description** | Drive a talking-head video with audio (VideoRetalk / videoretalk) | +| **Authentication** | API Key | +| **Usage** | `bl video portrait --video --audio [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------- | ------- | -------- | ------------------------------------------------------------------------------------------ | +| `--video ` | string | yes | Input video URL or local file (mp4/avi/mov) | +| `--audio ` | string | yes | Driving audio URL or local file (wav/mp3/aac) | +| `--ref-image ` | string | no | Optional reference face image when the video has multiple people | +| `--video-extension ` | boolean | no | Extend video by alternating reverse/forward playback when audio is longer (default: false) | +| `--face-threshold ` | number | no | Face match threshold 120–200 (default: 170; only with --ref-image) | +| `--download ` | string | no | Save video to file on completion (default: output dir) | +| `--async` | switch | no | Return async task id without waiting | +| `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Fixed model videoretalk (Beijing). Supports temporary OSS upload for local media. Requires model access on the account. + +#### Examples + +```bash +bl video portrait --video https://example.com/face.mp4 --audio https://example.com/speech.wav --download out.mp4 +``` + +```bash +bl video portrait --video ./face.mp4 --audio ./speech.wav --ref-image ./person.jpg --face-threshold 170 +``` + ### `bl video ref` | Field | Value | @@ -215,6 +256,107 @@ bl video ref --prompt "Image 1 and Image 2 have a conversation" --image a.jpg -- bl video ref --prompt "Image 1 drinks water" --image person.jpg --watermark false ``` +### `bl video retouch` + +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------------------- | +| **Name** | `video retouch` | +| **Description** | Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference) | +| **Authentication** | API Key | +| **Usage** | `bl video retouch --prompt [--function ] [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------------------------------------------------------------------------------------ | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- | +| `--prompt ` | string | yes | Edit / generation prompt (max 800 characters; server may truncate) | +| `--function ` | string | no | VACE function: video_repainting (default), video_edit, video_extension, video_outpainting, image_reference | +| `--video ` | string | no | Input video URL or local file (required for most functions) | +| `--ref-image ` | array | no | Reference image(s): image_reference 1–3; video_repainting/video_edit at most 1; unsupported for video_extension/video_outpainting | +| `--control-condition ` | string | no | Control condition (required for video_repainting; posebodyface/posebody/depth/scribble) | +| `--strength ` | number | no | Repaint strength in [0, 1] | +| `--seed ` | number | no | Random seed | +| `--prompt-extend ` | boolean | no | Enable prompt extend (true/false). Omit flag to omit the parameter (DashScope default). | +| `--watermark ` | boolean | no | Enable watermark (true/false). Omit flag to use the Profile setting or CLI default (true). | +| `--mask-image ` | string | no | Mask image for video_edit (mutually exclusive with --mask-video) | +| `--mask-video ` | string | no | Mask video for video_edit (mutually exclusive with --mask-image) | +| `--mask-frame-id ` | number | no | Mask frame id starting at 1 (video_edit) | +| `--mask-type ` | string | no | Mask type: tracking or fixed (video_edit) | +| `--expand-ratio ` | number | no | Expand ratio in [0, 1] (video_edit) | +| `--expand-mode ` | string | no | Expand mode hull/bbox/original (image mask + tracking only) | +| `--first-frame ` | string | no | First-frame image for video_extension (extends forward) | +| `--last-frame ` | string | no | Last-frame image for video_extension (extends backward) | +| `--first-clip ` | string | no | First clip for video_extension (extends forward) | +| `--last-clip ` | string | no | Last clip for video_extension (extends backward) | +| `--top-scale ` | number | no | Outpainting top scale in [1, 2] (1 = no expand) | +| `--bottom-scale ` | number | no | Outpainting bottom scale in [1, 2] | +| `--left-scale ` | number | no | Outpainting left scale in [1, 2] | +| `--right-scale ` | number | no | Outpainting right scale in [1, 2] | +| `--ref-role ` | array | no | Per-image role for image_reference (obj or bg; at most one bg) | +| `--size ` | string | no | Output size for image_reference / video_edit (1280*720, 720*1280, 960*960, 832*1088, 1088*832) | +| `--download ` | string | no | Save video to file on completion (default: output dir) | +| `--async` | switch | no | Return async task id without waiting | +| `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Fixed model wanx2.1-vace-plus (Beijing/Singapore). Distinct from `video edit` (happyhorse). Output is silent MP4. video_extension: first-frame/clip extends forward, last-frame/clip extends backward; total output is 5s. Requires model access. Do not use a boolean --video-extension alias. + +#### Examples + +```bash +bl video retouch --prompt "Convert the scene to claymation" --function video_repainting --video https://example.com/in.mp4 --control-condition depth --strength 0.8 +``` + +```bash +bl video retouch --prompt "Extend the shot" --function video_extension --first-frame https://example.com/first.png +``` + +```bash +bl video retouch --prompt "Generate from references" --function image_reference --ref-image https://example.com/a.png --ref-image https://example.com/b.png --ref-role obj --ref-role bg --size 1280*720 +``` + +### `bl video style` + +| Field | Value | +| ------------------ | --------------------------------------- | +| **Name** | `video style` | +| **Description** | Restyle a video (video-style-transform) | +| **Authentication** | API Key | +| **Usage** | `bl video style --video [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--video ` | string | yes | Input video public URL (local paths not supported in v1) | +| `--style ` | number | no | Style ID 0–7 (default: 0). 0 Japanese comic, 1 American comic, 2 fresh comic, 3 3D cartoon, 4 Chinese cartoon, 5 paper art, 6 simple illustration, 7 Chinese ink | +| `--fps ` | number | no | Output video FPS 15–25 (maps to video_fps) | +| `--animate-emotion ` | boolean | no | Animate facial emotion (server default: true) | +| `--min-len ` | number | no | Short-side length 540 or 720 (server default: 720) | +| `--super-resolution ` | boolean | no | Enable super-resolution (maps to use_SR; server default: false) | +| `--download ` | string | no | Save video to file on completion (default: output dir) | +| `--async` | switch | no | Return async task id without waiting | +| `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Fixed model video-style-transform (Beijing only). Success field is output.output_video_url. Local paths are rejected until temporary OSS support is verified. Requires model access. + +#### Examples + +```bash +bl video style --video https://example.com/clip.mp4 --style 0 --download styled.mp4 +``` + +```bash +bl video style --video https://example.com/clip.mp4 --style 4 --fps 15 --min-len 540 --super-resolution true +``` + ### `bl video task get` | Field | Value | From e14bf32e48950d86b94cc13a1db5b07b34cd49a7 Mon Sep 17 00:00:00 2001 From: clh02467605 Date: Wed, 25 Nov 2026 12:59:31 +0800 Subject: [PATCH 2/2] feat(video): introduce video retalk command and remove video retouch command - Added a new command `video retalk` for generating talking-head videos driven by audio. - Updated command references in the CLI and documentation to reflect the new command. - Removed the deprecated `video retouch` command and its associated tests. - Enhanced error handling and validation for the new command's flags. --- packages/cli/src/commands.ts | 6 +- .../src/commands/shared/dashscope-task.ts | 65 +- packages/commands/src/commands/video/edit.ts | 5 +- .../commands/video/{portrait.ts => retalk.ts} | 45 +- .../commands/src/commands/video/retouch.ts | 848 ------------------ .../src/commands/video/specialized-shared.ts | 191 +++- packages/commands/src/commands/video/style.ts | 55 +- .../commands/src/commands/video/task-get.ts | 2 - packages/commands/src/index.ts | 3 +- packages/commands/tests/e2e/topic-routes.ts | 13 +- ...t.e2e.test.ts => video-retalk.e2e.test.ts} | 181 ++-- .../tests/e2e/video-retouch.e2e.test.ts | 382 -------- .../tests/e2e/video-style.e2e.test.ts | 42 +- packages/core/src/types/api.ts | 46 +- packages/core/src/types/index.ts | 2 - packages/runtime/src/utils/polling.ts | 5 +- skills/bailian-gen/SKILL.md | 9 +- skills/bailian-gen/reference/index.md | 63 +- skills/bailian-gen/reference/video.md | 159 +--- 19 files changed, 519 insertions(+), 1603 deletions(-) rename packages/commands/src/commands/video/{portrait.ts => retalk.ts} (81%) delete mode 100644 packages/commands/src/commands/video/retouch.ts rename packages/commands/tests/e2e/{video-portrait.e2e.test.ts => video-retalk.e2e.test.ts} (66%) delete mode 100644 packages/commands/tests/e2e/video-retouch.e2e.test.ts diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 38950f81..d090ea19 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -21,9 +21,8 @@ import { videoGenerate, videoEdit, videoRef, - videoPortrait, + videoRetalk, videoStyle, - videoRetouch, videoTaskGet, videoDownload, visionDescribe, @@ -417,9 +416,8 @@ export const commands: Record = { "video generate": videoGenerate, "video edit": videoEdit, "video ref": videoRef, - "video portrait": videoPortrait, + "video retalk": videoRetalk, "video style": videoStyle, - "video retouch": videoRetouch, "video task get": videoTaskGet, "video download": videoDownload, "vision describe": visionDescribe, diff --git a/packages/commands/src/commands/shared/dashscope-task.ts b/packages/commands/src/commands/shared/dashscope-task.ts index 1a8bdfbc..775c5b0c 100644 --- a/packages/commands/src/commands/shared/dashscope-task.ts +++ b/packages/commands/src/commands/shared/dashscope-task.ts @@ -33,6 +33,26 @@ function isTimeoutLikeError(error: unknown): boolean { return false; } +function joinHints(...parts: Array): string | undefined { + const joined = parts + .map((part) => part?.trim()) + .filter((part): part is string => Boolean(part)) + .join(" "); + return joined.length > 0 ? joined : undefined; +} + +/** + * Terminal FAILED/CANCELED/UNKNOWN thrown from load() set api without httpStatus. + * HTTP failures from the poll GET go through mapApiError and set api.httpStatus. + */ +function isTerminalTaskStatusError(error: BailianError): boolean { + return ( + error.exitCode === ExitCode.GENERAL && + error.api !== undefined && + error.api.httpStatus === undefined + ); +} + /** Poll a DashScope async task until SUCCEEDED, FAILED, CANCELED, or UNKNOWN. */ export async function pollDashScopeTask( ctx: { @@ -48,6 +68,15 @@ export async function pollDashScopeTask( extraCheck?: (data: DashScopeTaskResponse) => void; }, ): Promise { + const pollInterruptHint = ctx.localize({ + "en-US": `Task may still be running. Query or re-download with task_id ${taskId}; do not resubmit.`, + "zh-CN": `任务可能仍在执行。请用 task_id ${taskId} 查询或重新下载,勿重新提交。`, + }); + const terminalHint = ctx.localize({ + "en-US": `Inspect with task_id ${taskId}.`, + "zh-CN": `可用 task_id ${taskId} 查询任务。`, + }); + try { return await poll(ctx.client, { output: ctx.output, @@ -93,22 +122,42 @@ export async function pollDashScopeTask( getStatus: (data) => (data as DashScopeTaskResponse).output.task_status, }); } catch (error) { - // Include submitted task_id for both poll-loop TIMEOUT and hung single GETs (AbortError). + // Keep messages intact for AEM; put task_id only in hint (timeout / interrupt / terminal). if (isTimeoutLikeError(error)) { throw new BailianError( ctx.localize({ - "en-US": `Polling timed out. task_id=${taskId}`, - "zh-CN": `轮询超时。task_id=${taskId}`, + "en-US": "Polling timed out.", + "zh-CN": "轮询超时。", }), ExitCode.TIMEOUT, - ctx.localize({ - "en-US": `Try increasing --timeout, or query the task with id ${taskId}.`, - "zh-CN": `可增大 --timeout,或用 task_id ${taskId} 查询任务状态。`, - }), + joinHints( + ctx.localize({ + "en-US": `Try increasing --timeout, or query the task with id ${taskId}.`, + "zh-CN": `可增大 --timeout,或用 task_id ${taskId} 查询任务状态。`, + }), + pollInterruptHint, + ), { cause: error }, ); } - throw error; + if (error instanceof BailianError) { + if (isTerminalTaskStatusError(error)) { + throw new BailianError(error.message, error.exitCode, joinHints(error.hint, terminalHint), { + cause: error.cause ?? error, + api: error.api, + rawResponse: error.rawResponse, + }); + } + // Poll interrupt: preserve message; append do-not-resubmit hint (includes task_id). + throw new BailianError( + error.message, + error.exitCode, + joinHints(error.hint, pollInterruptHint), + { cause: error.cause ?? error, api: error.api, rawResponse: error.rawResponse }, + ); + } + const originalMessage = error instanceof Error ? error.message : String(error); + throw new BailianError(originalMessage, ExitCode.GENERAL, pollInterruptHint, { cause: error }); } } diff --git a/packages/commands/src/commands/video/edit.ts b/packages/commands/src/commands/video/edit.ts index 87c022de..0b4764b8 100644 --- a/packages/commands/src/commands/video/edit.ts +++ b/packages/commands/src/commands/video/edit.ts @@ -21,8 +21,9 @@ import { BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_WATERMARK } from "bailia export default defineCommand({ description: { "en-US": - "Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.)", - "zh-CN": "使用 happyhorse-1.0-video-edit 编辑视频(风格转换、对象替换等)", + "Edit a video with happyhorse-1.0-video-edit (prompt-based style/object edits; preset comic/ink restyle → video style)", + "zh-CN": + "使用 happyhorse-1.0-video-edit 编辑视频(基于提示词的风格/对象编辑;预设漫画/水墨重绘请用 video style)", }, auth: "apiKey", usageArgs: "--video --prompt [flags]", diff --git a/packages/commands/src/commands/video/portrait.ts b/packages/commands/src/commands/video/retalk.ts similarity index 81% rename from packages/commands/src/commands/video/portrait.ts rename to packages/commands/src/commands/video/retalk.ts index dce3ad3d..6da39679 100644 --- a/packages/commands/src/commands/video/portrait.ts +++ b/packages/commands/src/commands/video/retalk.ts @@ -1,7 +1,6 @@ import { defineCommand, image2videoPath, - ASYNC_FLAG, stripUndefined, type DashScopeVideoRetalkRequest, type FlagsDef, @@ -12,11 +11,13 @@ import { previewMediaUrl, resolveMediaUrl, runSpecializedVideoLifecycle, + SPECIALIZED_VIDEO_SHARED_FLAGS, + specializedLifecycleFlagError, } from "./specialized-shared.ts"; const MODEL = "videoretalk"; -const PORTRAIT_FLAGS = { +const RETALK_FLAGS = { video: { type: "string", valueHint: "", @@ -60,33 +61,17 @@ const PORTRAIT_FLAGS = { "zh-CN": "人脸匹配阈值 120–200(默认 170;仅与 --ref-image 联用)", }, }, - download: { - type: "string", - valueHint: "", - description: { - "en-US": "Save video to file on completion (default: output dir)", - "zh-CN": "完成后将视频保存到文件(默认输出目录)", - }, - }, - ...ASYNC_FLAG, - pollInterval: { - type: "number", - valueHint: "", - description: { - "en-US": "Polling interval when waiting (default: 15)", - "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", - }, - }, + ...SPECIALIZED_VIDEO_SHARED_FLAGS, } satisfies FlagsDef; export default defineCommand({ description: { - "en-US": "Drive a talking-head video with audio (VideoRetalk / videoretalk)", - "zh-CN": "用音频驱动人像口型视频(VideoRetalk / videoretalk)", + "en-US": "Drive a talking-head video with audio (VideoRetalk)", + "zh-CN": "用音频驱动人像口型视频(VideoRetalk)", }, auth: "apiKey", usageArgs: "--video --audio [flags]", - flags: PORTRAIT_FLAGS, + flags: RETALK_FLAGS, exampleArgs: [ { "en-US": @@ -104,20 +89,14 @@ export default defineCommand({ notes: [ { "en-US": - "Fixed model videoretalk (Beijing). Supports temporary OSS upload for local media. Requires model access on the account.", - "zh-CN": "固定模型 videoretalk(北京)。本地媒体支持临时 OSS 上传。需账号已开通该模型权限。", + "Fixed model videoretalk (Beijing only). Wait-mode polling uses at least 600s (--timeout lower values are raised).", + "zh-CN": + "固定模型 videoretalk(仅北京)。等待模式轮询至少 600 秒(更小的 --timeout 会被抬高)。", }, ], validate: (flags) => { - if ( - flags.pollInterval !== undefined && - (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) - ) { - return { - "en-US": "--poll-interval must be a positive number.", - "zh-CN": "--poll-interval 必须为正数。", - }; - } + const sharedError = specializedLifecycleFlagError(flags); + if (sharedError) return sharedError; if (flags.faceThreshold !== undefined) { if ( !Number.isInteger(flags.faceThreshold) || diff --git a/packages/commands/src/commands/video/retouch.ts b/packages/commands/src/commands/video/retouch.ts deleted file mode 100644 index 597252d8..00000000 --- a/packages/commands/src/commands/video/retouch.ts +++ /dev/null @@ -1,848 +0,0 @@ -import { - defineCommand, - videoGeneratePath, - ASYNC_FLAG, - stripUndefined, - type DashScopeVideoVaceRequest, - type FlagsDef, - type LocalizedText, - type WanxVaceFunction, -} from "bailian-cli-core"; -import { BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_WATERMARK } from "bailian-cli-runtime"; -import { - extractVideoUrlField, - mediaInputError, - previewMediaUrl, - resolveMediaUrl, - runSpecializedVideoLifecycle, -} from "./specialized-shared.ts"; - -const MODEL = "wanx2.1-vace-plus"; -const DEFAULT_FUNCTION: WanxVaceFunction = "video_repainting"; - -const VACE_FUNCTIONS = new Set([ - "video_repainting", - "video_edit", - "video_extension", - "video_outpainting", - "image_reference", -]); - -const REPAINT_CONTROL = new Set(["posebodyface", "posebody", "depth", "scribble"]); -const EDIT_CONTROL = new Set(["", "posebodyface", "depth"]); -const EXTENSION_CONTROL = new Set(["posebodyface", "depth"]); -const MASK_TYPES = new Set(["tracking", "fixed"]); -const EXPAND_MODES = new Set(["hull", "bbox", "original"]); -const ALLOWED_SIZES = new Set(["1280*720", "720*1280", "960*960", "832*1088", "1088*832"]); - -const RETOUCH_FLAGS = { - prompt: { - type: "string", - valueHint: "", - description: { - "en-US": "Edit / generation prompt (max 800 characters; server may truncate)", - "zh-CN": "编辑/生成提示词(最多 800 字符;服务端可能截断)", - }, - required: true, - }, - function: { - type: "string", - valueHint: "", - description: { - "en-US": - "VACE function: video_repainting (default), video_edit, video_extension, video_outpainting, image_reference", - "zh-CN": - "VACE 模式:video_repainting(默认)、video_edit、video_extension、video_outpainting、image_reference", - }, - choices: [ - "video_repainting", - "video_edit", - "video_extension", - "video_outpainting", - "image_reference", - ] as const, - }, - video: { - type: "string", - valueHint: "", - description: { - "en-US": "Input video URL or local file (required for most functions)", - "zh-CN": "输入视频 URL 或本地文件(多数模式必填)", - }, - }, - refImage: { - type: "array", - valueHint: "", - description: { - "en-US": - "Reference image(s): image_reference 1–3; video_repainting/video_edit at most 1; unsupported for video_extension/video_outpainting", - "zh-CN": - "参考图:image_reference 1–3 张;video_repainting/video_edit 最多 1 张;video_extension/video_outpainting 不支持", - }, - }, - controlCondition: { - type: "string", - valueHint: "", - description: { - "en-US": - "Control condition (required for video_repainting; posebodyface/posebody/depth/scribble)", - "zh-CN": "控制条件(video_repainting 必填;posebodyface/posebody/depth/scribble)", - }, - }, - strength: { - type: "number", - valueHint: "", - description: { - "en-US": "Repaint strength in [0, 1]", - "zh-CN": "重绘强度,范围 [0, 1]", - }, - }, - seed: { - type: "number", - valueHint: "", - description: { - "en-US": "Random seed", - "zh-CN": "随机种子", - }, - }, - promptExtend: { - type: "boolean", - valueHint: "", - description: BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, - }, - watermark: { - type: "boolean", - valueHint: "", - description: BOOL_FLAG_WATERMARK, - }, - maskImage: { - type: "string", - valueHint: "", - description: { - "en-US": "Mask image for video_edit (mutually exclusive with --mask-video)", - "zh-CN": "video_edit 的掩码图(与 --mask-video 二选一)", - }, - }, - maskVideo: { - type: "string", - valueHint: "", - description: { - "en-US": "Mask video for video_edit (mutually exclusive with --mask-image)", - "zh-CN": "video_edit 的掩码视频(与 --mask-image 二选一)", - }, - }, - maskFrameId: { - type: "number", - valueHint: "", - description: { - "en-US": "Mask frame id starting at 1 (video_edit)", - "zh-CN": "掩码帧序号,从 1 起(video_edit)", - }, - }, - maskType: { - type: "string", - valueHint: "", - description: { - "en-US": "Mask type: tracking or fixed (video_edit)", - "zh-CN": "掩码类型:tracking 或 fixed(video_edit)", - }, - choices: ["tracking", "fixed"] as const, - }, - expandRatio: { - type: "number", - valueHint: "", - description: { - "en-US": "Expand ratio in [0, 1] (video_edit)", - "zh-CN": "扩展比例 [0, 1](video_edit)", - }, - }, - expandMode: { - type: "string", - valueHint: "", - description: { - "en-US": "Expand mode hull/bbox/original (image mask + tracking only)", - "zh-CN": "扩展模式 hull/bbox/original(仅图像掩码 + tracking)", - }, - choices: ["hull", "bbox", "original"] as const, - }, - firstFrame: { - type: "string", - valueHint: "", - description: { - "en-US": "First-frame image for video_extension (extends forward)", - "zh-CN": "video_extension 首帧图(向后延展)", - }, - }, - lastFrame: { - type: "string", - valueHint: "", - description: { - "en-US": "Last-frame image for video_extension (extends backward)", - "zh-CN": "video_extension 尾帧图(向前延展)", - }, - }, - firstClip: { - type: "string", - valueHint: "", - description: { - "en-US": "First clip for video_extension (extends forward)", - "zh-CN": "video_extension 首片段(向后延展)", - }, - }, - lastClip: { - type: "string", - valueHint: "", - description: { - "en-US": "Last clip for video_extension (extends backward)", - "zh-CN": "video_extension 尾片段(向前延展)", - }, - }, - topScale: { - type: "number", - valueHint: "", - description: { - "en-US": "Outpainting top scale in [1, 2] (1 = no expand)", - "zh-CN": "画面扩展上边比例 [1, 2](1 不扩展)", - }, - }, - bottomScale: { - type: "number", - valueHint: "", - description: { - "en-US": "Outpainting bottom scale in [1, 2]", - "zh-CN": "画面扩展下边比例 [1, 2]", - }, - }, - leftScale: { - type: "number", - valueHint: "", - description: { - "en-US": "Outpainting left scale in [1, 2]", - "zh-CN": "画面扩展左边比例 [1, 2]", - }, - }, - rightScale: { - type: "number", - valueHint: "", - description: { - "en-US": "Outpainting right scale in [1, 2]", - "zh-CN": "画面扩展右边比例 [1, 2]", - }, - }, - refRole: { - type: "array", - valueHint: "", - description: { - "en-US": "Per-image role for image_reference (obj or bg; at most one bg)", - "zh-CN": "image_reference 每张图的角色(obj 或 bg;最多一个 bg)", - }, - }, - size: { - type: "string", - valueHint: "", - description: { - "en-US": - "Output size for image_reference / video_edit (1280*720, 720*1280, 960*960, 832*1088, 1088*832)", - "zh-CN": - "image_reference / video_edit 输出尺寸(1280*720、720*1280、960*960、832*1088、1088*832)", - }, - }, - download: { - type: "string", - valueHint: "", - description: { - "en-US": "Save video to file on completion (default: output dir)", - "zh-CN": "完成后将视频保存到文件(默认输出目录)", - }, - }, - ...ASYNC_FLAG, - pollInterval: { - type: "number", - valueHint: "", - description: { - "en-US": "Polling interval when waiting (default: 15)", - "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", - }, - }, -} satisfies FlagsDef; - -type RetouchFlags = { - prompt: string; - function?: WanxVaceFunction; - video?: string; - refImage?: string[]; - controlCondition?: string; - strength?: number; - seed?: number; - promptExtend?: boolean; - watermark?: boolean; - maskImage?: string; - maskVideo?: string; - maskFrameId?: number; - maskType?: string; - expandRatio?: number; - expandMode?: string; - firstFrame?: string; - lastFrame?: string; - firstClip?: string; - lastClip?: string; - topScale?: number; - bottomScale?: number; - leftScale?: number; - rightScale?: number; - refRole?: string[]; - size?: string; - download?: string; - async?: boolean; - pollInterval?: number; -}; - -function resolveFunction(flags: RetouchFlags): WanxVaceFunction { - return flags.function ?? DEFAULT_FUNCTION; -} - -function rejectFlagsError( - present: Array<[string, unknown]>, - mode: WanxVaceFunction, -): LocalizedText | undefined { - const used = present.filter(([, value]) => value !== undefined); - if (used.length === 0) return undefined; - const names = used.map(([name]) => name).join(", "); - return { - "en-US": `Flags not applicable to --function ${mode}: ${names}.`, - "zh-CN": `以下参数不适用于 --function ${mode}:${names}。`, - }; -} - -function scaleError(value: number | undefined, flagName: string): LocalizedText | undefined { - if (value === undefined) return undefined; - if (!(value >= 1 && value <= 2) || !Number.isFinite(value)) { - return { - "en-US": `${flagName} must be in [1, 2].`, - "zh-CN": `${flagName} 必须在 [1, 2] 范围内。`, - }; - } - return undefined; -} - -/** Mode / media / cross-flag checks for validate (before auth). */ -function validateRetouchFlags(flags: RetouchFlags): LocalizedText | undefined { - if ( - flags.pollInterval !== undefined && - (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) - ) { - return { - "en-US": "--poll-interval must be a positive number.", - "zh-CN": "--poll-interval 必须为正数。", - }; - } - - const mode = resolveFunction(flags); - if (!VACE_FUNCTIONS.has(mode)) { - return { - "en-US": `Unsupported --function "${String(flags.function)}".`, - "zh-CN": `不支持的 --function "${String(flags.function)}"。`, - }; - } - - const refImages = flags.refImage ?? []; - for (const image of refImages) { - const refError = mediaInputError(image, "--ref-image", { allowLocal: true }); - if (refError) return refError; - } - - const mediaFlags: Array<[string, string | undefined]> = [ - ["--video", flags.video], - ["--mask-image", flags.maskImage], - ["--mask-video", flags.maskVideo], - ["--first-frame", flags.firstFrame], - ["--last-frame", flags.lastFrame], - ["--first-clip", flags.firstClip], - ["--last-clip", flags.lastClip], - ]; - for (const [name, value] of mediaFlags) { - if (value !== undefined) { - const mediaError = mediaInputError(value, name, { allowLocal: true }); - if (mediaError) return mediaError; - } - } - - switch (mode) { - case "video_repainting": { - const rejected = rejectFlagsError( - [ - ["--mask-image", flags.maskImage], - ["--mask-video", flags.maskVideo], - ["--mask-frame-id", flags.maskFrameId], - ["--mask-type", flags.maskType], - ["--expand-ratio", flags.expandRatio], - ["--expand-mode", flags.expandMode], - ["--first-frame", flags.firstFrame], - ["--last-frame", flags.lastFrame], - ["--first-clip", flags.firstClip], - ["--last-clip", flags.lastClip], - ["--top-scale", flags.topScale], - ["--bottom-scale", flags.bottomScale], - ["--left-scale", flags.leftScale], - ["--right-scale", flags.rightScale], - ["--ref-role", flags.refRole], - ["--size", flags.size], - ], - mode, - ); - if (rejected) return rejected; - if (!flags.video) { - return { - "en-US": "--video is required for video_repainting.", - "zh-CN": "video_repainting 需要 --video。", - }; - } - if (!flags.controlCondition || !REPAINT_CONTROL.has(flags.controlCondition)) { - return { - "en-US": - "--control-condition is required for video_repainting (posebodyface/posebody/depth/scribble).", - "zh-CN": - "video_repainting 需要 --control-condition(posebodyface/posebody/depth/scribble)。", - }; - } - if (refImages.length > 1) { - return { - "en-US": "video_repainting accepts at most one --ref-image.", - "zh-CN": "video_repainting 最多一张 --ref-image。", - }; - } - if ( - flags.strength !== undefined && - (!(flags.strength >= 0 && flags.strength <= 1) || !Number.isFinite(flags.strength)) - ) { - return { - "en-US": "--strength must be in [0, 1].", - "zh-CN": "--strength 必须在 [0, 1] 范围内。", - }; - } - return undefined; - } - case "video_edit": { - const rejected = rejectFlagsError( - [ - ["--first-frame", flags.firstFrame], - ["--last-frame", flags.lastFrame], - ["--first-clip", flags.firstClip], - ["--last-clip", flags.lastClip], - ["--top-scale", flags.topScale], - ["--bottom-scale", flags.bottomScale], - ["--left-scale", flags.leftScale], - ["--right-scale", flags.rightScale], - ["--ref-role", flags.refRole], - ["--strength", flags.strength], - ], - mode, - ); - if (rejected) return rejected; - if (!flags.video) { - return { - "en-US": "--video is required for video_edit.", - "zh-CN": "video_edit 需要 --video。", - }; - } - const hasMaskImage = flags.maskImage !== undefined; - const hasMaskVideo = flags.maskVideo !== undefined; - if (hasMaskImage === hasMaskVideo) { - return { - "en-US": "video_edit requires exactly one of --mask-image or --mask-video.", - "zh-CN": "video_edit 需要在 --mask-image 与 --mask-video 中二选一。", - }; - } - if (refImages.length > 1) { - return { - "en-US": "video_edit accepts at most one --ref-image.", - "zh-CN": "video_edit 最多一张 --ref-image。", - }; - } - if (flags.controlCondition !== undefined && !EDIT_CONTROL.has(flags.controlCondition)) { - return { - "en-US": "--control-condition for video_edit must be empty, posebodyface, or depth.", - "zh-CN": "video_edit 的 --control-condition 只能是空、posebodyface 或 depth。", - }; - } - if (flags.maskType !== undefined && !MASK_TYPES.has(flags.maskType)) { - return { - "en-US": "--mask-type must be tracking or fixed.", - "zh-CN": "--mask-type 必须是 tracking 或 fixed。", - }; - } - if ( - flags.expandRatio !== undefined && - (!(flags.expandRatio >= 0 && flags.expandRatio <= 1) || !Number.isFinite(flags.expandRatio)) - ) { - return { - "en-US": "--expand-ratio must be in [0, 1].", - "zh-CN": "--expand-ratio 必须在 [0, 1] 范围内。", - }; - } - if (flags.expandMode !== undefined) { - if (!EXPAND_MODES.has(flags.expandMode)) { - return { - "en-US": "--expand-mode must be hull, bbox, or original.", - "zh-CN": "--expand-mode 必须是 hull、bbox 或 original。", - }; - } - if (!(hasMaskImage && flags.maskType === "tracking")) { - return { - "en-US": "--expand-mode is only valid with --mask-image and --mask-type tracking.", - "zh-CN": "--expand-mode 仅在 --mask-image 且 --mask-type tracking 时可用。", - }; - } - } - if ( - flags.maskFrameId !== undefined && - (!Number.isInteger(flags.maskFrameId) || flags.maskFrameId < 1) - ) { - return { - "en-US": "--mask-frame-id must be an integer >= 1.", - "zh-CN": "--mask-frame-id 必须是大于等于 1 的整数。", - }; - } - if (flags.size !== undefined && !ALLOWED_SIZES.has(flags.size)) { - return { - "en-US": "--size must be one of 1280*720, 720*1280, 960*960, 832*1088, 1088*832.", - "zh-CN": "--size 必须是 1280*720、720*1280、960*960、832*1088、1088*832 之一。", - }; - } - return undefined; - } - case "video_extension": { - const rejected = rejectFlagsError( - [ - ["--mask-image", flags.maskImage], - ["--mask-video", flags.maskVideo], - ["--mask-frame-id", flags.maskFrameId], - ["--mask-type", flags.maskType], - ["--expand-ratio", flags.expandRatio], - ["--expand-mode", flags.expandMode], - ["--top-scale", flags.topScale], - ["--bottom-scale", flags.bottomScale], - ["--left-scale", flags.leftScale], - ["--right-scale", flags.rightScale], - ["--ref-role", flags.refRole], - ["--size", flags.size], - ["--strength", flags.strength], - ["--ref-image", flags.refImage], - ], - mode, - ); - if (rejected) return rejected; - const mediaCount = [ - flags.video, - flags.firstFrame, - flags.lastFrame, - flags.firstClip, - flags.lastClip, - ].filter((value) => value !== undefined).length; - if (mediaCount < 1) { - return { - "en-US": - "video_extension requires at least one of --video, --first-frame, --last-frame, --first-clip, --last-clip.", - "zh-CN": - "video_extension 需要在 --video / --first-frame / --last-frame / --first-clip / --last-clip 中至少提供一项。", - }; - } - if (flags.video) { - if (!flags.controlCondition || !EXTENSION_CONTROL.has(flags.controlCondition)) { - return { - "en-US": - "When --video is set for video_extension, --control-condition must be posebodyface or depth.", - "zh-CN": - "video_extension 提供 --video 时,--control-condition 必须是 posebodyface 或 depth。", - }; - } - } else if (flags.controlCondition !== undefined) { - if (!EXTENSION_CONTROL.has(flags.controlCondition)) { - return { - "en-US": "--control-condition for video_extension must be posebodyface or depth.", - "zh-CN": "video_extension 的 --control-condition 必须是 posebodyface 或 depth。", - }; - } - } - return undefined; - } - case "video_outpainting": { - const rejected = rejectFlagsError( - [ - ["--mask-image", flags.maskImage], - ["--mask-video", flags.maskVideo], - ["--mask-frame-id", flags.maskFrameId], - ["--mask-type", flags.maskType], - ["--expand-ratio", flags.expandRatio], - ["--expand-mode", flags.expandMode], - ["--first-frame", flags.firstFrame], - ["--last-frame", flags.lastFrame], - ["--first-clip", flags.firstClip], - ["--last-clip", flags.lastClip], - ["--ref-role", flags.refRole], - ["--size", flags.size], - ["--strength", flags.strength], - ["--control-condition", flags.controlCondition], - ["--ref-image", flags.refImage], - ], - mode, - ); - if (rejected) return rejected; - if (!flags.video) { - return { - "en-US": "--video is required for video_outpainting.", - "zh-CN": "video_outpainting 需要 --video。", - }; - } - return ( - scaleError(flags.topScale, "--top-scale") || - scaleError(flags.bottomScale, "--bottom-scale") || - scaleError(flags.leftScale, "--left-scale") || - scaleError(flags.rightScale, "--right-scale") - ); - } - case "image_reference": { - const rejected = rejectFlagsError( - [ - ["--video", flags.video], - ["--mask-image", flags.maskImage], - ["--mask-video", flags.maskVideo], - ["--mask-frame-id", flags.maskFrameId], - ["--mask-type", flags.maskType], - ["--expand-ratio", flags.expandRatio], - ["--expand-mode", flags.expandMode], - ["--first-frame", flags.firstFrame], - ["--last-frame", flags.lastFrame], - ["--first-clip", flags.firstClip], - ["--last-clip", flags.lastClip], - ["--top-scale", flags.topScale], - ["--bottom-scale", flags.bottomScale], - ["--left-scale", flags.leftScale], - ["--right-scale", flags.rightScale], - ["--strength", flags.strength], - ["--control-condition", flags.controlCondition], - ], - mode, - ); - if (rejected) return rejected; - if (refImages.length < 1 || refImages.length > 3) { - return { - "en-US": "image_reference requires 1–3 --ref-image values.", - "zh-CN": "image_reference 需要 1–3 张 --ref-image。", - }; - } - if (flags.refRole !== undefined) { - if (flags.refRole.length !== refImages.length) { - return { - "en-US": "--ref-role count must match --ref-image count.", - "zh-CN": "--ref-role 数量必须与 --ref-image 一致。", - }; - } - let bgCount = 0; - for (const role of flags.refRole) { - if (role !== "obj" && role !== "bg") { - return { - "en-US": '--ref-role values must be "obj" or "bg".', - "zh-CN": '--ref-role 取值必须是 "obj" 或 "bg"。', - }; - } - if (role === "bg") bgCount += 1; - } - if (bgCount > 1) { - return { - "en-US": "At most one --ref-role bg is allowed.", - "zh-CN": "--ref-role 最多只能有一个 bg。", - }; - } - } - if (flags.size !== undefined && !ALLOWED_SIZES.has(flags.size)) { - return { - "en-US": "--size must be one of 1280*720, 720*1280, 960*960, 832*1088, 1088*832.", - "zh-CN": "--size 必须是 1280*720、720*1280、960*960、832*1088、1088*832 之一。", - }; - } - return undefined; - } - default: { - const _exhaustive: never = mode; - return { - "en-US": `Unsupported --function "${String(_exhaustive)}".`, - "zh-CN": `不支持的 --function "${String(_exhaustive)}"。`, - }; - } - } -} - -function buildVaceRequest( - flags: RetouchFlags, - mode: WanxVaceFunction, - media: { - videoUrl?: string; - refImages?: string[]; - maskImageUrl?: string; - maskVideoUrl?: string; - firstFrameUrl?: string; - lastFrameUrl?: string; - firstClipUrl?: string; - lastClipUrl?: string; - }, -): DashScopeVideoVaceRequest { - const input = stripUndefined({ - function: mode, - prompt: flags.prompt, - video_url: media.videoUrl, - ref_images_url: media.refImages, - mask_image_url: media.maskImageUrl, - mask_video_url: media.maskVideoUrl, - mask_frame_id: flags.maskFrameId, - first_frame_url: media.firstFrameUrl, - last_frame_url: media.lastFrameUrl, - first_clip_url: media.firstClipUrl, - last_clip_url: media.lastClipUrl, - }) as DashScopeVideoVaceRequest["input"]; - - const objOrBg = flags.refRole === undefined ? undefined : (flags.refRole as Array<"obj" | "bg">); - - const parameters = stripUndefined({ - control_condition: flags.controlCondition === "" ? undefined : flags.controlCondition, - strength: flags.strength, - prompt_extend: flags.promptExtend, - watermark: flags.watermark, - seed: flags.seed, - mask_type: flags.maskType, - expand_ratio: flags.expandRatio, - expand_mode: flags.expandMode, - size: flags.size, - top_scale: flags.topScale, - bottom_scale: flags.bottomScale, - left_scale: flags.leftScale, - right_scale: flags.rightScale, - obj_or_bg: objOrBg, - }); - - return { - model: MODEL, - input, - parameters: Object.keys(parameters).length > 0 ? parameters : undefined, - }; -} - -export default defineCommand({ - description: { - "en-US": - "Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference)", - "zh-CN": "万相 2.1 VACE 统一视频编辑(重绘/局部编辑/延展/画面扩展/多图参考)", - }, - auth: "apiKey", - usageArgs: "--prompt [--function ] [flags]", - flags: RETOUCH_FLAGS, - exampleArgs: [ - { - "en-US": - '--prompt "Convert the scene to claymation" --function video_repainting --video https://example.com/in.mp4 --control-condition depth --strength 0.8', - "zh-CN": - '--prompt "将场景转为黏土风格" --function video_repainting --video https://example.com/in.mp4 --control-condition depth --strength 0.8', - }, - { - "en-US": - '--prompt "Extend the shot" --function video_extension --first-frame https://example.com/first.png', - "zh-CN": - '--prompt "延展镜头" --function video_extension --first-frame https://example.com/first.png', - }, - { - "en-US": - '--prompt "Generate from references" --function image_reference --ref-image https://example.com/a.png --ref-image https://example.com/b.png --ref-role obj --ref-role bg --size 1280*720', - "zh-CN": - '--prompt "参考图生成" --function image_reference --ref-image https://example.com/a.png --ref-image https://example.com/b.png --ref-role obj --ref-role bg --size 1280*720', - }, - ], - notes: [ - { - "en-US": - "Fixed model wanx2.1-vace-plus (Beijing/Singapore). Distinct from `video edit` (happyhorse). Output is silent MP4. video_extension: first-frame/clip extends forward, last-frame/clip extends backward; total output is 5s. Requires model access. Do not use a boolean --video-extension alias.", - "zh-CN": - "固定模型 wanx2.1-vace-plus(北京/新加坡)。与 `video edit`(happyhorse)不同。输出为无声 MP4。video_extension:首帧/首片段向后延展,尾帧/尾片段向前延展;完整输出共 5 秒。需账号已开通该模型权限。不要使用布尔 --video-extension 别名。", - }, - ], - validate: (flags) => validateRetouchFlags(flags as RetouchFlags), - async run(ctx) { - const flags = ctx.flags as RetouchFlags; - const mode = resolveFunction(flags); - - if (flags.prompt.length > 800) { - ctx.output.info({ - "en-US": - "Prompt exceeds 800 characters; the server may truncate it. The CLI does not modify the text.", - "zh-CN": "提示词超过 800 字符,服务端可能截断;CLI 不会改写原文。", - }); - } - - const previewMedia = { - videoUrl: flags.video !== undefined ? previewMediaUrl(flags.video) : undefined, - refImages: flags.refImage?.map((image) => previewMediaUrl(image)), - maskImageUrl: flags.maskImage !== undefined ? previewMediaUrl(flags.maskImage) : undefined, - maskVideoUrl: flags.maskVideo !== undefined ? previewMediaUrl(flags.maskVideo) : undefined, - firstFrameUrl: flags.firstFrame !== undefined ? previewMediaUrl(flags.firstFrame) : undefined, - lastFrameUrl: flags.lastFrame !== undefined ? previewMediaUrl(flags.lastFrame) : undefined, - firstClipUrl: flags.firstClip !== undefined ? previewMediaUrl(flags.firstClip) : undefined, - lastClipUrl: flags.lastClip !== undefined ? previewMediaUrl(flags.lastClip) : undefined, - }; - - const previewRequest = buildVaceRequest(flags, mode, previewMedia); - - await runSpecializedVideoLifecycle(ctx, { - endpointPath: videoGeneratePath(), - previewRequest, - resolveLiveRequest: async () => { - const videoUrl = - flags.video !== undefined - ? await resolveMediaUrl(ctx.client, flags.video, MODEL) - : undefined; - const refImages = - flags.refImage !== undefined - ? await Promise.all( - flags.refImage.map((image) => resolveMediaUrl(ctx.client, image, MODEL)), - ) - : undefined; - const maskImageUrl = - flags.maskImage !== undefined - ? await resolveMediaUrl(ctx.client, flags.maskImage, MODEL) - : undefined; - const maskVideoUrl = - flags.maskVideo !== undefined - ? await resolveMediaUrl(ctx.client, flags.maskVideo, MODEL) - : undefined; - const firstFrameUrl = - flags.firstFrame !== undefined - ? await resolveMediaUrl(ctx.client, flags.firstFrame, MODEL) - : undefined; - const lastFrameUrl = - flags.lastFrame !== undefined - ? await resolveMediaUrl(ctx.client, flags.lastFrame, MODEL) - : undefined; - const firstClipUrl = - flags.firstClip !== undefined - ? await resolveMediaUrl(ctx.client, flags.firstClip, MODEL) - : undefined; - const lastClipUrl = - flags.lastClip !== undefined - ? await resolveMediaUrl(ctx.client, flags.lastClip, MODEL) - : undefined; - return buildVaceRequest(flags, mode, { - videoUrl, - refImages, - maskImageUrl, - maskVideoUrl, - firstFrameUrl, - lastFrameUrl, - firstClipUrl, - lastClipUrl, - }); - }, - extractVideoUrl: extractVideoUrlField, - pollInterval: flags.pollInterval, - download: flags.download, - async: flags.async, - }); - }, -}); diff --git a/packages/commands/src/commands/video/specialized-shared.ts b/packages/commands/src/commands/video/specialized-shared.ts index 07b1bee1..58dadc91 100644 --- a/packages/commands/src/commands/video/specialized-shared.ts +++ b/packages/commands/src/commands/video/specialized-shared.ts @@ -1,7 +1,9 @@ import { BailianError, ExitCode, + REGIONS, resolveOutputDir, + ASYNC_FLAG, type Client, type CommandContext, type DashScopeAsyncResponse, @@ -9,20 +11,52 @@ import { type FlagsDef, type LocalizedText, } from "bailian-cli-core"; -import { join } from "path"; -import { existsSync, statSync } from "fs"; +import { dirname, join } from "path"; +import { accessSync, constants, existsSync, lstatSync, statSync } from "fs"; import { downloadDashScopeTaskResult, pollDashScopeTask } from "../shared/dashscope-task.ts"; -import { hasNonAscii, isHttpUrl } from "../shared/translation.ts"; +import { isHttpUrl } from "../shared/translation.ts"; /** Floor aligned with video edit/ref long-running tasks. */ export const SPECIALIZED_VIDEO_TIMEOUT_FLOOR_SEC = 600; +const BEIJING_ONLY_MESSAGE: LocalizedText = { + "en-US": + "This model is available only in China (Beijing). Use the Beijing base URL (https://dashscope.aliyuncs.com) and a Beijing-region API Key.", + "zh-CN": + "该模型仅支持华北 2(北京)地域。请使用北京地域 base URL(https://dashscope.aliyuncs.com)和北京地域 API Key。", +}; + +export const SPECIALIZED_VIDEO_SHARED_FLAGS = { + download: { + type: "string", + valueHint: "", + description: { + "en-US": "Save video to this file on completion (default: /videos/.mp4)", + "zh-CN": "完成后将视频保存到此文件(默认:/videos/.mp4)", + }, + }, + ...ASYNC_FLAG, + pollInterval: { + type: "number", + valueHint: "", + description: { + "en-US": "Polling interval when waiting (default: 15)", + "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", + }, + }, +} satisfies FlagsDef; + export function pendingUploadMarker(localPath: string): string { return ``; } export function previewMediaUrl(value: string): string { - return isHttpUrl(value) ? value : pendingUploadMarker(value); + if (isHttpUrl(value) || value.startsWith("oss://")) return value; + return pendingUploadMarker(value); +} + +function isOssUrl(value: string): boolean { + return value.startsWith("oss://"); } /** Usage error for media flags; safe for command.validate (auth-independent). */ @@ -37,11 +71,13 @@ export function mediaInputError( "zh-CN": `${flagName} 不能为空。`, }; } - if (isHttpUrl(value)) { - if (hasNonAscii(value)) { + // Pass http(s) through as-is (including non-ASCII); no encodeURI. + if (isHttpUrl(value)) return undefined; + if (isOssUrl(value)) { + if (options?.allowLocal === false) { return { - "en-US": `${flagName} URL must not contain non-ASCII characters.`, - "zh-CN": `${flagName} URL 不能包含非 ASCII 字符。`, + "en-US": `${flagName} must be a public http(s) URL (oss:// and local paths are not supported in v1).`, + "zh-CN": `${flagName} 必须是公网 http(s) URL(v1 不支持 oss:// 与本地路径)。`, }; } return undefined; @@ -67,15 +103,110 @@ export function mediaInputError( return undefined; } +/** Validate --download before submitting a billable task. */ +export function downloadPathError(downloadPath: string | undefined): LocalizedText | undefined { + if (downloadPath === undefined || downloadPath === "") return undefined; + try { + const entry = lstatSync(downloadPath); + const targetStats = entry.isSymbolicLink() ? statSync(downloadPath) : entry; + if (!targetStats.isFile()) { + return { + "en-US": `--download must be a regular file path (not a directory): ${downloadPath}`, + "zh-CN": `--download 必须是普通文件路径(不能是目录):${downloadPath}`, + }; + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + return { + "en-US": `Cannot access --download path: ${downloadPath}`, + "zh-CN": `无法访问 --download 路径:${downloadPath}`, + }; + } + } + + const parentDir = dirname(downloadPath); + if (!existsSync(parentDir)) return undefined; + try { + accessSync(parentDir, constants.W_OK); + } catch { + return { + "en-US": `--download parent directory is not writable: ${parentDir}`, + "zh-CN": `--download 父目录不可写:${parentDir}`, + }; + } + return undefined; +} + +/** Shared validate for --async / --download / --poll-interval. */ +export function specializedLifecycleFlagError(flags: { + async?: boolean; + download?: string; + pollInterval?: number; +}): LocalizedText | undefined { + if ( + flags.pollInterval !== undefined && + (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) + ) { + return { + "en-US": "--poll-interval must be a positive number.", + "zh-CN": "--poll-interval 必须为正数。", + }; + } + if (flags.async) { + if (flags.download !== undefined) { + return { + "en-US": "--async cannot be combined with --download.", + "zh-CN": "--async 不能与 --download 同时使用。", + }; + } + if (flags.pollInterval !== undefined) { + return { + "en-US": "--async cannot be combined with --poll-interval.", + "zh-CN": "--async 不能与 --poll-interval 同时使用。", + }; + } + } + return downloadPathError(flags.download); +} + export async function resolveMediaUrl( client: Client, value: string, model: string, ): Promise { - if (isHttpUrl(value)) return value; + if (isHttpUrl(value) || isOssUrl(value)) return value; return client.uploadFile(value, model); } +/** Reject known non-Beijing official DashScope hosts before submitting. */ +export function assertBeijingDashScopeEndpoint( + endpointUrl: string, + localize: (text: LocalizedText) => string, +): void { + let hostname: string; + try { + hostname = new URL(endpointUrl).hostname; + } catch { + return; + } + const beijingHost = new URL(REGIONS.cn).hostname; + if (hostname === beijingHost) return; + if (hostname.endsWith(".cn-beijing.maas.aliyuncs.com")) return; + + const intlHost = new URL(REGIONS.intl).hostname; + const usHost = new URL(REGIONS.us).hostname; + const isKnownNonBeijing = + hostname === intlHost || + hostname === usHost || + hostname.includes("dashscope-intl") || + hostname.includes("dashscope-us") || + hostname.includes("ap-southeast-1") || + hostname.includes("us-east-1"); + if (!isKnownNonBeijing) return; + + throw new BailianError(localize(BEIJING_ONLY_MESSAGE), ExitCode.USAGE); +} + export type SpecializedVideoUrlExtractor = (task: DashScopeTaskResponse) => string | undefined; export function extractVideoUrlField(task: DashScopeTaskResponse): string | undefined { @@ -97,7 +228,7 @@ type SpecializedLifecycleOptions = { async?: boolean; }; -/** Submit / poll / download lifecycle shared by portrait, style, and retouch. */ +/** Submit / poll / download lifecycle shared by retalk and style. */ export async function runSpecializedVideoLifecycle( ctx: CommandContext, options: SpecializedLifecycleOptions, @@ -107,10 +238,22 @@ export async function runSpecializedVideoLifecycle( const endpoint = ctx.client.url(options.endpointPath); if (settings.dryRun) { + try { + assertBeijingDashScopeEndpoint(endpoint, localize); + } catch (error) { + if (error instanceof BailianError) { + ctx.output.progress({ + "en-US": `Warning: ${error.message}`, + "zh-CN": `警告:${error.message}`, + }); + } + } ctx.output.result({ endpoint, request: options.previewRequest }); return; } + assertBeijingDashScopeEndpoint(endpoint, localize); + const liveRequest = await options.resolveLiveRequest(); const submitted = await ctx.client.requestJson({ path: options.endpointPath, @@ -120,11 +263,20 @@ export async function runSpecializedVideoLifecycle( }); const taskId = submitted.output.task_id; + ctx.output.progress({ + "en-US": `Submitted. task_id=${taskId}`, + "zh-CN": `已提交。task_id=${taskId}`, + }); + if (options.async) { ctx.output.result({ task_id: taskId, request_id: submitted.request_id }); return; } + const pollIntervalSec = options.pollInterval ?? 15; + // Avoid racing the first task lookup right after submit (UNKNOWN can mean "not visible yet"). + await new Promise((resolve) => setTimeout(resolve, pollIntervalSec * 1000)); + const pollTimeoutSec = Math.max(settings.timeout, SPECIALIZED_VIDEO_TIMEOUT_FLOOR_SEC); const taskResponse = await pollDashScopeTask( { @@ -132,17 +284,21 @@ export async function runSpecializedVideoLifecycle( settings: { ...settings, timeout: pollTimeoutSec }, }, taskId, - { pollInterval: options.pollInterval ?? 15 }, + { pollInterval: pollIntervalSec }, ); const videoUrl = options.extractVideoUrl(taskResponse); if (!videoUrl) { throw new BailianError( localize({ - "en-US": "Task succeeded but no video URL was returned.", - "zh-CN": "任务成功但未返回视频 URL。", + "en-US": `Task succeeded but no video URL was returned. task_id=${taskId}`, + "zh-CN": `任务成功但未返回视频 URL。task_id=${taskId}`, }), ExitCode.GENERAL, + localize({ + "en-US": `Query or re-download with task_id ${taskId}; do not resubmit.`, + "zh-CN": `请用 task_id ${taskId} 查询或重新下载,勿重新提交。`, + }), ); } @@ -150,15 +306,10 @@ export async function runSpecializedVideoLifecycle( options.download || join(resolveOutputDir(settings, { subDir: "videos" }), `${taskId}.mp4`); await downloadDashScopeTaskResult(ctx, taskId, videoUrl, destPath); - const result: Record = { + ctx.output.result({ ...taskResponse, task_id: taskId, video_url: videoUrl, saved: destPath, - }; - if (taskResponse.output.output_video_url) { - result.output_video_url = taskResponse.output.output_video_url; - } - - ctx.output.result(result); + }); } diff --git a/packages/commands/src/commands/video/style.ts b/packages/commands/src/commands/video/style.ts index 62726ed6..0e3decf8 100644 --- a/packages/commands/src/commands/video/style.ts +++ b/packages/commands/src/commands/video/style.ts @@ -1,7 +1,6 @@ import { defineCommand, videoGeneratePath, - ASYNC_FLAG, stripUndefined, type DashScopeVideoStyleTransformRequest, type FlagsDef, @@ -10,6 +9,8 @@ import { extractStyleOutputVideoUrl, mediaInputError, runSpecializedVideoLifecycle, + SPECIALIZED_VIDEO_SHARED_FLAGS, + specializedLifecycleFlagError, } from "./specialized-shared.ts"; const MODEL = "video-style-transform"; @@ -38,8 +39,8 @@ const STYLE_FLAGS = { type: "number", valueHint: "", description: { - "en-US": "Output video FPS 15–25 (maps to video_fps)", - "zh-CN": "输出视频帧率 15–25(映射为 video_fps)", + "en-US": "Output video FPS 15–25 (default: 15; maps to video_fps)", + "zh-CN": "输出视频帧率 15–25(默认 15;映射为 video_fps)", }, }, animateEmotion: { @@ -54,41 +55,28 @@ const STYLE_FLAGS = { type: "number", valueHint: "", description: { - "en-US": "Short-side length 540 or 720 (server default: 720)", - "zh-CN": "短边长度 540 或 720(服务端默认 720)", + "en-US": "Short-side length 540 or 720 (server default: 720; 720P costs more than 540P)", + "zh-CN": "短边长度 540 或 720(服务端默认 720;720P 比 540P 更贵)", }, }, superResolution: { type: "boolean", valueHint: "", description: { - "en-US": "Enable super-resolution (maps to use_SR; server default: false)", - "zh-CN": "是否启用超分(映射为 use_SR;服务端默认 false)", - }, - }, - download: { - type: "string", - valueHint: "", - description: { - "en-US": "Save video to file on completion (default: output dir)", - "zh-CN": "完成后将视频保存到文件(默认输出目录)", - }, - }, - ...ASYNC_FLAG, - pollInterval: { - type: "number", - valueHint: "", - description: { - "en-US": "Polling interval when waiting (default: 15)", - "zh-CN": "等待任务时的轮询间隔(默认:15 秒)", + "en-US": + "Enable super-resolution (maps to use_SR; server default: false; with min_len=540 outputs 1080P billed as 540P)", + "zh-CN": + "是否启用超分(映射为 use_SR;服务端默认 false;min_len=540 时输出 1080P 仍按 540P 计费)", }, }, + ...SPECIALIZED_VIDEO_SHARED_FLAGS, } satisfies FlagsDef; export default defineCommand({ description: { - "en-US": "Restyle a video (video-style-transform)", - "zh-CN": "视频风格重绘(video-style-transform)", + "en-US": + "Restyle a video with 8 presets (video-style-transform); for prompt-based edit use video edit", + "zh-CN": "按 8 种预设风格重绘视频(video-style-transform);基于提示词的编辑请用 video edit", }, auth: "apiKey", usageArgs: "--video [flags]", @@ -108,21 +96,14 @@ export default defineCommand({ notes: [ { "en-US": - "Fixed model video-style-transform (Beijing only). Success field is output.output_video_url. Local paths are rejected until temporary OSS support is verified. Requires model access.", + "Fixed model video-style-transform (Beijing only). Wait-mode polling uses at least 600s (--timeout lower values are raised).", "zh-CN": - "固定模型 video-style-transform(仅北京)。成功字段为 output.output_video_url。在临时 OSS 验证前拒绝本地路径。需账号已开通该模型权限。", + "固定模型 video-style-transform(仅北京)。等待模式轮询至少 600 秒(更小的 --timeout 会被抬高)。", }, ], validate: (flags) => { - if ( - flags.pollInterval !== undefined && - (!(flags.pollInterval > 0) || !Number.isFinite(flags.pollInterval)) - ) { - return { - "en-US": "--poll-interval must be a positive number.", - "zh-CN": "--poll-interval 必须为正数。", - }; - } + const sharedError = specializedLifecycleFlagError(flags); + if (sharedError) return sharedError; if (flags.style !== undefined) { if (!Number.isInteger(flags.style) || flags.style < 0 || flags.style > 7) { return { diff --git a/packages/commands/src/commands/video/task-get.ts b/packages/commands/src/commands/video/task-get.ts index df454d0a..a20d9c0a 100644 --- a/packages/commands/src/commands/video/task-get.ts +++ b/packages/commands/src/commands/video/task-get.ts @@ -41,8 +41,6 @@ export default defineCommand({ task_status: response.output.task_status, video_url: response.output.video_url, output_video_url: response.output.output_video_url, - orig_prompt: response.output.orig_prompt, - actual_prompt: response.output.actual_prompt, image_url: response.output.image_url, results: response.output.results, Success: response.output.Success, diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index 947a9ce0..77ebee74 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -23,9 +23,8 @@ export { default as imageTranslate } from "./commands/image/translate.ts"; export { default as videoGenerate } from "./commands/video/generate.ts"; export { default as videoEdit } from "./commands/video/edit.ts"; export { default as videoRef } from "./commands/video/ref.ts"; -export { default as videoPortrait } from "./commands/video/portrait.ts"; +export { default as videoRetalk } from "./commands/video/retalk.ts"; export { default as videoStyle } from "./commands/video/style.ts"; -export { default as videoRetouch } from "./commands/video/retouch.ts"; export { default as videoTaskGet } from "./commands/video/task-get.ts"; export { default as videoDownload } from "./commands/video/download.ts"; export { default as visionDescribe } from "./commands/vision/describe.ts"; diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index b3d103b9..5f7557da 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -135,16 +135,15 @@ export const VIDEO_ROUTES: E2eRouteExports = { "video generate": "videoGenerate", "video edit": "videoEdit", "video ref": "videoRef", - "video portrait": "videoPortrait", + "video retalk": "videoRetalk", "video style": "videoStyle", - "video retouch": "videoRetouch", "video task get": "videoTaskGet", "video download": "videoDownload", "speech synthesize": "speechSynthesize", }; -export const VIDEO_PORTRAIT_ROUTES: E2eRouteExports = { - "video portrait": "videoPortrait", +export const VIDEO_RETALK_ROUTES: E2eRouteExports = { + "video retalk": "videoRetalk", "video task get": "videoTaskGet", "video download": "videoDownload", }; @@ -155,12 +154,6 @@ export const VIDEO_STYLE_ROUTES: E2eRouteExports = { "video download": "videoDownload", }; -export const VIDEO_RETOUCH_ROUTES: E2eRouteExports = { - "video retouch": "videoRetouch", - "video task get": "videoTaskGet", - "video download": "videoDownload", -}; - export const VISION_ROUTES: E2eRouteExports = { "vision describe": "visionDescribe", }; diff --git a/packages/commands/tests/e2e/video-portrait.e2e.test.ts b/packages/commands/tests/e2e/video-retalk.e2e.test.ts similarity index 66% rename from packages/commands/tests/e2e/video-portrait.e2e.test.ts rename to packages/commands/tests/e2e/video-retalk.e2e.test.ts index c5191ebd..fd3a6b99 100644 --- a/packages/commands/tests/e2e/video-portrait.e2e.test.ts +++ b/packages/commands/tests/e2e/video-retalk.e2e.test.ts @@ -1,5 +1,5 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; -import { readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterEach, describe, expect, test } from "vite-plus/test"; import { @@ -11,7 +11,7 @@ import { runCommandE2e, runCommandInProcess, } from "./helpers.ts"; -import { VIDEO_PORTRAIT_ROUTES } from "./topic-routes.ts"; +import { VIDEO_RETALK_ROUTES } from "./topic-routes.ts"; const servers: Server[] = []; const tempDirs: string[] = []; @@ -72,11 +72,11 @@ async function startServer( return { origin: `http://127.0.0.1:${address.port}`, requests }; } -describe("e2e: video portrait", () => { +describe("e2e: video retalk", () => { test("help shows bilingual flags and fixed model", async () => { - const { stderr, exitCode } = await runCommandHelp(VIDEO_PORTRAIT_ROUTES, [ + const { stderr, exitCode } = await runCommandHelp(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--help", ]); expect(exitCode, stderr).toBe(0); @@ -89,18 +89,18 @@ describe("e2e: video portrait", () => { }); test("missing required flags → 2", async () => { - const missingVideo = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const missingVideo = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--audio", "https://example.com/a.wav", ]); expect(missingVideo.exitCode).toBe(2); expect(missingVideo.stderr).toMatch(/--video/i); - const missingAudio = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const missingAudio = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--video", "https://example.com/v.mp4", ]); @@ -109,9 +109,9 @@ describe("e2e: video portrait", () => { }); test("face-threshold without ref-image → 2", async () => { - const { stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const { stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--video", "https://example.com/v.mp4", "--audio", @@ -123,30 +123,104 @@ describe("e2e: video portrait", () => { expect(stderr).toMatch(/face-threshold|ref-image/i); }); - test("non-ASCII public URL → 2", async () => { - const { stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + test("non-ASCII public URL passes through on dry-run", async () => { + const videoUrl = "https://example.com/视频.mp4"; + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--video", - "https://example.com/视频.mp4", + videoUrl, "--audio", "https://example.com/a.wav", + "--dry-run", + "--output", + "json", ]); - expect(exitCode).toBe(2); - expect(stderr).toMatch(/non-ASCII|非 ASCII/i); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ request?: { input?: { video_url?: string } } }>(stdout); + expect(body.request?.input?.video_url).toBe(videoUrl); + }); + + test("async+download / download-dir / intl base-url → 2", async () => { + const asyncDownload = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ + "video", + "retalk", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--async", + "--download", + "out.mp4", + ]); + expect(asyncDownload.exitCode).toBe(2); + expect(asyncDownload.stderr).toMatch(/--async|--download/i); + + const outDir = makeE2eOutputDir("video-retalk-download-dir"); + tempDirs.push(outDir); + mkdirSync(outDir, { recursive: true }); + const dirAsDownload = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ + "video", + "retalk", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--download", + outDir, + ]); + expect(dirAsDownload.exitCode).toBe(2); + expect(dirAsDownload.stderr).toMatch(/regular file|普通文件|directory|目录/i); + + const intl = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ + "video", + "retalk", + "--base-url", + "https://dashscope-intl.aliyuncs.com", + "--api-key", + "sk-test", + "--video", + "https://example.com/v.mp4", + "--audio", + "https://example.com/a.wav", + "--output", + "json", + ]); + expect(intl.exitCode).toBe(2); + expect(intl.stderr).toMatch(/Beijing|北京/i); + }); + + test("oss:// media accepted in dry-run", async () => { + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ + "video", + "retalk", + "--video", + "oss://bucket/video.mp4", + "--audio", + "oss://bucket/audio.wav", + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ + request?: { input?: { video_url?: string; audio_url?: string } }; + }>(stdout); + expect(body.request?.input?.video_url).toBe("oss://bucket/video.mp4"); + expect(body.request?.input?.audio_url).toBe("oss://bucket/audio.wav"); }); test("dry-run builds image2video body with pending local markers", async () => { - const fixtureDir = makeE2eOutputDir("video-portrait-dry"); + const fixtureDir = makeE2eOutputDir("video-retalk-dry"); tempDirs.push(fixtureDir); const videoPath = join(fixtureDir, "face.mp4"); const audioPath = join(fixtureDir, "speech.wav"); writeFileSync(videoPath, "fake-video"); writeFileSync(audioPath, "fake-audio"); - const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--video", videoPath, "--audio", @@ -179,15 +253,15 @@ describe("e2e: video portrait", () => { response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify({ - output: { task_id: "task-portrait-1", task_status: "PENDING" }, - request_id: "req-portrait-1", + output: { task_id: "task-retalk-1", task_status: "PENDING" }, + request_id: "req-retalk-1", }), ); }); - const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--base-url", origin, "--api-key", @@ -202,8 +276,8 @@ describe("e2e: video portrait", () => { ]); expect(exitCode, stderr).toBe(0); const body = parseStdoutJson<{ task_id?: string; request_id?: string }>(stdout); - expect(body.task_id).toBe("task-portrait-1"); - expect(body.request_id).toBe("req-portrait-1"); + expect(body.task_id).toBe("task-retalk-1"); + expect(body.request_id).toBe("req-retalk-1"); expect(requests).toHaveLength(1); expect(requests[0]?.method).toBe("POST"); expect(requests[0]?.path).toBe("/api/v1/services/aigc/image2video/video-synthesis"); @@ -220,19 +294,19 @@ describe("e2e: video portrait", () => { response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify({ - output: { task_id: "task-portrait-2", task_status: "PENDING" }, + output: { task_id: "task-retalk-2", task_status: "PENDING" }, request_id: "req-2", }), ); return; } - if (url.pathname === "/api/v1/tasks/task-portrait-2") { + if (url.pathname === "/api/v1/tasks/task-retalk-2") { pollCount += 1; if (pollCount === 1) { response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify({ - output: { task_id: "task-portrait-2", task_status: "PRE-PROCESSING" }, + output: { task_id: "task-retalk-2", task_status: "PRE-PROCESSING" }, request_id: "req-2", }), ); @@ -242,7 +316,7 @@ describe("e2e: video portrait", () => { response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify({ - output: { task_id: "task-portrait-2", task_status: "POST-PROCESSING" }, + output: { task_id: "task-retalk-2", task_status: "POST-PROCESSING" }, request_id: "req-2", }), ); @@ -252,7 +326,7 @@ describe("e2e: video portrait", () => { response.end( JSON.stringify({ output: { - task_id: "task-portrait-2", + task_id: "task-retalk-2", task_status: "SUCCEEDED", video_url: `${origin}/out.mp4`, }, @@ -270,13 +344,13 @@ describe("e2e: video portrait", () => { response.end(); }); - const outDir = makeE2eOutputDir("video-portrait-wait"); + const outDir = makeE2eOutputDir("video-retalk-wait"); tempDirs.push(outDir); - const dest = join(outDir, "portrait.mp4"); + const dest = join(outDir, "retalk.mp4"); - const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--base-url", origin, "--api-key", @@ -296,7 +370,7 @@ describe("e2e: video portrait", () => { ]); expect(exitCode, stderr).toBe(0); const body = parseStdoutJson<{ task_id?: string; video_url?: string; saved?: string }>(stdout); - expect(body.task_id).toBe("task-portrait-2"); + expect(body.task_id).toBe("task-retalk-2"); expect(body.video_url).toMatch(/out\.mp4$/); expect(body.saved).toBe(dest); expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); @@ -309,18 +383,18 @@ describe("e2e: video portrait", () => { response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify({ - output: { task_id: "task-portrait-fail", task_status: "PENDING" }, + output: { task_id: "task-retalk-fail", task_status: "PENDING" }, request_id: "req-fail", }), ); return; } - if (url.pathname === "/api/v1/tasks/task-portrait-fail") { + if (url.pathname === "/api/v1/tasks/task-retalk-fail") { response.writeHead(200, { "content-type": "application/json" }); response.end( JSON.stringify({ output: { - task_id: "task-portrait-fail", + task_id: "task-retalk-fail", task_status: "FAILED", code: "InvalidParameter", message: "face not detected", @@ -334,9 +408,9 @@ describe("e2e: video portrait", () => { response.end(); }); - const { stderr, exitCode } = await runCommandInProcess(VIDEO_PORTRAIT_ROUTES, [ + const { stderr, exitCode } = await runCommandInProcess(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--base-url", origin, "--api-key", @@ -352,27 +426,30 @@ describe("e2e: video portrait", () => { ]); expect(exitCode).toBe(1); expect(stderr).toMatch(/face not detected/); + // Server FAILED message stays verbatim; task_id lives in the hint only. + expect(stderr).not.toMatch(/face not detected task_id=/); + expect(stderr).toMatch(/task_id[= ]task-retalk-fail|task-retalk-fail/); expect(stderr).not.toMatch(/Task failed:/); }); }); -const portraitLiveVideo = process.env.BAILIAN_E2E_VIDEORETALK_VIDEO_URL?.trim(); -const portraitLiveAudio = process.env.BAILIAN_E2E_VIDEORETALK_AUDIO_URL?.trim(); +const retalkLiveVideo = process.env.BAILIAN_E2E_VIDEORETALK_VIDEO_URL?.trim(); +const retalkLiveAudio = process.env.BAILIAN_E2E_VIDEORETALK_AUDIO_URL?.trim(); describe.skipIf( - !isBailianE2EVideoEnabled() || !isDashScopeE2EReady() || !portraitLiveVideo || !portraitLiveAudio, -)("e2e: video portrait(DashScope live)", () => { - test("videoretalk live portrait drive", async () => { - const outDir = makeE2eOutputDir("video-portrait-live"); - const { stdout, stderr, exitCode } = await runCommandE2e(VIDEO_PORTRAIT_ROUTES, [ + !isBailianE2EVideoEnabled() || !isDashScopeE2EReady() || !retalkLiveVideo || !retalkLiveAudio, +)("e2e: video retalk(DashScope live)", () => { + test("videoretalk live retalk drive", async () => { + const outDir = makeE2eOutputDir("video-retalk-live"); + const { stdout, stderr, exitCode } = await runCommandE2e(VIDEO_RETALK_ROUTES, [ "video", - "portrait", + "retalk", "--video", - portraitLiveVideo!, + retalkLiveVideo!, "--audio", - portraitLiveAudio!, + retalkLiveAudio!, "--download", - join(outDir, "portrait-live.mp4"), + join(outDir, "retalk-live.mp4"), "--output", "json", ]); diff --git a/packages/commands/tests/e2e/video-retouch.e2e.test.ts b/packages/commands/tests/e2e/video-retouch.e2e.test.ts deleted file mode 100644 index 6db1c71c..00000000 --- a/packages/commands/tests/e2e/video-retouch.e2e.test.ts +++ /dev/null @@ -1,382 +0,0 @@ -import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; -import { readFileSync, rmSync } from "node:fs"; -import { join } from "node:path"; -import { afterEach, describe, expect, test } from "vite-plus/test"; -import { - isBailianE2EVideoEnabled, - isDashScopeE2EReady, - makeE2eOutputDir, - parseStdoutJson, - runCommandHelp, - runCommandE2e, - runCommandInProcess, -} from "./helpers.ts"; -import { VIDEO_RETOUCH_ROUTES } from "./topic-routes.ts"; - -const servers: Server[] = []; -const tempDirs: string[] = []; - -afterEach(async () => { - await Promise.all( - servers.splice(0).map( - (server) => - new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())); - }), - ), - ); - for (const tempDir of tempDirs.splice(0)) { - rmSync(tempDir, { recursive: true, force: true }); - } -}); - -async function startServer( - handler: (request: IncomingMessage, response: ServerResponse, body: string) => void, -): Promise<{ origin: string; requests: Array<{ method?: string; path: string; body: string }> }> { - const requests: Array<{ method?: string; path: string; body: string }> = []; - const server = createServer((request, response) => { - const chunks: Buffer[] = []; - request.on("data", (chunk) => chunks.push(chunk)); - request.on("end", () => { - const body = Buffer.concat(chunks).toString("utf8"); - const url = new URL(request.url ?? "/", "http://127.0.0.1"); - requests.push({ method: request.method, path: url.pathname, body }); - handler(request, response, body); - }); - }); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - servers.push(server); - const address = server.address(); - if (!address || typeof address === "string") throw new Error("Expected TCP address"); - return { origin: `http://127.0.0.1:${address.port}`, requests }; -} - -describe("e2e: video retouch", () => { - test("help distinguishes VACE from happyhorse edit", async () => { - const { stderr, exitCode } = await runCommandHelp(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--help", - ]); - expect(exitCode, stderr).toBe(0); - expect(stderr).toMatch(/VACE|万相/); - expect(stderr).toMatch(/wanx2\.1-vace-plus/); - expect(stderr).toMatch(/--function/); - expect(stderr).not.toMatch(/--model/); - expect(stderr).not.toMatch(/--concurrent/); - }); - - test("video_repainting requires control-condition and video", async () => { - const missingControl = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "clay", - "--video", - "https://example.com/in.mp4", - ]); - expect(missingControl.exitCode).toBe(2); - expect(missingControl.stderr).toMatch(/control-condition/i); - - const missingVideo = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "clay", - "--control-condition", - "depth", - ]); - expect(missingVideo.exitCode).toBe(2); - expect(missingVideo.stderr).toMatch(/--video/i); - }); - - test("video_edit requires exactly one mask", async () => { - const none = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "edit", - "--function", - "video_edit", - "--video", - "https://example.com/in.mp4", - ]); - expect(none.exitCode).toBe(2); - expect(none.stderr).toMatch(/mask/i); - - const both = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "edit", - "--function", - "video_edit", - "--video", - "https://example.com/in.mp4", - "--mask-image", - "https://example.com/mask.png", - "--mask-video", - "https://example.com/mask.mp4", - ]); - expect(both.exitCode).toBe(2); - expect(both.stderr).toMatch(/mask/i); - }); - - test("video_extension requires >=1 media source", async () => { - const { stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "extend", - "--function", - "video_extension", - ]); - expect(exitCode).toBe(2); - expect(stderr).toMatch(/first-frame|video_extension|至少/i); - }); - - test("rejects flags not applicable to mode", async () => { - const { stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "clay", - "--video", - "https://example.com/in.mp4", - "--control-condition", - "depth", - "--mask-image", - "https://example.com/mask.png", - ]); - expect(exitCode).toBe(2); - expect(stderr).toMatch(/not applicable|不适用于|--mask-image/i); - }); - - test("image_reference dry-run and role count", async () => { - const badRoles = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "refs", - "--function", - "image_reference", - "--ref-image", - "https://example.com/a.png", - "--ref-image", - "https://example.com/b.png", - "--ref-role", - "obj", - ]); - expect(badRoles.exitCode).toBe(2); - expect(badRoles.stderr).toMatch(/ref-role|ref-image/i); - - const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "refs", - "--function", - "image_reference", - "--ref-image", - "https://example.com/a.png", - "--ref-image", - "https://example.com/b.png", - "--ref-role", - "obj", - "--ref-role", - "bg", - "--size", - "1280*720", - "--dry-run", - "--output", - "json", - ]); - expect(exitCode, stderr).toBe(0); - const body = parseStdoutJson<{ - request?: { - model?: string; - input?: { function?: string; video_url?: string; ref_images_url?: string[] }; - parameters?: { obj_or_bg?: string[]; size?: string }; - }; - }>(stdout); - expect(body.request?.model).toBe("wanx2.1-vace-plus"); - expect(body.request?.input?.function).toBe("image_reference"); - expect(body.request?.input?.video_url).toBeUndefined(); - expect(body.request?.input?.ref_images_url).toEqual([ - "https://example.com/a.png", - "https://example.com/b.png", - ]); - expect(body.request?.parameters?.obj_or_bg).toEqual(["obj", "bg"]); - expect(body.request?.parameters?.size).toBe("1280*720"); - }); - - test("repainting dry-run keeps strength=0 and omits unset params", async () => { - const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "clay", - "--video", - "https://example.com/in.mp4", - "--control-condition", - "depth", - "--strength", - "0", - "--prompt-extend", - "false", - "--dry-run", - "--output", - "json", - ]); - expect(exitCode, stderr).toBe(0); - const body = parseStdoutJson<{ - endpoint?: string; - request?: { - input?: { function?: string; prompt?: string; video_url?: string }; - parameters?: { - control_condition?: string; - strength?: number; - prompt_extend?: boolean; - watermark?: boolean; - }; - }; - }>(stdout); - expect(body.endpoint).toMatch(/video-generation\/video-synthesis$/); - expect(body.request?.input?.function).toBe("video_repainting"); - expect(body.request?.parameters?.control_condition).toBe("depth"); - expect(body.request?.parameters?.strength).toBe(0); - expect(body.request?.parameters?.prompt_extend).toBe(false); - expect(body.request?.parameters?.watermark).toBeUndefined(); - }); - - test("wait mode downloads video_url for repainting", async () => { - let pollCount = 0; - const mp4Bytes = Buffer.from("vace-mp4"); - const { origin, requests } = await startServer((request, response) => { - const url = new URL(request.url ?? "/", "http://127.0.0.1"); - if (request.method === "POST") { - response.writeHead(200, { "content-type": "application/json" }); - response.end( - JSON.stringify({ - output: { task_id: "task-vace-1", task_status: "PENDING" }, - request_id: "req-vace-1", - }), - ); - return; - } - if (url.pathname === "/api/v1/tasks/task-vace-1") { - pollCount += 1; - if (pollCount < 2) { - response.writeHead(200, { "content-type": "application/json" }); - response.end( - JSON.stringify({ - output: { task_id: "task-vace-1", task_status: "RUNNING" }, - request_id: "req-vace-1", - }), - ); - return; - } - response.writeHead(200, { "content-type": "application/json" }); - response.end( - JSON.stringify({ - output: { - task_id: "task-vace-1", - task_status: "SUCCEEDED", - video_url: `${origin}/vace.mp4`, - orig_prompt: "clay", - actual_prompt: "clay style", - }, - request_id: "req-vace-1", - }), - ); - return; - } - if (url.pathname === "/vace.mp4") { - response.writeHead(200, { "content-type": "video/mp4" }); - response.end(mp4Bytes); - return; - } - response.writeHead(404); - response.end(); - }); - - const outDir = makeE2eOutputDir("video-retouch-wait"); - tempDirs.push(outDir); - const dest = join(outDir, "vace.mp4"); - - const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--base-url", - origin, - "--api-key", - "sk-test", - "--prompt", - "clay", - "--video", - "https://example.com/in.mp4", - "--control-condition", - "depth", - "--strength", - "0.8", - "--poll-interval", - "0.05", - "--timeout", - "10", - "--download", - dest, - "--output", - "json", - ]); - expect(exitCode, stderr).toBe(0); - const post = requests.find((entry) => entry.method === "POST"); - expect(post?.path).toBe("/api/v1/services/aigc/video-generation/video-synthesis"); - const posted = JSON.parse(post!.body) as { - input?: { function?: string }; - parameters?: { control_condition?: string; strength?: number }; - }; - expect(posted.input?.function).toBe("video_repainting"); - expect(posted.parameters?.control_condition).toBe("depth"); - expect(posted.parameters?.strength).toBe(0.8); - - const body = parseStdoutJson<{ task_id?: string; video_url?: string; saved?: string }>(stdout); - expect(body.task_id).toBe("task-vace-1"); - expect(body.saved).toBe(dest); - expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); - }); -}); - -const vaceLiveVideo = process.env.BAILIAN_E2E_VACE_VIDEO_URL?.trim(); - -describe.skipIf(!isBailianE2EVideoEnabled() || !isDashScopeE2EReady() || !vaceLiveVideo)( - "e2e: video retouch(DashScope live)", - () => { - test("VACE live video_repainting only (other functions unverified)", async () => { - const outDir = makeE2eOutputDir("video-retouch-live"); - const { stdout, stderr, exitCode } = await runCommandE2e(VIDEO_RETOUCH_ROUTES, [ - "video", - "retouch", - "--prompt", - "Convert the scene to claymation style", - "--function", - "video_repainting", - "--video", - vaceLiveVideo!, - "--control-condition", - "depth", - "--strength", - "0.8", - "--download", - join(outDir, "vace-live.mp4"), - "--output", - "json", - ]); - expect(exitCode, stderr).toBe(0); - const body = parseStdoutJson<{ video_url?: string }>(stdout); - expect(body.video_url?.startsWith("https://")).toBe(true); - }, 3_600_000); - }, -); diff --git a/packages/commands/tests/e2e/video-style.e2e.test.ts b/packages/commands/tests/e2e/video-style.e2e.test.ts index 4d87f800..2e20e28c 100644 --- a/packages/commands/tests/e2e/video-style.e2e.test.ts +++ b/packages/commands/tests/e2e/video-style.e2e.test.ts @@ -87,7 +87,7 @@ describe("e2e: video style", () => { expect(stderr).not.toMatch(/--concurrent/); }); - test("missing video / local path / non-ASCII → 2", async () => { + test("missing video / local path / oss / async conflict → 2", async () => { const missing = await runCommandInProcess(VIDEO_STYLE_ROUTES, ["video", "style", "--quiet"]); expect(missing.exitCode).toBe(2); expect(missing.stderr).toMatch(/--video/i); @@ -101,14 +101,42 @@ describe("e2e: video style", () => { expect(localPath.exitCode).toBe(2); expect(localPath.stderr).toMatch(/public|公网|local|本地/i); - const nonAscii = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + const ossUrl = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ "video", "style", "--video", - "https://example.com/风格.mp4", + "oss://bucket/clip.mp4", ]); - expect(nonAscii.exitCode).toBe(2); - expect(nonAscii.stderr).toMatch(/non-ASCII|非 ASCII/i); + expect(ossUrl.exitCode).toBe(2); + expect(ossUrl.stderr).toMatch(/public|公网|oss:\/\//i); + + const asyncDownload = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--video", + "https://example.com/clip.mp4", + "--async", + "--poll-interval", + "5", + ]); + expect(asyncDownload.exitCode).toBe(2); + expect(asyncDownload.stderr).toMatch(/--async|--poll-interval/i); + }); + + test("non-ASCII public URL passes through on dry-run", async () => { + const videoUrl = "https://example.com/风格.mp4"; + const { stdout, stderr, exitCode } = await runCommandInProcess(VIDEO_STYLE_ROUTES, [ + "video", + "style", + "--video", + videoUrl, + "--dry-run", + "--output", + "json", + ]); + expect(exitCode, stderr).toBe(0); + const body = parseStdoutJson<{ request?: { input?: { video_url?: string } } }>(stdout); + expect(body.request?.input?.video_url).toBe(videoUrl); }); test("dry-run preserves style=0 and boolean false", async () => { @@ -234,13 +262,13 @@ describe("e2e: video style", () => { const body = parseStdoutJson<{ task_id?: string; video_url?: string; - output_video_url?: string; saved?: string; + output?: { output_video_url?: string }; usage?: { SR?: number }; }>(stdout); expect(body.task_id).toBe("task-style-1"); expect(body.video_url).toMatch(/styled\.mp4$/); - expect(body.output_video_url).toMatch(/styled\.mp4$/); + expect(body.output?.output_video_url).toMatch(/styled\.mp4$/); expect(body.usage?.SR).toBe(720); expect(readFileSync(dest).equals(mp4Bytes)).toBe(true); }); diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts index 3c3817ff..8edbd7bf 100644 --- a/packages/core/src/types/api.ts +++ b/packages/core/src/types/api.ts @@ -281,7 +281,7 @@ export interface DashScopeVideoEditRequest { }; } -/** VideoRetalk (bl video portrait) request body. */ +/** VideoRetalk (bl video retalk) request body. */ export interface DashScopeVideoRetalkRequest { model: string; input: { @@ -310,47 +310,6 @@ export interface DashScopeVideoStyleTransformRequest { }; } -export type WanxVaceFunction = - | "video_repainting" - | "video_edit" - | "video_extension" - | "video_outpainting" - | "image_reference"; - -/** Wanx 2.1 VACE (bl video retouch) request body. */ -export interface DashScopeVideoVaceRequest { - model: string; - input: { - function: WanxVaceFunction; - prompt?: string; - video_url?: string; - ref_images_url?: string[]; - mask_image_url?: string; - mask_video_url?: string; - mask_frame_id?: number; - first_frame_url?: string; - last_frame_url?: string; - first_clip_url?: string; - last_clip_url?: string; - }; - parameters?: { - control_condition?: string; - strength?: number; - prompt_extend?: boolean; - watermark?: boolean; - seed?: number; - mask_type?: string; - expand_ratio?: number; - expand_mode?: string; - size?: string; - top_scale?: number; - bottom_scale?: number; - left_scale?: number; - right_scale?: number; - obj_or_bg?: Array<"obj" | "bg">; - }; -} - // ---- Application (Agent / Workflow) ---- export interface AppCompletionRequest { @@ -1062,9 +1021,6 @@ export interface DashScopeTaskResponse { video_url?: string; // video-style-transform returns output_video_url output_video_url?: string; - // VACE / edit prompt echoes - orig_prompt?: string; - actual_prompt?: string; // Image translation (qwen-mt-image) returns image_url image_url?: string; // qwen-mt-uni business envelope (exact casing) diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 38eeffb7..f223a6cd 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -70,8 +70,6 @@ export type { DashScopeVideoRequest, DashScopeVideoRetalkRequest, DashScopeVideoStyleTransformRequest, - DashScopeVideoVaceRequest, - WanxVaceFunction, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, diff --git a/packages/runtime/src/utils/polling.ts b/packages/runtime/src/utils/polling.ts index ef802e88..4a71d9c8 100644 --- a/packages/runtime/src/utils/polling.ts +++ b/packages/runtime/src/utils/polling.ts @@ -45,7 +45,10 @@ export async function poll(client: Client, opts: PollOptions): Promise { ); } - await new Promise((resolve) => setTimeout(resolve, opts.intervalSec * 1000)); + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) break; + const sleepMs = Math.min(opts.intervalSec * 1000, remainingMs); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); } throw new BailianError( diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 1704d742..cebfaceb 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -43,10 +43,9 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Image text translation (layout-preserving) | `bl image translate` | Default `qwen-mt-image` (async); optional `qwen-mt-image-2.0`. Not image edit. | | File multimodal translation | `bl omni translate` | `qwen-mt-uni` (async file→file). Keep `bl omni --message` for multimodal chat. | | Text-to-video / image-to-video | `bl video generate` | `wan3.0-video` | -| Video edit (happyhorse) | `bl video edit` | `happyhorse-1.0-video-edit` — not VACE | -| Talking-head / lip sync | `bl video portrait` | Fixed `videoretalk` (no `--model`) | -| Video style transform | `bl video style` | Fixed `video-style-transform` (Beijing; public URL only in v1) | -| VACE unified video edit | `bl video retouch` | Fixed `wanx2.1-vace-plus` — five `--function` modes; distinct from `bl video edit` | +| Video edit (happyhorse) | `bl video edit` | `happyhorse-1.0-video-edit` — prompt-based edit; preset comic/ink restyle → `bl video style` | +| Talking-head / lip sync | `bl video retalk` | Fixed `videoretalk` (no `--model`; Beijing only) | +| Video style transform | `bl video style` | Fixed `video-style-transform` (Beijing; public URL only in v1; 8 preset styles) | | Reference-to-video + voice | `bl video ref` | `wan3.0-video` | | Speech synthesis (TTS / voiceover) | `bl speech synthesize` | `cosyvoice-v3-flash` | | Voice clone / manage | `bl speech voice clone/list/get/update/delete/preview` | CosyVoice/Qwen-Audio: `voice-enrollment` → `speech synthesize --model`. Omni (non-realtime flash/plus only): `qwen-voice-enrollment` create/list/delete → `omni --model --voice` | @@ -56,7 +55,7 @@ BAILIAN_CALLER_TYPE=agent BAILIAN_CALLER_NAME=codex BAILIAN_SKILL_NAME=bailian-g | Image describe | `bl vision describe` | `qwen3-vl-plus`;宿主能做且未点名 → host-first | | Video / A-V understand | `bl vision describe --video` 或 `bl omni` | 视频理解默认走百炼;`omni` 默认 `qwen3.8-omni-flash`,省略 `--model` 且无 `--text-only` 时自动切换 `qwen3.5-omni-plus` | -`bl video edit` vs `bl video retouch`: edit uses happyhorse for general style/object edits; retouch is Wan 2.1 VACE with `--function` (`video_repainting` / `video_edit` / `video_extension` / `video_outpainting` / `image_reference`). They are not interchangeable. `bl video portrait` is lip-sync (videoretalk); `bl video style` is comic/ink style transform. VACE / style outputs are silent MP4. Portrait and style do not expose `--model`. +`bl video edit` vs `bl video style`: edit uses happyhorse for prompt-based style/object edits; style applies one of 8 preset comic/ink transforms (`video-style-transform`). `bl video retalk` is audio-driven lip-sync (videoretalk). Style outputs are silent MP4. Retalk and style are Beijing-only and do not expose `--model`. Unless the user explicitly specifies a model, omit `--model` and let the CLI use the active Profile’s default. diff --git a/skills/bailian-gen/reference/index.md b/skills/bailian-gen/reference/index.md index b23bd94e..89c0b437 100644 --- a/skills/bailian-gen/reference/index.md +++ b/skills/bailian-gen/reference/index.md @@ -9,37 +9,36 @@ Use this index for the skill-scoped quick index and global flags. ## Quick index -| Command | Authentication | Description | Detail | -| ----------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------- | ---------------------- | -| `bl image edit` | API Key | Edit an existing image with text instructions (Qwen-Image / Wan 2.7) | [image.md](image.md) | -| `bl image generate` | API Key | Generate images (Qwen-Image / wan2.x) | [image.md](image.md) | -| `bl image translate` | API Key | Translate text in an image (Qwen-MT-Image) | [image.md](image.md) | -| `bl omni` | API Key | Multimodal chat with text + audio output (Qwen-Omni) | [omni.md](omni.md) | -| `bl omni translate` | API Key | Translate a document, image or audio file (Qwen-MT-Uni) | [omni.md](omni.md) | -| `bl speech generate` | API Key | Generate podcast/dialogue audio content from a text prompt | [speech.md](speech.md) | -| `bl speech recognize` | API Key | Recognize speech from audio files (FunAudio-ASR / Qwen-ASR Flash) | [speech.md](speech.md) | -| `bl speech synthesize` | API Key | Synthesize speech from text | [speech.md](speech.md) | -| `bl speech vocabulary create` | API Key | Create a precompiled hot-word vocabulary for ASR | [speech.md](speech.md) | -| `bl speech vocabulary delete` | API Key | Delete a precompiled hot-word vocabulary | [speech.md](speech.md) | -| `bl speech vocabulary get` | API Key | Get details of a precompiled hot-word vocabulary | [speech.md](speech.md) | -| `bl speech vocabulary list` | API Key | List precompiled hot-word vocabularies | [speech.md](speech.md) | -| `bl speech vocabulary update` | API Key | Replace the contents of a precompiled hot-word vocabulary | [speech.md](speech.md) | -| `bl speech voice clone` | API Key | Clone a custom voice from reference audio | [speech.md](speech.md) | -| `bl speech voice delete` | API Key | Delete a custom voice | [speech.md](speech.md) | -| `bl speech voice design` | API Key | Design a custom voice from a text description | [speech.md](speech.md) | -| `bl speech voice get` | API Key | Get details of a custom voice | [speech.md](speech.md) | -| `bl speech voice list` | API Key | List custom voices | [speech.md](speech.md) | -| `bl speech voice preview` | API Key | Fetch the reference audio URL for a cloned voice | [speech.md](speech.md) | -| `bl speech voice update` | API Key | Update the reference audio of a cloned voice | [speech.md](speech.md) | -| `bl video download` | API Key | Download a completed video by task ID | [video.md](video.md) | -| `bl video edit` | API Key | Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.) | [video.md](video.md) | -| `bl video generate` | API Key | Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v) | [video.md](video.md) | -| `bl video portrait` | API Key | Drive a talking-head video with audio (VideoRetalk / videoretalk) | [video.md](video.md) | -| `bl video ref` | API Key | Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice | [video.md](video.md) | -| `bl video retouch` | API Key | Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference) | [video.md](video.md) | -| `bl video style` | API Key | Restyle a video (video-style-transform) | [video.md](video.md) | -| `bl video task get` | API Key | Query async task status | [video.md](video.md) | -| `bl vision describe` | API Key | Describe an image or video using Qwen-VL | [vision.md](vision.md) | +| Command | Authentication | Description | Detail | +| ----------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------- | +| `bl image edit` | API Key | Edit an existing image with text instructions (Qwen-Image / Wan 2.7) | [image.md](image.md) | +| `bl image generate` | API Key | Generate images (Qwen-Image / wan2.x) | [image.md](image.md) | +| `bl image translate` | API Key | Translate text in an image (Qwen-MT-Image) | [image.md](image.md) | +| `bl omni` | API Key | Multimodal chat with text + audio output (Qwen-Omni) | [omni.md](omni.md) | +| `bl omni translate` | API Key | Translate a document, image or audio file (Qwen-MT-Uni) | [omni.md](omni.md) | +| `bl speech generate` | API Key | Generate podcast/dialogue audio content from a text prompt | [speech.md](speech.md) | +| `bl speech recognize` | API Key | Recognize speech from audio files (FunAudio-ASR / Qwen-ASR Flash) | [speech.md](speech.md) | +| `bl speech synthesize` | API Key | Synthesize speech from text | [speech.md](speech.md) | +| `bl speech vocabulary create` | API Key | Create a precompiled hot-word vocabulary for ASR | [speech.md](speech.md) | +| `bl speech vocabulary delete` | API Key | Delete a precompiled hot-word vocabulary | [speech.md](speech.md) | +| `bl speech vocabulary get` | API Key | Get details of a precompiled hot-word vocabulary | [speech.md](speech.md) | +| `bl speech vocabulary list` | API Key | List precompiled hot-word vocabularies | [speech.md](speech.md) | +| `bl speech vocabulary update` | API Key | Replace the contents of a precompiled hot-word vocabulary | [speech.md](speech.md) | +| `bl speech voice clone` | API Key | Clone a custom voice from reference audio | [speech.md](speech.md) | +| `bl speech voice delete` | API Key | Delete a custom voice | [speech.md](speech.md) | +| `bl speech voice design` | API Key | Design a custom voice from a text description | [speech.md](speech.md) | +| `bl speech voice get` | API Key | Get details of a custom voice | [speech.md](speech.md) | +| `bl speech voice list` | API Key | List custom voices | [speech.md](speech.md) | +| `bl speech voice preview` | API Key | Fetch the reference audio URL for a cloned voice | [speech.md](speech.md) | +| `bl speech voice update` | API Key | Update the reference audio of a cloned voice | [speech.md](speech.md) | +| `bl video download` | API Key | Download a completed video by task ID | [video.md](video.md) | +| `bl video edit` | API Key | Edit a video with happyhorse-1.0-video-edit (prompt-based style/object edits; preset comic/ink restyle → video style) | [video.md](video.md) | +| `bl video generate` | API Key | Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v) | [video.md](video.md) | +| `bl video ref` | API Key | Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice | [video.md](video.md) | +| `bl video retalk` | API Key | Drive a talking-head video with audio (VideoRetalk) | [video.md](video.md) | +| `bl video style` | API Key | Restyle a video with 8 presets (video-style-transform); for prompt-based edit use video edit | [video.md](video.md) | +| `bl video task get` | API Key | Query async task status | [video.md](video.md) | +| `bl vision describe` | API Key | Describe an image or video using Qwen-VL | [vision.md](vision.md) | ## By group @@ -48,7 +47,7 @@ Use this index for the skill-scoped quick index and global flags. | `image` | `edit`, `generate`, `translate` | [image.md](image.md) | | `omni` | `(root)`, `translate` | [omni.md](omni.md) | | `speech` | `generate`, `recognize`, `synthesize`, `vocabulary create`, `vocabulary delete`, `vocabulary get`, `vocabulary list`, `vocabulary update`, `voice clone`, `voice delete`, `voice design`, `voice get`, `voice list`, `voice preview`, `voice update` | [speech.md](speech.md) | -| `video` | `download`, `edit`, `generate`, `portrait`, `ref`, `retouch`, `style`, `task get` | [video.md](video.md) | +| `video` | `download`, `edit`, `generate`, `ref`, `retalk`, `style`, `task get` | [video.md](video.md) | | `vision` | `describe` | [vision.md](vision.md) | ## Global flags diff --git a/skills/bailian-gen/reference/video.md b/skills/bailian-gen/reference/video.md index 4b49ef77..803ced10 100644 --- a/skills/bailian-gen/reference/video.md +++ b/skills/bailian-gen/reference/video.md @@ -7,16 +7,15 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Authentication | Description | -| ------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------- | -| `bl video download` | API Key | Download a completed video by task ID | -| `bl video edit` | API Key | Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.) | -| `bl video generate` | API Key | Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v) | -| `bl video portrait` | API Key | Drive a talking-head video with audio (VideoRetalk / videoretalk) | -| `bl video ref` | API Key | Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice | -| `bl video retouch` | API Key | Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference) | -| `bl video style` | API Key | Restyle a video (video-style-transform) | -| `bl video task get` | API Key | Query async task status | +| Command | Authentication | Description | +| ------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------- | +| `bl video download` | API Key | Download a completed video by task ID | +| `bl video edit` | API Key | Edit a video with happyhorse-1.0-video-edit (prompt-based style/object edits; preset comic/ink restyle → video style) | +| `bl video generate` | API Key | Generate a video from text or image (wan3.0-video / wan2.6-t2v / happyhorse-1.1-i2v) | +| `bl video ref` | API Key | Reference-to-video generation (wan3.0-video / happyhorse-1.1-r2v / wan2.6-r2v): multi-subject, multi-shot with voice | +| `bl video retalk` | API Key | Drive a talking-head video with audio (VideoRetalk) | +| `bl video style` | API Key | Restyle a video with 8 presets (video-style-transform); for prompt-based edit use video edit | +| `bl video task get` | API Key | Query async task status | ## Command details @@ -50,12 +49,12 @@ bl video download --task-id 3b256896-xxxx --out video.mp4 --quiet ### `bl video edit` -| Field | Value | -| ------------------ | -------------------------------------------------------------------------------------- | -| **Name** | `video edit` | -| **Description** | Edit a video with happyhorse-1.0-video-edit (style transfer, object replacement, etc.) | -| **Authentication** | API Key | -| **Usage** | `bl video edit --video --prompt [flags]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------- | +| **Name** | `video edit` | +| **Description** | Edit a video with happyhorse-1.0-video-edit (prompt-based style/object edits; preset comic/ink restyle → video style) | +| **Authentication** | API Key | +| **Usage** | `bl video edit --video --prompt [flags]` | #### Flags @@ -164,44 +163,6 @@ bl video generate --prompt "A cat playing with a ball" --watermark false bl video generate --prime --workspace-id --model wan3.0-video-prime --prompt "Ocean waves at sunset" ``` -### `bl video portrait` - -| Field | Value | -| ------------------ | ----------------------------------------------------------------------- | -| **Name** | `video portrait` | -| **Description** | Drive a talking-head video with audio (VideoRetalk / videoretalk) | -| **Authentication** | API Key | -| **Usage** | `bl video portrait --video --audio [flags]` | - -#### Flags - -| Flag | Type | Required | Description | -| --------------------------- | ------- | -------- | ------------------------------------------------------------------------------------------ | -| `--video ` | string | yes | Input video URL or local file (mp4/avi/mov) | -| `--audio ` | string | yes | Driving audio URL or local file (wav/mp3/aac) | -| `--ref-image ` | string | no | Optional reference face image when the video has multiple people | -| `--video-extension ` | boolean | no | Extend video by alternating reverse/forward playback when audio is longer (default: false) | -| `--face-threshold ` | number | no | Face match threshold 120–200 (default: 170; only with --ref-image) | -| `--download ` | string | no | Save video to file on completion (default: output dir) | -| `--async` | switch | no | Return async task id without waiting | -| `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | - -#### Notes - -- Fixed model videoretalk (Beijing). Supports temporary OSS upload for local media. Requires model access on the account. - -#### Examples - -```bash -bl video portrait --video https://example.com/face.mp4 --audio https://example.com/speech.wav --download out.mp4 -``` - -```bash -bl video portrait --video ./face.mp4 --audio ./speech.wav --ref-image ./person.jpg --face-threshold 170 -``` - ### `bl video ref` | Field | Value | @@ -256,76 +217,52 @@ bl video ref --prompt "Image 1 and Image 2 have a conversation" --image a.jpg -- bl video ref --prompt "Image 1 drinks water" --image person.jpg --watermark false ``` -### `bl video retouch` +### `bl video retalk` -| Field | Value | -| ------------------ | -------------------------------------------------------------------------------------------------- | -| **Name** | `video retouch` | -| **Description** | Wan 2.1 VACE unified video edit (repaint / local edit / extension / outpainting / image reference) | -| **Authentication** | API Key | -| **Usage** | `bl video retouch --prompt [--function ] [flags]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------- | +| **Name** | `video retalk` | +| **Description** | Drive a talking-head video with audio (VideoRetalk) | +| **Authentication** | API Key | +| **Usage** | `bl video retalk --video --audio [flags]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------------------------------------------------------------------------ | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- | -| `--prompt ` | string | yes | Edit / generation prompt (max 800 characters; server may truncate) | -| `--function ` | string | no | VACE function: video_repainting (default), video_edit, video_extension, video_outpainting, image_reference | -| `--video ` | string | no | Input video URL or local file (required for most functions) | -| `--ref-image ` | array | no | Reference image(s): image_reference 1–3; video_repainting/video_edit at most 1; unsupported for video_extension/video_outpainting | -| `--control-condition ` | string | no | Control condition (required for video_repainting; posebodyface/posebody/depth/scribble) | -| `--strength ` | number | no | Repaint strength in [0, 1] | -| `--seed ` | number | no | Random seed | -| `--prompt-extend ` | boolean | no | Enable prompt extend (true/false). Omit flag to omit the parameter (DashScope default). | -| `--watermark ` | boolean | no | Enable watermark (true/false). Omit flag to use the Profile setting or CLI default (true). | -| `--mask-image ` | string | no | Mask image for video_edit (mutually exclusive with --mask-video) | -| `--mask-video ` | string | no | Mask video for video_edit (mutually exclusive with --mask-image) | -| `--mask-frame-id ` | number | no | Mask frame id starting at 1 (video_edit) | -| `--mask-type ` | string | no | Mask type: tracking or fixed (video_edit) | -| `--expand-ratio ` | number | no | Expand ratio in [0, 1] (video_edit) | -| `--expand-mode ` | string | no | Expand mode hull/bbox/original (image mask + tracking only) | -| `--first-frame ` | string | no | First-frame image for video_extension (extends forward) | -| `--last-frame ` | string | no | Last-frame image for video_extension (extends backward) | -| `--first-clip ` | string | no | First clip for video_extension (extends forward) | -| `--last-clip ` | string | no | Last clip for video_extension (extends backward) | -| `--top-scale ` | number | no | Outpainting top scale in [1, 2] (1 = no expand) | -| `--bottom-scale ` | number | no | Outpainting bottom scale in [1, 2] | -| `--left-scale ` | number | no | Outpainting left scale in [1, 2] | -| `--right-scale ` | number | no | Outpainting right scale in [1, 2] | -| `--ref-role ` | array | no | Per-image role for image_reference (obj or bg; at most one bg) | -| `--size ` | string | no | Output size for image_reference / video_edit (1280*720, 720*1280, 960*960, 832*1088, 1088*832) | -| `--download ` | string | no | Save video to file on completion (default: output dir) | -| `--async` | switch | no | Return async task id without waiting | -| `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| --------------------------- | ------- | -------- | ------------------------------------------------------------------------------------------ | +| `--video ` | string | yes | Input video URL or local file (mp4/avi/mov) | +| `--audio ` | string | yes | Driving audio URL or local file (wav/mp3/aac) | +| `--ref-image ` | string | no | Optional reference face image when the video has multiple people | +| `--video-extension ` | boolean | no | Extend video by alternating reverse/forward playback when audio is longer (default: false) | +| `--face-threshold ` | number | no | Face match threshold 120–200 (default: 170; only with --ref-image) | +| `--download ` | string | no | Save video to this file on completion (default: /videos/.mp4) | +| `--async` | switch | no | Return async task id without waiting | +| `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes -- Fixed model wanx2.1-vace-plus (Beijing/Singapore). Distinct from `video edit` (happyhorse). Output is silent MP4. video_extension: first-frame/clip extends forward, last-frame/clip extends backward; total output is 5s. Requires model access. Do not use a boolean --video-extension alias. +- Fixed model videoretalk (Beijing only). Wait-mode polling uses at least 600s (--timeout lower values are raised). #### Examples ```bash -bl video retouch --prompt "Convert the scene to claymation" --function video_repainting --video https://example.com/in.mp4 --control-condition depth --strength 0.8 -``` - -```bash -bl video retouch --prompt "Extend the shot" --function video_extension --first-frame https://example.com/first.png +bl video retalk --video https://example.com/face.mp4 --audio https://example.com/speech.wav --download out.mp4 ``` ```bash -bl video retouch --prompt "Generate from references" --function image_reference --ref-image https://example.com/a.png --ref-image https://example.com/b.png --ref-role obj --ref-role bg --size 1280*720 +bl video retalk --video ./face.mp4 --audio ./speech.wav --ref-image ./person.jpg --face-threshold 170 ``` ### `bl video style` -| Field | Value | -| ------------------ | --------------------------------------- | -| **Name** | `video style` | -| **Description** | Restyle a video (video-style-transform) | -| **Authentication** | API Key | -| **Usage** | `bl video style --video [flags]` | +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------------- | +| **Name** | `video style` | +| **Description** | Restyle a video with 8 presets (video-style-transform); for prompt-based edit use video edit | +| **Authentication** | API Key | +| **Usage** | `bl video style --video [flags]` | #### Flags @@ -333,11 +270,11 @@ bl video retouch --prompt "Generate from references" --function image_reference | --------------------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--video ` | string | yes | Input video public URL (local paths not supported in v1) | | `--style ` | number | no | Style ID 0–7 (default: 0). 0 Japanese comic, 1 American comic, 2 fresh comic, 3 3D cartoon, 4 Chinese cartoon, 5 paper art, 6 simple illustration, 7 Chinese ink | -| `--fps ` | number | no | Output video FPS 15–25 (maps to video_fps) | +| `--fps ` | number | no | Output video FPS 15–25 (default: 15; maps to video_fps) | | `--animate-emotion ` | boolean | no | Animate facial emotion (server default: true) | -| `--min-len ` | number | no | Short-side length 540 or 720 (server default: 720) | -| `--super-resolution ` | boolean | no | Enable super-resolution (maps to use_SR; server default: false) | -| `--download ` | string | no | Save video to file on completion (default: output dir) | +| `--min-len ` | number | no | Short-side length 540 or 720 (server default: 720; 720P costs more than 540P) | +| `--super-resolution ` | boolean | no | Enable super-resolution (maps to use_SR; server default: false; with min_len=540 outputs 1080P billed as 540P) | +| `--download ` | string | no | Save video to this file on completion (default: /videos/.mp4) | | `--async` | switch | no | Return async task id without waiting | | `--poll-interval ` | number | no | Polling interval when waiting (default: 15) | | `--api-key ` | string | no | API key | @@ -345,7 +282,7 @@ bl video retouch --prompt "Generate from references" --function image_reference #### Notes -- Fixed model video-style-transform (Beijing only). Success field is output.output_video_url. Local paths are rejected until temporary OSS support is verified. Requires model access. +- Fixed model video-style-transform (Beijing only). Wait-mode polling uses at least 600s (--timeout lower values are raised). #### Examples