From e45385e08441fa5f53996d8fd4c470bdd0b782ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 10:56:50 +0000 Subject: [PATCH 1/5] [feat] canvas: video blockout tool that keeps a clip's motion, timing and camera without its appearance ## summary RFC #444 asks for a way to carry a reference clip's action, timing, camera and scene structure into a regenerated clip with a different look. The existing pieces (person masks, depth) each give part of that and have to be combined by hand. - `video-blockout` is a new canvas tool for video nodes. It tracks the named subjects (people by default) and estimates per-frame depth, then renders one frame per source frame: the scene as neutral gray relief and each tracked subject in one fixed solid colour. The result is a silent MP4 with the source's frame count and rate, registered as an ordinary video asset that can be connected as a reference video. - It needs both `video.matting` (tracking) and `video.motion_capture` (depth). The catalog reports the missing capability otherwise, and unsupported input is refused before any model call: clips over 30 s or 2048 frames, an unknown resolution, and a named subject that is not found. Tracking and depth results whose frame counts differ fail the task instead of producing a misaligned clip. - `Tracks` carries the tracker's per-instance identities, so one subject keeps its colour when its position in the instance list changes. - The tool is offered on the selection toolbar and in the video action panel (resolution and subjects) in both locales, and through the shared tool-task interface. Both user guides describe it, including that it is rendered from depth and masks and is not an editable 3D scene. - Contracts regenerated. The i18n baseline rises by one line for the tool's catalog entry, which is translated in the display layer. Refs #444 Co-Authored-By: Claude Fable 5.2 --- docs/guides/user-guide.md | 2 + docs/guides/user-guide.zh-CN.md | 2 + .../application/creation_media_publication.py | 2 +- .../application/tool_operations.py | 5 +- .../application/tool_video_recipes.py | 34 ++++++ .../src/opendirector/domain/capabilities.py | 1 + .../opendirector/domain/creation/editors.py | 2 +- .../integrations/model_adapters.py | 5 +- .../core/src/opendirector/media/blockout.py | 72 ++++++++++++ .../core/src/opendirector/media/processing.py | 4 +- scripts/i18n-baseline.json | 4 +- src/canvas/NodeSelectionToolbar.tsx | 1 + src/canvas/VideoActionEditor.tsx | 14 +++ src/canvas/toolCatalog.ts | 8 ++ src/canvas/toolTaskText.ts | 3 + src/canvas/toolText.ts | 3 + src/canvas/videoActionRuntime.ts | 8 ++ src/contracts/creation.schema.json | 2 + src/contracts/generated.ts | 4 +- src/i18n/messages/en-US/canvasShell.ts | 1 + src/i18n/messages/en-US/errors.ts | 5 + src/i18n/messages/en-US/tools.ts | 6 + src/i18n/messages/zh-CN/canvasShell.ts | 1 + src/i18n/messages/zh-CN/errors.ts | 4 + src/i18n/messages/zh-CN/tools.ts | 6 + tests/test_blockout.py | 72 ++++++++++++ tests/test_tool_tasks.py | 103 ++++++++++++++++++ tests/toolCatalog.test.ts | 21 ++++ tests/toolTaskText.test.ts | 5 + tests/videoActionRuntime.test.ts | 9 ++ 30 files changed, 399 insertions(+), 10 deletions(-) create mode 100644 packages/core/src/opendirector/media/blockout.py create mode 100644 tests/test_blockout.py diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 9fe1d001c..1cf313cf0 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -82,6 +82,8 @@ To make music from a reference recording, connect an audio node to a YuE2 music To use **Depth motion capture** on a video, add a video model with the **vLLM-Omni depth** protocol, for example `depth-anything/Video-Depth-Anything-Small` served by `vllm serve --omni`. The tool turns a clip of up to 30 seconds into a grayscale depth video at 480P or 720P, frame for frame, with near objects bright and far ones dark, ready to use as a motion and structure reference. The depth model does not generate video. +**Video blockout** turns a video of up to 30 seconds into a blockout video aligned frame by frame with the source: the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame count, frame rate and duration match the source, and the output is silent. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The blockout is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The blockout is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. + In **General** settings, you can switch themes and adjust the watermark removal option. Watermark settings affect only content generated afterward, and the actual effect depends on support from the model service. ## Make your first short film diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 2d279e8d4..1b2ab010b 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -69,6 +69,8 @@ HTTP 400。 使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。 +**视频脱模** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的白模视频:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧数、帧率和时长与原片一致,输出没有声音。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。白模视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。白模由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的白模。 + 在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。 vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可使用 `opendirector video create --duration 6.583333` 并填写其余必需参数。先运行 `opendirector video create --help` 和 `opendirector model list`;`inputRules.fractionalDuration` 表示支持小数秒,各输出规格的时长列表定义允许范围。H3 可能按模型支持的帧数对齐,拼接分段前应核对结果的实际时长。 diff --git a/packages/core/src/opendirector/application/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index 3def2c189..15f0499d1 100644 --- a/packages/core/src/opendirector/application/creation_media_publication.py +++ b/packages/core/src/opendirector/application/creation_media_publication.py @@ -37,7 +37,7 @@ def publish_media(service, data, payload): expected, allowed = 'video', {'audio'} if not actual.metadata.hasAudio: raise ContractError('invalid_input', '来源视频没有可提取的音轨。', actual.id) - elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite'}: + elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite', 'video-blockout'}: expected, allowed = 'video', {'video'} elif tool in {'audio-trim', 'audio-separation'}: expected, allowed = ('video' if tool == 'audio-separation' and actual.kind == 'video' else 'audio'), {'audio'} diff --git a/packages/core/src/opendirector/application/tool_operations.py b/packages/core/src/opendirector/application/tool_operations.py index 96e0d83b6..a2b0fb16d 100644 --- a/packages/core/src/opendirector/application/tool_operations.py +++ b/packages/core/src/opendirector/application/tool_operations.py @@ -16,7 +16,7 @@ from opendirector.domain.image_presets import PRESETS, preset_instructions from opendirector.application.tool_video_recipes import ( AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot, - subtitle_erasure, video_edit, video_matting, video_upscale, + subtitle_erasure, video_blockout, video_edit, video_matting, video_upscale, ) # Editor previews and tool tasks import this helper from the catalog module. @@ -108,4 +108,7 @@ def _preset_select(): note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'), ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture, note='逐帧估计景深,输出灰度深度视频(近处亮、远处暗),可作为视频生成的动作与结构参考;最长 30 秒。'), + ToolSpec('video-blockout', ('video',), _needs('video.matting', 'video.motion_capture'), video_blockout, + note='去除外观,只保留原片的动作、时序、机位和场景结构:场景渲染为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色;' + '输出与原片逐帧对齐的无声白模视频,最长 30 秒。'), ]} diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index 6cff2d032..4b8a896d2 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -8,6 +8,7 @@ from opendirector.domain.projects import ProjectError from opendirector.media import processing as media from opendirector.media.async_work import blocking +from opendirector.media.blockout import write_blockout def _source_video(ctx: ToolContext) -> Source: @@ -242,6 +243,39 @@ async def depth_capture(ctx: ToolContext): data = await ctx.depth(clip.read_bytes()) return [Output('video', data, 'mp4', f'深度动作捕捉 {resolution}')] +BLOCKOUT_CRF = 20 + +async def video_blockout(ctx: ToolContext): + source = _source_video(ctx) + resolution = ctx.choice('resolution', tuple(DEPTH_SHORT_EDGES), '480P') + named = bool(ctx.text('prompt')) + pairs = await ctx.concepts(ctx.text('prompt'), ('人物',)) + label = '、'.join(label for _, label in pairs) + with media.Workspace() as work: + raw = work.write('source', source.data) + info = await blocking(media.video_info, raw) + if not 0 < info['duration'] <= DEPTH_MAX_SECONDS + 0.05: + raise ProjectError(f'视频脱模需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422) + if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES: + raise ProjectError(f'视频脱模单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422) + await ctx.progress('正在整理视频') + width, height = _depth_size(info['width'], info['height'], DEPTH_SHORT_EDGES[resolution]) + clip = await blocking(media.picture, raw, work.path / 'clip.mp4', width=width, height=height) + await ctx.progress(f'正在识别并跟踪「{label}」') + tracks = await ctx.track(clip.read_bytes(), tuple(concept for concept, _ in pairs)) + if named and not any(tracks.frames): + raise ToolInputError(f'视频中没有识别到「{label}」,请换一种描述后重试。', code='tool_no_video_match', label=label) + await ctx.progress('正在估计每一帧的深度') + depth = work.write('depth.mp4', await ctx.depth(clip.read_bytes())) + await ctx.progress('正在渲染白模') + frames = await blocking(media.frames_of, depth, work.path / 'depth-frames', gray=True) + if abs(len(frames) - len(tracks.frames)) > 1: + raise ProjectError('跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。', 502) + await blocking(write_blockout, frames, tracks, work.path / 'blockout') + data = await blocking(media.encode_frames, str(work.path / 'blockout' / '%05d.png'), info['fps'], work.path / 'blockout.mp4', + crf=BLOCKOUT_CRF) + return [Output('video', data, 'mp4', f'视频脱模 {resolution}')] + async def video_edit(ctx: ToolContext): source = _source_video(ctx) prompt = ctx.text('prompt') diff --git a/packages/core/src/opendirector/domain/capabilities.py b/packages/core/src/opendirector/domain/capabilities.py index cff91e6ce..9e010b379 100644 --- a/packages/core/src/opendirector/domain/capabilities.py +++ b/packages/core/src/opendirector/domain/capabilities.py @@ -95,6 +95,7 @@ class Tracks: height: int fps: float frames: tuple[tuple[tuple[int, ...], ...], ...] + identities: tuple[tuple[int, ...], ...] = () @dataclass(frozen=True) diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index eda3f4033..fe1ea37a0 100644 --- a/packages/core/src/opendirector/domain/creation/editors.py +++ b/packages/core/src/opendirector/domain/creation/editors.py @@ -488,7 +488,7 @@ class SelectionBox(Contract): 'dynamic-poster', 'ecommerce-main', 'image-presets', 'grid-split', 'composition', 'annotation', 'video-edit', 'video-extend', 'video-partial-reshoot', 'video-upscale', 'video-frame-interpolation', 'video-depth-capture', 'video-subtitle-erasure', 'video-matting', 'video-crop', 'video-translation', - 'video-mask-composite', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] + 'video-mask-composite', 'video-blockout', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] class ToolDraftBinding(Contract): diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index ecfa09437..a3572c29e 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -950,7 +950,10 @@ async def work(): limit=512 * 1024 * 1024)) frames = tuple(tuple(tuple(int(count) for count in item['mask']['counts']) for item in frame['instances']) for frame in value['frames']) - return Tracks(int(value['width']), int(value['height']), float(value['fps'] or 24), frames) + identities = tuple(tuple(item.get('id') for item in frame['instances']) for frame in value['frames']) + if any(isinstance(identity, bool) or not isinstance(identity, int) for frame in identities for identity in frame): + identities = () + return Tracks(int(value['width']), int(value['height']), float(value['fps'] or 24), frames, identities) return await _call('submit', work) diff --git a/packages/core/src/opendirector/media/blockout.py b/packages/core/src/opendirector/media/blockout.py new file mode 100644 index 000000000..c0bf14776 --- /dev/null +++ b/packages/core/src/opendirector/media/blockout.py @@ -0,0 +1,72 @@ +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +from PIL import Image, ImageChops, ImageFilter, ImageMath + +from opendirector.domain.projects import ProjectError +from opendirector.media.processing import rle_mask + +SCENE = (206, 208, 212) +SUBJECTS = ((226, 52, 44), (40, 110, 214), (236, 176, 32), (46, 160, 84), + (150, 80, 200), (230, 120, 40), (32, 170, 180), (220, 90, 160)) +RELIEF_CELL = 4 +RELIEF_GAIN = 7.0 +WORKERS = 4 + + +def subject_colors(identities) -> dict: + colors = {} + for frame in identities: + for identity in frame: + colors.setdefault(identity, SUBJECTS[len(colors) % len(SUBJECTS)]) + return colors + + +def _relief(depth: Image.Image): + width, height = depth.size + cells = depth.convert('F').resize((max(3, width // RELIEF_CELL), max(3, height // RELIEF_CELL)), Image.Resampling.BOX) + lit = cells.resize(depth.size, Image.Resampling.BICUBIC, box=(1, 1, cells.width, cells.height)) + shaded = cells.resize(depth.size, Image.Resampling.BICUBIC, box=(0, 0, cells.width - 1, cells.height - 1)) + slope = ImageMath.lambda_eval( + lambda args: args['convert'](args['min'](args['max']((args['lit'] - args['shaded']) * RELIEF_GAIN + 128, 64), 192), 'L'), + lit=lit, shaded=shaded) + fog = cells.resize(depth.size, Image.Resampling.BICUBIC).point(lambda value: value * 0.38 + 140).convert('L') + return fog, slope + + +def _contours(depth: Image.Image) -> Image.Image: + half = depth.resize((max(1, depth.width // 2), max(1, depth.height // 2)), Image.Resampling.BILINEAR) + step = ImageChops.subtract(half.filter(ImageFilter.MaxFilter(3)), half.filter(ImageFilter.MinFilter(3))) + return step.point(lambda value: min(96, max(0, (value - 12) * 3))).resize(depth.size, Image.Resampling.BILINEAR) + + +def blockout_frame(depth: Image.Image, subjects) -> Image.Image: + fog, slope = _relief(depth) + light = ImageChops.subtract(ImageChops.add(fog, slope, 1, -128), _contours(depth)) + albedo = Image.new('RGB', depth.size, SCENE) + for color, mask in subjects: + if mask.size != depth.size: + mask = mask.resize(depth.size, Image.Resampling.BILINEAR) + albedo.paste(color, mask=mask.filter(ImageFilter.GaussianBlur(0.8))) + rim = ImageChops.subtract(mask.filter(ImageFilter.MaxFilter(3)), mask.filter(ImageFilter.MinFilter(3))) + light = ImageChops.subtract(light, rim.point(lambda value: value // 3)) + return ImageChops.multiply(albedo, Image.merge('RGB', (light, light, light))) + + +def write_blockout(depth_frames: list[Path], tracks, folder: Path) -> int: + if not depth_frames: + raise ProjectError('视频中没有可处理的画面。', 422) + identities = tracks.identities or tuple(tuple(range(len(frame))) for frame in tracks.frames) + colors = subject_colors(identities) + folder.mkdir() + + def render(index): + subjects = [] + if index < len(tracks.frames): + subjects = [(colors[identity], rle_mask(counts, tracks.width, tracks.height)) + for identity, counts in zip(identities[index], tracks.frames[index])] + blockout_frame(Image.open(depth_frames[index]).convert('L'), subjects).save(folder / f'{index:05d}.png', compress_level=1) + + with ThreadPoolExecutor(max_workers=WORKERS) as pool: + list(pool.map(render, range(len(depth_frames)))) + return len(colors) diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index 6cd9be5b7..85a927f5b 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -259,10 +259,10 @@ def frames_of(source: Path, folder: Path, *, gray=False) -> list[Path]: return sorted(folder.glob('*.png')) -def encode_frames(pattern: str, fps: float, out: Path) -> bytes: +def encode_frames(pattern: str, fps: float, out: Path, *, crf: int = 12) -> bytes: """A silent H.264 clip from an image-sequence pattern.""" _run(['ffmpeg', '-v', 'error', '-y', '-framerate', f'{fps:.6f}', '-i', pattern, '-vf', 'format=yuv420p', - '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '12', '-movflags', '+faststart', str(out)]) + '-c:v', 'libx264', '-preset', 'veryfast', '-crf', str(crf), '-movflags', '+faststart', str(out)]) return out.read_bytes() diff --git a/scripts/i18n-baseline.json b/scripts/i18n-baseline.json index f10ddb53c..5ec454f17 100644 --- a/scripts/i18n-baseline.json +++ b/scripts/i18n-baseline.json @@ -1,5 +1,5 @@ { - "total": 169, + "total": 170, "counts": { "src/canvas/assets.ts": 14, "src/canvas/dataBoundary.ts": 3, @@ -9,7 +9,7 @@ "src/canvas/model.ts": 1, "src/canvas/NodeComposer.tsx": 1, "src/canvas/referenceMentions.ts": 1, - "src/canvas/toolCatalog.ts": 127, + "src/canvas/toolCatalog.ts": 128, "src/canvas/workspace/useWorkspaceTransfer.ts": 1 } } diff --git a/src/canvas/NodeSelectionToolbar.tsx b/src/canvas/NodeSelectionToolbar.tsx index 09b33f921..da4c8001f 100644 --- a/src/canvas/NodeSelectionToolbar.tsx +++ b/src/canvas/NodeSelectionToolbar.tsx @@ -452,6 +452,7 @@ export function NodeSelectionToolbar({ t("canvas.selection.depthCapture"), "subject", ); + addTool("video-blockout", t("canvas.selection.videoBlockout"), "subject"); addEditor("video-trim", t("canvas.selection.trimVideo"), "trim", "trim"); addMenu( "sound-separation", diff --git a/src/canvas/VideoActionEditor.tsx b/src/canvas/VideoActionEditor.tsx index 697d298eb..683b8473d 100644 --- a/src/canvas/VideoActionEditor.tsx +++ b/src/canvas/VideoActionEditor.tsx @@ -791,6 +791,12 @@ function VideoActionSession({ label: "tools.videoEditor.prompt.mattingLabel", placeholder: "tools.videoEditor.prompt.mattingPlaceholder", } + : tool === "video-blockout" + ? { + key: "prompt", + label: "tools.videoEditor.prompt.blockoutLabel", + placeholder: "tools.videoEditor.prompt.blockoutPlaceholder", + } : tool === "audio-separation" && parameters.mode === "description" ? { key: "description", @@ -1245,6 +1251,14 @@ function VideoActionSession({ ["480P", "480P"], ["720P", "720P"], ])} + {tool === "video-blockout" && + choices(t("tools.videoEditor.blockout.resolution"), "resolution", [ + ["480P", "480P"], + ["720P", "720P"], + ])} + {tool === "video-blockout" && ( +

{t("tools.videoEditor.blockout.hint")}

+ )} {tool === "video-frame-interpolation" && choices(t("tools.videoEditor.interpolation.fps"), "fps", [ [30, "30 FPS"], diff --git a/src/canvas/toolCatalog.ts b/src/canvas/toolCatalog.ts index 4c64de1e4..198704917 100644 --- a/src/canvas/toolCatalog.ts +++ b/src/canvas/toolCatalog.ts @@ -35,6 +35,7 @@ export type CanvasToolId = | "video-crop" | "video-translation" | "video-mask-composite" + | "video-blockout" | "extract-audio" | "audio-separation" | "video-trim" @@ -448,6 +449,13 @@ export const CANVAS_TOOLS: readonly CanvasToolDefinition[] = [ [choice("resolution", "清晰度", ["480P", "720P"])], { category: "video", sources: ["video"], parameterCoverage: "entry-only" }, ), + tool( + "video-blockout", + "视频脱模", + "去除外观,只保留原片的动作、时序、机位和场景结构:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 480P / 720P、与原片逐帧对齐的白模视频,素材最长 30 秒;需要接入视频跟踪和深度模型。", + [choice("resolution", "清晰度", ["480P", "720P"])], + { category: "video", sources: ["video"], parameterCoverage: "entry-only" }, + ), tool( "video-mask-composite", "遮罩合成", diff --git a/src/canvas/toolTaskText.ts b/src/canvas/toolTaskText.ts index d7b288eab..c3aa57473 100644 --- a/src/canvas/toolTaskText.ts +++ b/src/canvas/toolTaskText.ts @@ -36,6 +36,7 @@ const PHASE: Record = { 正在整理视频: "errors.tools.phase.organizeVideo", 正在合成抠像视频: "errors.tools.phase.matteVideo", 正在估计每一帧的深度: "errors.tools.phase.depth", + 正在渲染白模: "errors.tools.phase.blockout", 正在分离音轨: "errors.tools.phase.separateAudio", 正在放大视频: "errors.tools.phase.upscaleVideo", 正在保存结果: "errors.tools.phase.save", @@ -44,6 +45,8 @@ const PHASE: Record = { const ERROR: Record = { "服务重启,任务已中断,请重新提交。": "errors.tools.error.interrupted", "已取消。": "errors.tools.error.cancelled", + "跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。": + "errors.tools.error.blockoutMisaligned", "工具执行出错,请检查素材和参数后重试。": "errors.tools.error.failed", "生成结果处理失败,请检查服务协议;不会自动重新提交。": "errors.tools.error.resultProcessing", diff --git a/src/canvas/toolText.ts b/src/canvas/toolText.ts index 6248ad108..7228db0d2 100644 --- a/src/canvas/toolText.ts +++ b/src/canvas/toolText.ts @@ -152,6 +152,9 @@ const EN: Record = { "选择黑色、绿色或透明背景,或输出黑底白色的对象遮罩;输出格式由服务提供。": "Choose a black, green, or transparent background, or output a white-on-black object mask; output formats depend on the service.", "遮罩": "Mask", + "视频脱模": "Video Blockout", + "去除外观,只保留原片的动作、时序、机位和场景结构:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 480P / 720P、与原片逐帧对齐的白模视频,素材最长 30 秒;需要接入视频跟踪和深度模型。": + "Strips appearance and keeps the source's motion, timing, camera and scene structure: the scene becomes gray relief and each tracked subject one solid color. Outputs a 480P / 720P blockout video aligned frame by frame with the source, up to 30 seconds; requires a video tracking model and a depth model.", "遮罩合成": "Mask Composite", "保留内容视频在遮罩视频白色区域内的画面,其余变黑;可拉伸遮罩内的明暗范围。本地处理,不调用模型。": "Keeps the content video inside the white area of the mask video and blacks out the rest; can stretch brightness inside the mask. Local processing, no model.", diff --git a/src/canvas/videoActionRuntime.ts b/src/canvas/videoActionRuntime.ts index 077efebb7..65c69cdcd 100644 --- a/src/canvas/videoActionRuntime.ts +++ b/src/canvas/videoActionRuntime.ts @@ -112,6 +112,8 @@ export function initialVideoActionParameters( return { resolution: "4K" }; case "video-depth-capture": return { resolution: "480P" }; + case "video-blockout": + return { resolution: "480P", prompt: "" }; case "video-frame-interpolation": return { fps: 30 }; case "video-matting": @@ -142,6 +144,7 @@ export function videoActionInputError( > = { "video-upscale": { key: "resolution", values: ["2K", "4K"] }, "video-depth-capture": { key: "resolution", values: ["480P", "720P"] }, + "video-blockout": { key: "resolution", values: ["480P", "720P"] }, "video-frame-interpolation": { key: "fps", values: [30, 60] }, "video-matting": { key: "background", @@ -187,6 +190,11 @@ export function videoActionInputError( (!Number.isFinite(duration) || duration <= 0 || duration > 30) ) return tNow("errors.videoAction.depthDuration"); + if ( + tool === "video-blockout" && + (!Number.isFinite(duration) || duration <= 0 || duration > 30) + ) + return tNow("errors.videoAction.blockoutDuration"); if ( tool === "audio-separation" && parameters.mode === "description" && diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 9e28e4748..f88cac35f 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -9483,6 +9483,7 @@ "video-crop", "video-translation", "video-mask-composite", + "video-blockout", "extract-audio", "audio-separation", "video-trim", @@ -28153,6 +28154,7 @@ "video-crop", "video-translation", "video-mask-composite", + "video-blockout", "extract-audio", "audio-separation", "video-trim", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index d9b149d0c..5d9d3cf9a 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -939,7 +939,7 @@ export interface MediaCanvasItemInput extends CanvasItemBaseInput { } export interface MediaEditDataInput extends ContractInput { - readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; + readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "video-blockout" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; readonly sources?: ReadonlyArray; readonly sourceItems?: ReadonlyArray; readonly parameters?: Readonly>; @@ -2835,7 +2835,7 @@ export interface MediaCanvasItem extends CanvasItemBase { } export interface MediaEditData extends Contract { - readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; + readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "video-blockout" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; readonly sources: ReadonlyArray; readonly sourceItems: ReadonlyArray; readonly parameters: Readonly>; diff --git a/src/i18n/messages/en-US/canvasShell.ts b/src/i18n/messages/en-US/canvasShell.ts index 7bb3bf744..739d11fb5 100644 --- a/src/i18n/messages/en-US/canvasShell.ts +++ b/src/i18n/messages/en-US/canvasShell.ts @@ -127,6 +127,7 @@ export const canvasShell = { "canvas.selection.lastFrame": "Last frame", "canvas.selection.customFrame": "Capture custom frame", "canvas.selection.depthCapture": "Depth motion capture", + "canvas.selection.videoBlockout": "Video blockout", "canvas.selection.trimVideo": "Trim duration", "canvas.selection.audioSeparation": "Separate audio", "canvas.selection.extractAudio": "Extract audio", diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index 105f4cc5e..add13b668 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -328,6 +328,7 @@ export const errors = { "errors.tools.phase.track": 'Detecting and tracking "{labels}"', "errors.tools.phase.matteVideo": "Compositing the matte video", "errors.tools.phase.depth": "Estimating depth for every frame", + "errors.tools.phase.blockout": "Rendering the blockout", "errors.tools.phase.separateAudio": "Separating the audio track", "errors.tools.phase.upscaleVideo": "Upscaling the video", "errors.tools.phase.interpolate": "Interpolating to {fps} fps", @@ -336,6 +337,8 @@ export const errors = { "errors.tools.error.interrupted": "The service restarted and the task was interrupted. Submit it again.", "errors.tools.error.cancelled": "Cancelled.", + "errors.tools.error.blockoutMisaligned": + "Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.", "errors.tools.error.failed": "The tool failed. Check the media and parameters and try again.", "errors.tools.error.resultProcessing": @@ -458,6 +461,8 @@ export const errors = { "errors.videoAction.maskSource": "Choose a mask video from the canvas.", "errors.videoAction.depthDuration": "Depth motion capture needs media no longer than 30 seconds.", + "errors.videoAction.blockoutDuration": + "Video blockout needs media no longer than 30 seconds.", "errors.videoAction.audioDescription": "Describe the sound to separate.", "errors.videoAction.confirmSubtitles": "Confirm subtitle removal.", "errors.videoAction.frameNotReady": diff --git a/src/i18n/messages/en-US/tools.ts b/src/i18n/messages/en-US/tools.ts index 859460c28..def9323b3 100644 --- a/src/i18n/messages/en-US/tools.ts +++ b/src/i18n/messages/en-US/tools.ts @@ -226,6 +226,9 @@ export const tools = { "tools.videoEditor.prompt.mattingLabel": "Subjects to matte", "tools.videoEditor.prompt.mattingPlaceholder": "People are matted by default; list several subjects separated by commas, e.g. person, dog", + "tools.videoEditor.prompt.blockoutLabel": "Colored subjects", + "tools.videoEditor.prompt.blockoutPlaceholder": + "People are colored by default; list several subjects separated by commas, e.g. person, dog", "tools.videoEditor.prompt.soundLabel": "Sound description", "tools.videoEditor.prompt.soundPlaceholder": "e.g. rain, footsteps, or voices in the scene…", @@ -270,6 +273,9 @@ export const tools = { "The box covers the lower subtitle band by default; drag it to the actual subtitle position. Sound is unchanged.", "tools.videoEditor.upscale.resolution": "Output resolution", "tools.videoEditor.depth.resolution": "Output resolution", + "tools.videoEditor.blockout.resolution": "Output resolution", + "tools.videoEditor.blockout.hint": + "Outputs a silent blockout video aligned frame by frame with the source: the scene as gray relief and each tracked subject in one fixed color, with none of the source's appearance. Use it as a reference video so generation follows the source's motion, pacing and camera.", "tools.videoEditor.interpolation.fps": "Target frame rate", "tools.videoEditor.matting.mask": "Mask (white object on black)", "tools.videoEditor.composite.mask": "Mask video", diff --git a/src/i18n/messages/zh-CN/canvasShell.ts b/src/i18n/messages/zh-CN/canvasShell.ts index b813463fc..535c4ea2c 100644 --- a/src/i18n/messages/zh-CN/canvasShell.ts +++ b/src/i18n/messages/zh-CN/canvasShell.ts @@ -125,6 +125,7 @@ export const canvasShell = { "canvas.selection.lastFrame": "尾帧", "canvas.selection.customFrame": "自定义截帧", "canvas.selection.depthCapture": "深度动作捕捉", + "canvas.selection.videoBlockout": "视频脱模", "canvas.selection.trimVideo": "时长修剪", "canvas.selection.audioSeparation": "声音分离", "canvas.selection.extractAudio": "提取音频", diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index 2941324cf..4cba8211f 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -251,6 +251,7 @@ export const errors = { "errors.tools.phase.track": "正在识别并跟踪「{labels}」", "errors.tools.phase.matteVideo": "正在合成抠像视频", "errors.tools.phase.depth": "正在估计每一帧的深度", + "errors.tools.phase.blockout": "正在渲染白模", "errors.tools.phase.separateAudio": "正在分离音轨", "errors.tools.phase.upscaleVideo": "正在放大视频", "errors.tools.phase.interpolate": "正在补帧到 {fps} fps", @@ -258,6 +259,8 @@ export const errors = { "errors.tools.phase.generic": "正在处理素材…", "errors.tools.error.interrupted": "服务重启,任务已中断,请重新提交。", "errors.tools.error.cancelled": "已取消。", + "errors.tools.error.blockoutMisaligned": + "跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。", "errors.tools.error.failed": "工具执行出错,请检查素材和参数后重试。", "errors.tools.error.resultProcessing": "生成结果处理失败,请检查服务协议;不会自动重新提交。", @@ -354,6 +357,7 @@ export const errors = { "errors.videoAction.minDuration": "视频编辑需要 4–30 秒的素材。", "errors.videoAction.maskSource": "请选择画布上的遮罩视频。", "errors.videoAction.depthDuration": "深度动作捕捉需要不超过 30 秒的素材。", + "errors.videoAction.blockoutDuration": "视频脱模需要不超过 30 秒的素材。", "errors.videoAction.audioDescription": "请描述要分离的声音。", "errors.videoAction.confirmSubtitles": "请确认擦除字幕。", "errors.videoAction.frameNotReady": "当前视频帧尚未解码完成,请稍候再截取。", diff --git a/src/i18n/messages/zh-CN/tools.ts b/src/i18n/messages/zh-CN/tools.ts index b13e25bda..319212600 100644 --- a/src/i18n/messages/zh-CN/tools.ts +++ b/src/i18n/messages/zh-CN/tools.ts @@ -210,6 +210,9 @@ export const tools = { "tools.videoEditor.prompt.mattingLabel": "抠像对象", "tools.videoEditor.prompt.mattingPlaceholder": "默认抠出人物;可写多个对象,用逗号分隔,如:人物,狗", + "tools.videoEditor.prompt.blockoutLabel": "着色对象", + "tools.videoEditor.prompt.blockoutPlaceholder": + "默认给人物着色;可写多个对象,用逗号分隔,如:人物,狗", "tools.videoEditor.prompt.soundLabel": "声音描述", "tools.videoEditor.prompt.soundPlaceholder": "例如:雨声、脚步声或画面中的人声…", @@ -252,6 +255,9 @@ export const tools = { "选框默认覆盖底部字幕带,可拖动到字幕实际位置;声音保持不变。", "tools.videoEditor.upscale.resolution": "输出清晰度", "tools.videoEditor.depth.resolution": "输出清晰度", + "tools.videoEditor.blockout.resolution": "输出清晰度", + "tools.videoEditor.blockout.hint": + "输出与原片逐帧对齐的无声白模视频:场景为灰色浮雕,每个跟踪到的对象固定一种颜色,不带原片的外观。可作为参考视频,让生成沿用原片的动作、节奏和机位。", "tools.videoEditor.interpolation.fps": "目标帧率", "tools.videoEditor.matting.mask": "遮罩(黑底白色对象)", "tools.videoEditor.composite.mask": "遮罩视频", diff --git a/tests/test_blockout.py b/tests/test_blockout.py new file mode 100644 index 000000000..2b3a531cb --- /dev/null +++ b/tests/test_blockout.py @@ -0,0 +1,72 @@ +import pytest +from PIL import Image + +from opendirector.domain.capabilities import Tracks +from opendirector.domain.projects import ProjectError +from opendirector.media.blockout import SCENE, SUBJECTS, blockout_frame, subject_colors, write_blockout + +pytestmark = [pytest.mark.cpu, pytest.mark.ready] + +WIDTH, HEIGHT = 32, 16 +LEFT = (0, 8 * HEIGHT, 24 * HEIGHT) +RIGHT = (24 * HEIGHT, 8 * HEIGHT) + + +def depth_frames(folder, count, shade=96): + folder.mkdir() + paths = [] + for index in range(count): + paths.append(folder / f'{index:05d}.png') + Image.new('L', (WIDTH, HEIGHT), shade).save(paths[-1]) + return paths + + +def tint(pixel): + return max(range(len(SUBJECTS)), key=lambda index: -sum((a - b) ** 2 for a, b in zip(pixel, SUBJECTS[index]))) + + +def is_gray(pixel): + return max(pixel) - min(pixel) < 8 + + +def test_colours_follow_identities_in_order_of_first_appearance(): + colors = subject_colors(((7,), (7, 3), (3, 11))) + assert list(colors) == [7, 3, 11] and [colors[key] for key in (7, 3, 11)] == list(SUBJECTS[:3]) + assert len(subject_colors((tuple(range(len(SUBJECTS) + 1)),))) == len(SUBJECTS) + 1 + + +def test_one_identity_keeps_its_colour_when_its_position_among_instances_changes(tmp_path): + tracks = Tracks(WIDTH, HEIGHT, 24.0, ((LEFT, RIGHT), (RIGHT, LEFT)), ((5, 9), (9, 5))) + assert write_blockout(depth_frames(tmp_path / 'depth', 2), tracks, tmp_path / 'out') == 2 + first, second = (Image.open(tmp_path / 'out' / f'{index:05d}.png').convert('RGB') for index in range(2)) + assert tint(first.getpixel((3, 8))) == tint(second.getpixel((3, 8))) == 0 + assert tint(first.getpixel((28, 8))) == tint(second.getpixel((28, 8))) == 1 + assert is_gray(first.getpixel((16, 8))) + + +def test_every_depth_frame_is_rendered_and_untracked_frames_keep_the_scene(tmp_path): + tracks = Tracks(WIDTH, HEIGHT, 24.0, ((LEFT,), ())) + assert write_blockout(depth_frames(tmp_path / 'depth', 3), tracks, tmp_path / 'out') == 1 + frames = [Image.open(path).convert('RGB') for path in sorted((tmp_path / 'out').glob('*.png'))] + assert len(frames) == 3 and all(frame.size == (WIDTH, HEIGHT) for frame in frames) + assert tint(frames[0].getpixel((3, 8))) == 0 and not is_gray(frames[0].getpixel((3, 8))) + assert all(is_gray(frame.getpixel((3, 8))) for frame in frames[1:]) + with pytest.raises(ProjectError): + write_blockout([], tracks, tmp_path / 'empty') + + +def test_relief_is_neutral_with_nearer_surfaces_lighter_and_depth_steps_outlined(): + step = Image.new('L', (64, 32), 40) + step.paste(200, (32, 0, 64, 32)) + frame = blockout_frame(step, []) + far, near, edge = frame.getpixel((8, 16)), frame.getpixel((56, 16)), frame.getpixel((31, 16)) + assert is_gray(far) and is_gray(near) and near[0] > far[0] + 30 + assert edge[0] < far[0] + assert all(value <= limit for value, limit in zip(near, SCENE)) + + +def test_a_mask_of_another_size_is_fitted_to_the_depth_frame(): + mask = Image.new('L', (16, 8), 0) + mask.paste(255, (0, 0, 8, 8)) + frame = blockout_frame(Image.new('L', (64, 32), 96), [(SUBJECTS[1], mask)]) + assert tint(frame.getpixel((12, 16))) == 1 and is_gray(frame.getpixel((52, 16))) diff --git a/tests/test_tool_tasks.py b/tests/test_tool_tasks.py index 9dae12a07..f84c6ff5f 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -974,6 +974,109 @@ def test_depth_capture_rejects_long_clips_and_unknown_resolutions_before_calling assert log == [] +def configure_blockout(store): + configs = configure(store, SAM3) + configs.save(*VDA, '', connection_type='self_hosted', protocol='vllm_omni_depth') + return configs + + +def blockout_server(prompts, depths, tmp_path, *, empty=False, shade=40): + track, depth = tracking_server(prompts, empty=empty), depth_server(depths, tmp_path, shade=shade) + return lambda request: (track if request.url.path == '/v1/videos/segmentations' else depth)(request) + + +def output_frames(store, project_id, task, tmp_path): + path = tmp_path / 'blockout.mp4' + path.write_bytes(CreationToolAssets(store).read_bytes(project_id, task['outputs'][0]['id'])) + folder = tmp_path / f"frames-{task['id']}" + folder.mkdir() + subprocess.run(['ffmpeg', '-v', 'error', '-i', str(path), '-fps_mode', 'passthrough', str(folder / '%05d.png')], + capture_output=True, check=True) + return [Image.open(item).convert('RGB') for item in sorted(folder.glob('*.png'))], probe(path, 'stream=r_frame_rate,codec_name') + + +@pytest.mark.parametrize(('instance', 'expected'), [({'id': 4}, ((4,),) * 24), ({}, ()), ({'id': '4'}, ())], + ids=['integer-identities', 'no-identities', 'non-integer-identities']) +def test_tracking_reports_identities_only_when_every_instance_has_an_integer_one(project, instance, expected): + store, _, _ = project + config = configure(store, SAM3).list()[0] + config = ModelConfigs(store.local.repository).resolve(config['id'], config['kind']) + + def handle(request): + value = {'score': 0.9, 'box': [0, 0, 32, 36], 'mask': {'size': [36, 64], 'counts': [0, 32 * 36, 32 * 36]}, **instance} + frames = [{'frame_index': index, 'instances': [value]} for index in range(24)] + return httpx.Response(200, json={'width': 64, 'height': 36, 'num_frames': 24, 'fps': 24.0, 'objects': [], 'frames': frames}) + + from opendirector.domain.capabilities import TrackRequest + tracks = asyncio.run(adapter_for(config, httpx.MockTransport(handle), 0).track(config, TrackRequest(video=b'clip', concepts=('person',)))) + assert tracks.identities == expected and len(tracks.frames) == 24 + + +def test_video_blockout_needs_both_a_tracking_and_a_depth_model(project): + store, _, _ = project + tools = {item['id']: item for item in ToolTasks(store.local, configure(store, SAM3), None, projects=store).catalog()['tools']} + assert not tools['video-blockout']['available'] and tools['video-blockout']['reason'] == '需要接入具备「深度动作捕捉」能力的模型。' + tools = {item['id']: item for item in ToolTasks(store.local, configure_blockout(store), None, projects=store).catalog()['tools']} + assert tools['video-blockout']['available'] + assert [item['capability'] for item in tools['video-blockout']['requires']] == ['video.matting', 'video.motion_capture'] + + +def test_video_blockout_keeps_every_frame_and_colours_the_tracked_subject(project, tmp_path): + store, project_id, session = project + source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) + prompts, depths = [], [] + task = run(store, configure_blockout(store), httpx.MockTransport(blockout_server(prompts, depths, tmp_path)), project_id, session, + {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': {'resolution': '480P'}}) + assert task['status'] == 'succeeded', task['error'] + assert prompts == ['person'] and [(item['width'], item['height'], item['frames']) for item in depths] == [(64, 36, 24)] + assert task['modelConfigIds'].keys() == {'video.matting', 'video.motion_capture'} + output = task['outputs'][0] + assert output['type'] == 'video/mp4' and (output['width'], output['height']) == (64, 36) and output['title'] == '视频脱模 480P' + frames, stream = output_frames(store, project_id, task, tmp_path) + assert len(frames) == 24 and stream == {'codec_name': 'h264', 'r_frame_rate': '24/1'} + for frame in (frames[0], frames[-1]): + red, green, blue = frame.getpixel((12, 18)) + assert red > 120 and green < 70 and blue < 70 + red, green, blue = frame.getpixel((52, 18)) + assert abs(red - green) < 12 and abs(green - blue) < 12 and 90 < green < 200 + + +def test_video_blockout_without_a_subject_keeps_the_scene_unless_one_was_named(project, tmp_path): + store, project_id, session = project + source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) + configs = configure_blockout(store) + prompts, depths = [], [] + server = httpx.MockTransport(blockout_server(prompts, depths, tmp_path, empty=True)) + task = run(store, configs, server, project_id, session, {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': {}}) + assert task['status'] == 'succeeded', task['error'] + frames, _ = output_frames(store, project_id, task, tmp_path) + red, green, blue = frames[0].getpixel((12, 18)) + assert len(frames) == 24 and abs(red - green) < 12 and abs(green - blue) < 12 + task = run(store, configs, server, project_id, session, + {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': {'prompt': '猫咪'}}) + assert task['status'] == 'failed' and task['errorDetails'] == {'code': 'tool_no_video_match', 'params': {'label': '猫咪'}} + assert prompts == ['person', 'cat'] and len(depths) == 1 + + +def test_video_blockout_rejects_unusable_input_before_calling_a_model_and_misaligned_results_after(project, tmp_path): + store, project_id, session = project + configs = configure_blockout(store) + prompts, depths = [], [] + server = httpx.MockTransport(blockout_server(prompts, depths, tmp_path)) + long = upload(store, project_id, session, 'long.mp4', mp4(31)) + task = run(store, configs, server, project_id, session, {'tool': 'video-blockout', 'sourceAssetIds': [long], 'parameters': {}}) + assert task['status'] == 'failed' and '不超过 30 秒' in task['error'] + short = upload(store, project_id, session, 'short.mp4', mp4(1)) + task = run(store, configs, server, project_id, session, + {'tool': 'video-blockout', 'sourceAssetIds': [short], 'parameters': {'resolution': '1080P'}}) + assert task['status'] == 'failed' and '不在可选范围内' in task['error'] + assert prompts == [] and depths == [] + double = upload(store, project_id, session, 'double.mp4', mp4(2)) + task = run(store, configs, server, project_id, session, {'tool': 'video-blockout', 'sourceAssetIds': [double], 'parameters': {}}) + assert task['status'] == 'failed' and '帧数不一致' in task['error'] and task['outputs'] == [] + assert depths[-1]['frames'] == 48 + + def test_cancel_drains_an_inflight_write_so_the_task_never_stays_running(project): """A cancelled task must not be resurrected by the write it interrupted.""" store, project_id, session = project diff --git a/tests/toolCatalog.test.ts b/tests/toolCatalog.test.ts index 0ec6f48ca..bbcf36da9 100644 --- a/tests/toolCatalog.test.ts +++ b/tests/toolCatalog.test.ts @@ -351,6 +351,27 @@ test("video edit uses actual 4–30 second source metadata and rejects invented confirmed, ).some((error) => error.includes("可用选项")), ); + for (const resolution of ["480P", "720P"]) + assert.deepEqual( + validateToolTask( + createCanvasToolTask("video-blockout", [video.nodeId], { + resolution, + prompt: "人物,狗", + }), + [video], + confirmed, + ), + [], + ); + assert.ok( + validateToolTask( + createCanvasToolTask("video-blockout", [video.nodeId], { + resolution: "1080P", + }), + [video], + confirmed, + ).some((error) => error.includes("可用选项")), + ); const noExtra = CANVAS_TOOLS.find( (tool) => tool.id === "video-subtitle-erasure", )!; diff --git a/tests/toolTaskText.test.ts b/tests/toolTaskText.test.ts index b00e6e6d5..cf7e89874 100644 --- a/tests/toolTaskText.test.ts +++ b/tests/toolTaskText.test.ts @@ -15,6 +15,7 @@ test("tool progress messages are localized, including counters", () => { ); assert.equal(toolTaskPhase("正在补帧到 60 fps"), "Interpolating to 60 fps"); assert.equal(toolTaskPhase("正在识别并跟踪「猫、狗」"), 'Detecting and tracking "猫、狗"'); + assert.equal(toolTaskPhase("正在渲染白模"), "Rendering the blockout"); assert.equal(toolTaskPhase("provider custom text"), "provider custom text"); assert.equal(toolTaskPhase(null), undefined); assert.equal(toolTaskPhase("正在生成人物三视图(1/1)"), "Generating Character three-view (1/1)"); @@ -37,6 +38,10 @@ test("tool task errors never leak persisted Chinese", () => { toolTaskError("工具执行出错,请检查素材和参数后重试。"), "The tool failed. Check the media and parameters and try again.", ); + assert.match( + toolTaskError("跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。")!, + /different frame counts/, + ); assert.equal( toolTaskError("unexpected provider exception"), "unexpected provider exception", diff --git a/tests/videoActionRuntime.test.ts b/tests/videoActionRuntime.test.ts index 422a71ece..1e70c8d7a 100644 --- a/tests/videoActionRuntime.test.ts +++ b/tests/videoActionRuntime.test.ts @@ -42,6 +42,7 @@ test("dedicated video settings survive the shared task persistence boundary", () for (const tool of [ "video-upscale", "video-depth-capture", + "video-blockout", "video-frame-interpolation", "video-matting", "audio-separation", @@ -120,6 +121,14 @@ test("AI video controls reject incomplete descriptions, invalid restored choices )!, /30/, ); + assert.match( + videoActionInputError("video-blockout", { resolution: "720P" }, 31, range)!, + /视频脱模.*30/, + ); + assert.match( + videoActionInputError("video-blockout", { resolution: "1080P" }, 6, range)!, + /选项/, + ); assert.match( videoActionInputError("video-frame-interpolation", { fps: 48 }, 6, range)!, /选项/, From 1a2c4e8c25d79538a5292b335b239ddd2f1b1d65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 11:38:48 +0000 Subject: [PATCH 2/5] [feat] canvas: keep video blockout on the source's timeline, bound its size and give its errors codes ## summary Follow-up to the video blockout tool from a pre-review of e45385e0. - A variable-frame-rate source lost its timing: every decoded frame was kept and the result was then encoded at a constant rate, so an 80-frame 3.8 s clip came out 2.7 s long. The clip sent to tracking and depth is now conformed to the source's nominal rate, as video matting does, so the blockout keeps the source's duration. A constant-rate source keeps its frame count as before. - The duration and frame-count checks now run before the subjects are resolved, so a refused clip makes no model call at all, including the chat call that translates a subject name. The previous commit message said a named subject that is not found is refused before any model call; it is refused after tracking and before depth. - The three blockout refusals carry codes (`tool_blockout_duration`, `tool_blockout_frames`, `tool_blockout_misaligned`) with English copy in the API and both locales in the canvas, in place of the generic "did not complete" text. - The encoded blockout is capped at 8 Mbit/s, so 30 seconds cannot exceed the 50 MB asset limit whatever the frame rate or content. - A prompt of separators only is treated as no named subject. - Tests: the two tests that called ffmpeg with `-fps_mode` now decode through `media.frames_of`, which also runs on FFmpeg 4. Added cases for a variable-rate source, the 2048-frame limit, one frame of difference between tracking and depth, a refused clip with a subject that would need translation, the bitrate ceiling, colour reuse past eight subjects, and publication of a blockout from a video item. Refs #444 Co-Authored-By: Claude Fable 5.2 --- apps/api/src/opendirector_api/localization.py | 3 + docs/guides/user-guide.md | 2 +- docs/guides/user-guide.zh-CN.md | 2 +- .../application/tool_video_recipes.py | 18 ++- .../core/src/opendirector/media/blockout.py | 3 +- .../core/src/opendirector/media/processing.py | 5 +- src/canvas/toolTaskText.ts | 5 +- src/i18n/messages/en-US/errors.ts | 4 + src/i18n/messages/zh-CN/errors.ts | 4 + tests/test_blockout.py | 6 +- tests/test_creation_media_publication.py | 24 +++ tests/test_localization.py | 10 ++ tests/test_tool_tasks.py | 144 +++++++++++++----- tests/toolTaskText.test.ts | 14 +- 14 files changed, 182 insertions(+), 62 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 50de34034..fcdb7252b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -75,6 +75,9 @@ 'capability_connection_changed': 'The model connection changed during the capability check. Submit again.', 'tool_concept_translation': 'Use a short English subject description, or add a chat model in Models to translate it automatically.', 'tool_no_video_match': 'The requested subject was not found in the video. Try a different description.', + 'tool_blockout_duration': 'Video blockout needs a clip no longer than 30 seconds. Trim the video first.', + 'tool_blockout_frames': 'Video blockout processes at most 2048 frames at a time. Trim the video or lower its frame rate first.', + 'tool_blockout_misaligned': 'Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.', 'voice_upload_type': 'Upload the voice recording using multipart/form-data.', 'voice_upload_form': 'Check the recording, form fields and text lengths, then try the upload again.', 'voice_model_unsupported': 'This checkpoint does not accept uploaded voices. Choose a Base model for voice cloning or a compatible built-in voice.', diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 1cf313cf0..634939068 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -82,7 +82,7 @@ To make music from a reference recording, connect an audio node to a YuE2 music To use **Depth motion capture** on a video, add a video model with the **vLLM-Omni depth** protocol, for example `depth-anything/Video-Depth-Anything-Small` served by `vllm serve --omni`. The tool turns a clip of up to 30 seconds into a grayscale depth video at 480P or 720P, frame for frame, with near objects bright and far ones dark, ready to use as a motion and structure reference. The depth model does not generate video. -**Video blockout** turns a video of up to 30 seconds into a blockout video aligned frame by frame with the source: the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame count, frame rate and duration match the source, and the output is silent. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The blockout is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The blockout is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. +**Video blockout** turns a video of up to 30 seconds into a blockout video aligned frame by frame with the source: the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame rate and duration match the source, and so does the frame count of a constant-frame-rate clip; a variable-frame-rate clip is first resampled at its nominal rate, so the blockout lines up with the source by time. The output is silent and capped at 8 Mbit/s. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The blockout is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The blockout is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. In **General** settings, you can switch themes and adjust the watermark removal option. Watermark settings affect only content generated afterward, and the actual effect depends on support from the model service. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 1b2ab010b..fb710d782 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -69,7 +69,7 @@ HTTP 400。 使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。 -**视频脱模** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的白模视频:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧数、帧率和时长与原片一致,输出没有声音。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。白模视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。白模由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的白模。 +**视频脱模** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的白模视频:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧率和时长与原片一致,恒定帧率的素材帧数也一致;可变帧率的素材会先按其标称帧率重采样,白模按时间与原片对齐。输出没有声音,码率上限为 8 Mbit/s。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。白模视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。白模由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的白模。 在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。 diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index 4b8a896d2..5390634ff 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -245,22 +245,24 @@ async def depth_capture(ctx: ToolContext): BLOCKOUT_CRF = 20 +BLOCKOUT_MAX_MEGABITS = 8 + async def video_blockout(ctx: ToolContext): source = _source_video(ctx) resolution = ctx.choice('resolution', tuple(DEPTH_SHORT_EDGES), '480P') - named = bool(ctx.text('prompt')) - pairs = await ctx.concepts(ctx.text('prompt'), ('人物',)) - label = '、'.join(label for _, label in pairs) with media.Workspace() as work: raw = work.write('source', source.data) info = await blocking(media.video_info, raw) if not 0 < info['duration'] <= DEPTH_MAX_SECONDS + 0.05: - raise ProjectError(f'视频脱模需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422) + raise ProjectError(f'视频脱模需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422, code='tool_blockout_duration') if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES: - raise ProjectError(f'视频脱模单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422) + raise ProjectError(f'视频脱模单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422, code='tool_blockout_frames') + named = await ctx.concepts(ctx.text('prompt'), ()) + pairs = named or await ctx.concepts('', ('人物',)) + label = '、'.join(label for _, label in pairs) await ctx.progress('正在整理视频') width, height = _depth_size(info['width'], info['height'], DEPTH_SHORT_EDGES[resolution]) - clip = await blocking(media.picture, raw, work.path / 'clip.mp4', width=width, height=height) + clip = await blocking(media.conform, raw, work.path / 'clip.mp4', width=width, height=height, fps=info['fps']) await ctx.progress(f'正在识别并跟踪「{label}」') tracks = await ctx.track(clip.read_bytes(), tuple(concept for concept, _ in pairs)) if named and not any(tracks.frames): @@ -270,10 +272,10 @@ async def video_blockout(ctx: ToolContext): await ctx.progress('正在渲染白模') frames = await blocking(media.frames_of, depth, work.path / 'depth-frames', gray=True) if abs(len(frames) - len(tracks.frames)) > 1: - raise ProjectError('跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。', 502) + raise ProjectError('跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。', 502, code='tool_blockout_misaligned') await blocking(write_blockout, frames, tracks, work.path / 'blockout') data = await blocking(media.encode_frames, str(work.path / 'blockout' / '%05d.png'), info['fps'], work.path / 'blockout.mp4', - crf=BLOCKOUT_CRF) + crf=BLOCKOUT_CRF, max_megabits=BLOCKOUT_MAX_MEGABITS) return [Output('video', data, 'mp4', f'视频脱模 {resolution}')] async def video_edit(ctx: ToolContext): diff --git a/packages/core/src/opendirector/media/blockout.py b/packages/core/src/opendirector/media/blockout.py index c0bf14776..f450bd65b 100644 --- a/packages/core/src/opendirector/media/blockout.py +++ b/packages/core/src/opendirector/media/blockout.py @@ -53,7 +53,7 @@ def blockout_frame(depth: Image.Image, subjects) -> Image.Image: return ImageChops.multiply(albedo, Image.merge('RGB', (light, light, light))) -def write_blockout(depth_frames: list[Path], tracks, folder: Path) -> int: +def write_blockout(depth_frames: list[Path], tracks, folder: Path) -> None: if not depth_frames: raise ProjectError('视频中没有可处理的画面。', 422) identities = tracks.identities or tuple(tuple(range(len(frame))) for frame in tracks.frames) @@ -69,4 +69,3 @@ def render(index): with ThreadPoolExecutor(max_workers=WORKERS) as pool: list(pool.map(render, range(len(depth_frames)))) - return len(colors) diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index 85a927f5b..dff933a0a 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -259,10 +259,11 @@ def frames_of(source: Path, folder: Path, *, gray=False) -> list[Path]: return sorted(folder.glob('*.png')) -def encode_frames(pattern: str, fps: float, out: Path, *, crf: int = 12) -> bytes: +def encode_frames(pattern: str, fps: float, out: Path, *, crf: int = 12, max_megabits: int | None = None) -> bytes: """A silent H.264 clip from an image-sequence pattern.""" + ceiling = ['-maxrate', f'{max_megabits}M', '-bufsize', f'{2 * max_megabits}M'] if max_megabits else [] _run(['ffmpeg', '-v', 'error', '-y', '-framerate', f'{fps:.6f}', '-i', pattern, '-vf', 'format=yuv420p', - '-c:v', 'libx264', '-preset', 'veryfast', '-crf', str(crf), '-movflags', '+faststart', str(out)]) + '-c:v', 'libx264', '-preset', 'veryfast', '-crf', str(crf), *ceiling, '-movflags', '+faststart', str(out)]) return out.read_bytes() diff --git a/src/canvas/toolTaskText.ts b/src/canvas/toolTaskText.ts index c3aa57473..0938542fd 100644 --- a/src/canvas/toolTaskText.ts +++ b/src/canvas/toolTaskText.ts @@ -16,6 +16,9 @@ export interface ToolTaskFailure { const CODE: Record = { tool_concept_translation: "errors.tools.error.conceptTranslation", tool_no_video_match: "errors.tools.error.noVideoMatch", + tool_blockout_duration: "errors.tools.error.blockoutDuration", + tool_blockout_frames: "errors.tools.error.blockoutFrames", + tool_blockout_misaligned: "errors.tools.error.blockoutMisaligned", }; const PHASE: Record = { @@ -45,8 +48,6 @@ const PHASE: Record = { const ERROR: Record = { "服务重启,任务已中断,请重新提交。": "errors.tools.error.interrupted", "已取消。": "errors.tools.error.cancelled", - "跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。": - "errors.tools.error.blockoutMisaligned", "工具执行出错,请检查素材和参数后重试。": "errors.tools.error.failed", "生成结果处理失败,请检查服务协议;不会自动重新提交。": "errors.tools.error.resultProcessing", diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index add13b668..5a222f60e 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -337,6 +337,10 @@ export const errors = { "errors.tools.error.interrupted": "The service restarted and the task was interrupted. Submit it again.", "errors.tools.error.cancelled": "Cancelled.", + "errors.tools.error.blockoutDuration": + "Video blockout needs a clip no longer than 30 seconds. Trim the video first.", + "errors.tools.error.blockoutFrames": + "Video blockout processes at most 2048 frames at a time. Trim the video or lower its frame rate first.", "errors.tools.error.blockoutMisaligned": "Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.", "errors.tools.error.failed": diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index 4cba8211f..f1dd9700f 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -259,6 +259,10 @@ export const errors = { "errors.tools.phase.generic": "正在处理素材…", "errors.tools.error.interrupted": "服务重启,任务已中断,请重新提交。", "errors.tools.error.cancelled": "已取消。", + "errors.tools.error.blockoutDuration": + "视频脱模需要不超过 30 秒的素材,请先裁剪视频。", + "errors.tools.error.blockoutFrames": + "视频脱模单次最多处理 2048 帧,请先裁剪视频或降低帧率。", "errors.tools.error.blockoutMisaligned": "跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。", "errors.tools.error.failed": "工具执行出错,请检查素材和参数后重试。", diff --git a/tests/test_blockout.py b/tests/test_blockout.py index 2b3a531cb..0e0209b0d 100644 --- a/tests/test_blockout.py +++ b/tests/test_blockout.py @@ -32,12 +32,12 @@ def is_gray(pixel): def test_colours_follow_identities_in_order_of_first_appearance(): colors = subject_colors(((7,), (7, 3), (3, 11))) assert list(colors) == [7, 3, 11] and [colors[key] for key in (7, 3, 11)] == list(SUBJECTS[:3]) - assert len(subject_colors((tuple(range(len(SUBJECTS) + 1)),))) == len(SUBJECTS) + 1 + assert subject_colors((tuple(range(len(SUBJECTS) + 1)),))[len(SUBJECTS)] == SUBJECTS[0] def test_one_identity_keeps_its_colour_when_its_position_among_instances_changes(tmp_path): tracks = Tracks(WIDTH, HEIGHT, 24.0, ((LEFT, RIGHT), (RIGHT, LEFT)), ((5, 9), (9, 5))) - assert write_blockout(depth_frames(tmp_path / 'depth', 2), tracks, tmp_path / 'out') == 2 + write_blockout(depth_frames(tmp_path / 'depth', 2), tracks, tmp_path / 'out') first, second = (Image.open(tmp_path / 'out' / f'{index:05d}.png').convert('RGB') for index in range(2)) assert tint(first.getpixel((3, 8))) == tint(second.getpixel((3, 8))) == 0 assert tint(first.getpixel((28, 8))) == tint(second.getpixel((28, 8))) == 1 @@ -46,7 +46,7 @@ def test_one_identity_keeps_its_colour_when_its_position_among_instances_changes def test_every_depth_frame_is_rendered_and_untracked_frames_keep_the_scene(tmp_path): tracks = Tracks(WIDTH, HEIGHT, 24.0, ((LEFT,), ())) - assert write_blockout(depth_frames(tmp_path / 'depth', 3), tracks, tmp_path / 'out') == 1 + write_blockout(depth_frames(tmp_path / 'depth', 3), tracks, tmp_path / 'out') frames = [Image.open(path).convert('RGB') for path in sorted((tmp_path / 'out').glob('*.png'))] assert len(frames) == 3 and all(frame.size == (WIDTH, HEIGHT) for frame in frames) assert tint(frames[0].getpixel((3, 8))) == 0 and not is_gray(frames[0].getpixel((3, 8))) diff --git a/tests/test_creation_media_publication.py b/tests/test_creation_media_publication.py index f259388e1..6a925d4af 100644 --- a/tests/test_creation_media_publication.py +++ b/tests/test_creation_media_publication.py @@ -11,6 +11,7 @@ from opendirector.infrastructure.local_projects import LocalProjects from test_creation_canvas_service import project, send, ver from test_creation_tool_drafts import png +from test_tool_tasks import mp4 pytestmark = pytest.mark.cpu @@ -125,3 +126,26 @@ def node(item_id): assert result.status == 'applied', result assert not node(anchor_id).visible and node(anchor_id).revision == 1 assert (node(previous_id).visible, node(output_id).visible) == expected + + +def test_a_blockout_published_from_a_video_item_stays_a_video_with_its_source(project): + store, pid, session = project + assets = CreationToolAssets(store) + + def upload(name): + record = assets.import_file(pid, uuid4(), name, mp4(1), session, provenance=AssetProvenance(source='upload')) + return assets.assets.get(pid, record['id']) + + source = upload('source.mp4') + assert send(store, pid, 'canvas.show', session=session, item=dict(id=uuid4(), projectId=pid, kind='video', + binding=dict(role='material', objectRef=asset_ref(source)))).status == 'applied' + item = store.snapshot(pid).canvasItems[0] + result = assets.import_file(pid, uuid4(), 'blockout.mp4', mp4(1, size='96x54'), session, provenance=AssetProvenance(source='upload')) + output = assets.assets.get(pid, result['id']) + payload = dict(itemId=item.id, source=asset_ref(source), outputs=[dict(itemId=uuid4(), asset=asset_ref(output), title='Blockout')], + document=dict(id=uuid4(), projectId=pid, kind='media_edit', data=dict( + tool='video-blockout', sources=[asset_ref(source)], sourceItems=[item.id], parameters={'resolution': '480P'}))) + receipt = send(store, pid, 'canvas.publishMedia', session=session, versions=[ver('canvas_item', item), ver('asset', output)], **payload) + assert receipt.status == 'applied', receipt + saved = next(asset for asset in store.snapshot(pid).assets if asset.id == output.id) + assert saved.kind == 'video' and saved.provenance.source == 'edited' and saved.provenance.sources == (asset_ref(source),) diff --git a/tests/test_localization.py b/tests/test_localization.py index e96c4c824..2d6ca7f93 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -47,6 +47,16 @@ def test_matting_error_codes_remain_localized_when_backend_copy_changes() -> Non assert localized_error(request('zh-CN'), chinese='更新后的中文', status=422, code=code) == '更新后的中文' +def test_blockout_error_codes_have_english_copy() -> None: + for code, expected in [ + ('tool_blockout_duration', 'no longer than 30 seconds'), + ('tool_blockout_frames', 'at most 2048 frames'), + ('tool_blockout_misaligned', 'different frame counts'), + ]: + assert expected in localized_error(request('en-US'), chinese='更新后的中文', status=422, code=code) + assert localized_error(request('zh-CN'), chinese='更新后的中文', status=422, code=code) == '更新后的中文' + + def test_chinese_and_english_messages_do_not_mix() -> None: assert ( localized_error( diff --git a/tests/test_tool_tasks.py b/tests/test_tool_tasks.py index f84c6ff5f..57affbda2 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -2,6 +2,7 @@ import base64 import io import json +import random import subprocess import time from uuid import uuid4 @@ -11,12 +12,14 @@ from PIL import Image from opendirector.application.tool_tasks import ToolTasks +from opendirector.domain.capabilities import TrackRequest from opendirector.domain.projects import ProjectError from opendirector.application.creation_tool_assets import CreationToolAssets from generation_helpers import new_project from opendirector.infrastructure.local_projects import LocalProjects, child from opendirector.infrastructure.model_configs import ModelConfigs from opendirector.integrations.model_adapters import OpenAIImages, adapter_for, capabilities_of +from opendirector.media import processing pytestmark = pytest.mark.cpu @@ -835,9 +838,10 @@ def handle(request): return handle -def probe(path, entries): - return json.loads(subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', entries, '-of', 'json', str(path)], - capture_output=True, check=True).stdout)['streams'][0] +def probe(path, entries, *options): + value = json.loads(subprocess.run(['ffprobe', '-v', 'error', *options, '-select_streams', 'v:0', '-show_entries', entries, '-of', 'json', str(path)], + capture_output=True, check=True).stdout) + return value['streams'][0] | value.get('format', {}) def test_video_matting_keeps_the_tracked_subject_over_the_chosen_background(project, tmp_path): @@ -980,19 +984,37 @@ def configure_blockout(store): return configs -def blockout_server(prompts, depths, tmp_path, *, empty=False, shade=40): - track, depth = tracking_server(prompts, empty=empty), depth_server(depths, tmp_path, shade=shade) +def uploaded_frames(request, tmp_path, name): + boundary = request.headers['content-type'].split('boundary=', 1)[1].encode() + part = next(item for item in request.read().split(b'--' + boundary) if b'name="video"' in item.split(b'\r\n\r\n', 1)[0]) + path = tmp_path / name + path.write_bytes(part.partition(b'\r\n\r\n')[2][:-2]) + return int(probe(path, 'stream=nb_read_frames', '-count_frames')['nb_read_frames']) + + +def blockout_server(prompts, depths, tmp_path, *, empty=False, extra_tracked_frames=0): + depth = depth_server(depths, tmp_path) + + def track(request): + prompt = request.read().split(b'name="prompt"\r\n\r\n', 1)[1].split(b'\r\n', 1)[0].decode() + count = uploaded_frames(request, tmp_path, f'tracked-{len(prompts)}.mp4') + extra_tracked_frames + prompts.append(prompt) + instance = {'id': 0, 'score': 0.9, 'box': [0, 0, 32, 36], 'mask': {'size': [36, 64], 'counts': [0, 32 * 36, 32 * 36]}} + frames = [{'frame_index': index, 'instances': [] if empty else [instance]} for index in range(count)] + return httpx.Response(200, json={'width': 64, 'height': 36, 'num_frames': count, 'fps': 24.0, 'objects': [], 'frames': frames}) return lambda request: (track if request.url.path == '/v1/videos/segmentations' else depth)(request) def output_frames(store, project_id, task, tmp_path): - path = tmp_path / 'blockout.mp4' + path = tmp_path / f"blockout-{task['id']}.mp4" path.write_bytes(CreationToolAssets(store).read_bytes(project_id, task['outputs'][0]['id'])) - folder = tmp_path / f"frames-{task['id']}" - folder.mkdir() - subprocess.run(['ffmpeg', '-v', 'error', '-i', str(path), '-fps_mode', 'passthrough', str(folder / '%05d.png')], - capture_output=True, check=True) - return [Image.open(item).convert('RGB') for item in sorted(folder.glob('*.png'))], probe(path, 'stream=r_frame_rate,codec_name') + frames = [Image.open(item).convert('RGB') for item in processing.frames_of(path, tmp_path / f"frames-{task['id']}")] + return frames, probe(path, 'stream=r_frame_rate,codec_name:format=duration') + + +def blockout(store, configs, server, project_id, session, source, **parameters): + return run(store, configs, httpx.MockTransport(server), project_id, session, + {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': parameters}) @pytest.mark.parametrize(('instance', 'expected'), [({'id': 4}, ((4,),) * 24), ({}, ()), ({'id': '4'}, ())], @@ -1007,7 +1029,6 @@ def handle(request): frames = [{'frame_index': index, 'instances': [value]} for index in range(24)] return httpx.Response(200, json={'width': 64, 'height': 36, 'num_frames': 24, 'fps': 24.0, 'objects': [], 'frames': frames}) - from opendirector.domain.capabilities import TrackRequest tracks = asyncio.run(adapter_for(config, httpx.MockTransport(handle), 0).track(config, TrackRequest(video=b'clip', concepts=('person',)))) assert tracks.identities == expected and len(tracks.frames) == 24 @@ -1025,15 +1046,14 @@ def test_video_blockout_keeps_every_frame_and_colours_the_tracked_subject(projec store, project_id, session = project source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) prompts, depths = [], [] - task = run(store, configure_blockout(store), httpx.MockTransport(blockout_server(prompts, depths, tmp_path)), project_id, session, - {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': {'resolution': '480P'}}) + task = blockout(store, configure_blockout(store), blockout_server(prompts, depths, tmp_path), project_id, session, source, resolution='480P') assert task['status'] == 'succeeded', task['error'] assert prompts == ['person'] and [(item['width'], item['height'], item['frames']) for item in depths] == [(64, 36, 24)] assert task['modelConfigIds'].keys() == {'video.matting', 'video.motion_capture'} output = task['outputs'][0] assert output['type'] == 'video/mp4' and (output['width'], output['height']) == (64, 36) and output['title'] == '视频脱模 480P' frames, stream = output_frames(store, project_id, task, tmp_path) - assert len(frames) == 24 and stream == {'codec_name': 'h264', 'r_frame_rate': '24/1'} + assert len(frames) == 24 and (stream['codec_name'], stream['r_frame_rate']) == ('h264', '24/1') for frame in (frames[0], frames[-1]): red, green, blue = frame.getpixel((12, 18)) assert red > 120 and green < 70 and blue < 70 @@ -1041,40 +1061,86 @@ def test_video_blockout_keeps_every_frame_and_colours_the_tracked_subject(projec assert abs(red - green) < 12 and abs(green - blue) < 12 and 90 < green < 200 +def test_video_blockout_puts_a_variable_frame_rate_source_on_a_constant_timeline(project, tmp_path): + store, project_id, session = project + path = tmp_path / 'variable.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=64x36:rate=10:duration=2', + '-vf', "select='lt(n,3)+eq(n,9)+eq(n,14)+eq(n,19)'", processing._frame_sync_option(), 'passthrough', + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(path)], check=True, capture_output=True) + shown = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-show_frames', '-of', 'json', str(path)]))['frames'] + assert [float(frame['best_effort_timestamp_time']) for frame in shown] == pytest.approx([0, 0.1, 0.2, 0.9, 1.4, 1.9], abs=0.0001) + source = upload(store, project_id, session, 'variable.mp4', path.read_bytes()) + depths = [] + task = blockout(store, configure_blockout(store), blockout_server([], depths, tmp_path), project_id, session, source) + assert task['status'] == 'succeeded', task['error'] + frames, stream = output_frames(store, project_id, task, tmp_path) + assert len(frames) == depths[0]['frames'] == 20 and stream['r_frame_rate'] == '10/1' + assert float(stream['duration']) == pytest.approx(2.0, abs=0.01) + + def test_video_blockout_without_a_subject_keeps_the_scene_unless_one_was_named(project, tmp_path): store, project_id, session = project source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) configs = configure_blockout(store) prompts, depths = [], [] - server = httpx.MockTransport(blockout_server(prompts, depths, tmp_path, empty=True)) - task = run(store, configs, server, project_id, session, {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': {}}) - assert task['status'] == 'succeeded', task['error'] - frames, _ = output_frames(store, project_id, task, tmp_path) - red, green, blue = frames[0].getpixel((12, 18)) - assert len(frames) == 24 and abs(red - green) < 12 and abs(green - blue) < 12 - task = run(store, configs, server, project_id, session, - {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': {'prompt': '猫咪'}}) + server = blockout_server(prompts, depths, tmp_path, empty=True) + for parameters in ({}, {'prompt': ' ,, '}): + task = blockout(store, configs, server, project_id, session, source, **parameters) + assert task['status'] == 'succeeded', task['error'] + frames, _ = output_frames(store, project_id, task, tmp_path) + red, green, blue = frames[0].getpixel((12, 18)) + assert len(frames) == 24 and abs(red - green) < 12 and abs(green - blue) < 12 + task = blockout(store, configs, server, project_id, session, source, prompt='猫咪') assert task['status'] == 'failed' and task['errorDetails'] == {'code': 'tool_no_video_match', 'params': {'label': '猫咪'}} - assert prompts == ['person', 'cat'] and len(depths) == 1 + assert prompts == ['person', 'person', 'cat'] and len(depths) == 2 -def test_video_blockout_rejects_unusable_input_before_calling_a_model_and_misaligned_results_after(project, tmp_path): +@pytest.mark.parametrize(('clip', 'parameters', 'code', 'text'), [ + ((31, '24'), {}, 'tool_blockout_duration', '不超过 30 秒'), + ((25, '90'), {}, 'tool_blockout_frames', '最多处理 2048 帧'), + ((1, '24'), {'resolution': '1080P'}, 'invalid_input', '不在可选范围内'), + ((31, '24'), {'prompt': '三花猫'}, 'tool_blockout_duration', '不超过 30 秒'), +], ids=['too-long', 'too-many-frames', 'unknown-resolution', 'too-long-with-a-subject-to-translate']) +def test_video_blockout_rejects_unusable_input_before_calling_any_model(project, tmp_path, clip, parameters, code, text): store, project_id, session = project + seconds, rate = clip + data = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', f'color=c=gray:size=64x36:rate={rate}', '-t', str(seconds), + '-pix_fmt', 'yuv420p', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', 'pipe:1'], + capture_output=True, check=True).stdout + source = upload(store, project_id, session, 'clip.mp4', data) + requests = [] + + def server(request): + requests.append(request.url.path) + return httpx.Response(500) + configs = configure_blockout(store) - prompts, depths = [], [] - server = httpx.MockTransport(blockout_server(prompts, depths, tmp_path)) - long = upload(store, project_id, session, 'long.mp4', mp4(31)) - task = run(store, configs, server, project_id, session, {'tool': 'video-blockout', 'sourceAssetIds': [long], 'parameters': {}}) - assert task['status'] == 'failed' and '不超过 30 秒' in task['error'] - short = upload(store, project_id, session, 'short.mp4', mp4(1)) - task = run(store, configs, server, project_id, session, - {'tool': 'video-blockout', 'sourceAssetIds': [short], 'parameters': {'resolution': '1080P'}}) - assert task['status'] == 'failed' and '不在可选范围内' in task['error'] - assert prompts == [] and depths == [] - double = upload(store, project_id, session, 'double.mp4', mp4(2)) - task = run(store, configs, server, project_id, session, {'tool': 'video-blockout', 'sourceAssetIds': [double], 'parameters': {}}) - assert task['status'] == 'failed' and '帧数不一致' in task['error'] and task['outputs'] == [] - assert depths[-1]['frames'] == 48 + configs.save(*CHAT, '', connection_type='self_hosted', protocol='openai') + task = blockout(store, configs, server, project_id, session, source, **parameters) + assert task['status'] == 'failed' and text in task['error'] and task['errorDetails']['code'] == code + assert requests == [] and task['outputs'] == [] + + +@pytest.mark.parametrize(('extra', 'status'), [(1, 'succeeded'), (-1, 'succeeded'), (2, 'failed')]) +def test_video_blockout_tolerates_one_frame_of_difference_and_refuses_more(project, tmp_path, extra, status): + store, project_id, session = project + source = upload(store, project_id, session, 'clip.mp4', mp4(1)) + depths = [] + task = blockout(store, configure_blockout(store), blockout_server([], depths, tmp_path, extra_tracked_frames=extra), project_id, session, source) + assert task['status'] == status, task['error'] + if status == 'failed': + assert task['errorDetails']['code'] == 'tool_blockout_misaligned' and task['outputs'] == [] + else: + assert len(output_frames(store, project_id, task, tmp_path)[0]) == depths[0]['frames'] == 24 + + +def test_a_bitrate_ceiling_bounds_the_size_of_an_encoded_frame_sequence(tmp_path): + for index in range(48): + Image.frombytes('RGB', (320, 180), random.randbytes(320 * 180 * 3)).save(tmp_path / f'{index:05d}.png', compress_level=1) + pattern = str(tmp_path / '%05d.png') + free = processing.encode_frames(pattern, 24, tmp_path / 'free.mp4', crf=20) + capped = processing.encode_frames(pattern, 24, tmp_path / 'capped.mp4', crf=20, max_megabits=1) + assert len(capped) < len(free) / 2 and len(capped) < 2 * 1_000_000 / 8 * 2 def test_cancel_drains_an_inflight_write_so_the_task_never_stays_running(project): diff --git a/tests/toolTaskText.test.ts b/tests/toolTaskText.test.ts index cf7e89874..e4cc41c99 100644 --- a/tests/toolTaskText.test.ts +++ b/tests/toolTaskText.test.ts @@ -38,10 +38,16 @@ test("tool task errors never leak persisted Chinese", () => { toolTaskError("工具执行出错,请检查素材和参数后重试。"), "The tool failed. Check the media and parameters and try again.", ); - assert.match( - toolTaskError("跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。")!, - /different frame counts/, - ); + for (const [code, english, chinese] of [ + ["tool_blockout_duration", /no longer than 30 seconds/, /不超过 30 秒/], + ["tool_blockout_frames", /at most 2048 frames/, /最多处理 2048 帧/], + ["tool_blockout_misaligned", /different frame counts/, /帧数不一致/], + ] as const) { + assert.match(toolTaskError("后端文案已更新", undefined, { code })!, english); + setActiveLocale("zh-CN"); + assert.match(toolTaskError("后端文案已更新", undefined, { code })!, chinese); + setActiveLocale("en-US"); + } assert.equal( toolTaskError("unexpected provider exception"), "unexpected provider exception", From c0a4f3632f5a63416cd7c7155879c760ad3febe4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 16:35:40 +0000 Subject: [PATCH 3/5] [bugfix] canvas: keep video blockout frame-aligned on FFmpeg 4 ## summary Release checks on af491b33 failed two blockout tests on the runner's FFmpeg 4.4.2: a 24-frame clip came back as 26 frames. The test clip is a fragmented MP4 with sound whose video stream starts at 0.083 s. The clip sent to tracking and depth was made with the shared `conform` helper, and FFmpeg 4 fills such a start gap with duplicated frames at the muxer, which FFmpeg 7 does not. The blockout then had two frames more than its source. - The recipe now builds that clip with `media.constant_rate_picture`: the same scale and `fps` filter, no sound, and frame passthrough at the muxer, so the filter alone decides the frames. A constant-rate source keeps its frame count and a variable-rate one is still resampled onto a constant timeline. - Reproduced and verified with real FFmpeg 4.4.2, 7.1.1 and 9.1 builds; the wrapper used before only hid the `-fps_mode` option and could not show this difference. Refs #444 Co-Authored-By: Claude Fable 5.2 --- .../src/opendirector/application/tool_video_recipes.py | 2 +- packages/core/src/opendirector/media/processing.py | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index 5390634ff..4a140f1ee 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -262,7 +262,7 @@ async def video_blockout(ctx: ToolContext): label = '、'.join(label for _, label in pairs) await ctx.progress('正在整理视频') width, height = _depth_size(info['width'], info['height'], DEPTH_SHORT_EDGES[resolution]) - clip = await blocking(media.conform, raw, work.path / 'clip.mp4', width=width, height=height, fps=info['fps']) + clip = await blocking(media.constant_rate_picture, raw, work.path / 'clip.mp4', width=width, height=height, fps=info['fps']) await ctx.progress(f'正在识别并跟踪「{label}」') tracks = await ctx.track(clip.read_bytes(), tuple(concept for concept, _ in pairs)) if named and not any(tracks.frames): diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index dff933a0a..0befee954 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -251,6 +251,13 @@ def picture(source: Path, out: Path, *, width: int, height: int) -> Path: return out +def constant_rate_picture(source: Path, out: Path, *, width: int, height: int, fps: float) -> Path: + _run(['ffmpeg', '-v', 'error', '-y', '-i', str(source), + '-vf', f'scale={width}:{height},setsar=1,fps={fps:.6f},format=yuv420p', '-an', + _frame_sync_option(), 'passthrough', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', str(out)]) + return out + + def frames_of(source: Path, folder: Path, *, gray=False) -> list[Path]: """Every decoded frame of source as a PNG, in order (grayscale when gray).""" folder.mkdir() From 186b7c78e402d190fc6b2640e9d77784a2871910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Wed, 2 Dec 2026 04:23:07 +0000 Subject: [PATCH 4/5] [refactor] canvas: rename the 2.5D video blockout tool to structure reference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The name "视频脱模" (Video blockout, RFC #444) is kept for a separate 3D tool: a grey-box scene and mannequin rendered from the recovered camera and 3D bodies. This tool renders a depth relief with colored tracked subjects, a 2.5D reference for regenerating a clip with the same motion, timing and camera, so it no longer uses the blockout name. - Tool id `video-blockout` becomes `video-structure-reference`, titled 结构参考 / Structure reference, in the canvas catalog, the backend tool registry, the media-edit contract (regenerated) and publication. - Recipe `video_blockout` becomes `structure_reference`; the renderer module `media/blockout.py` becomes `media/structure_reference.py` with `write_structure_reference` and `structure_frame`; the encoder constants become `STRUCTURE_REFERENCE_CRF` and `STRUCTURE_REFERENCE_MAX_MEGABITS`. - Error codes `tool_blockout_duration`, `tool_blockout_frames` and `tool_blockout_misaligned` become `tool_structure_reference_*`; the i18n keys, the progress phase, the output title, the panel hint and both user guides follow, with matching zh-CN and en-US copy. - Tests are renamed accordingly (`tests/test_blockout.py` becomes `tests/test_structure_reference.py`). Behaviour is unchanged. Refs #444 Co-Authored-By: Claude Opus 5.5 Signed-off-by: 汪志鹏 --- apps/api/src/opendirector_api/localization.py | 6 +- docs/guides/user-guide.md | 2 +- docs/guides/user-guide.zh-CN.md | 2 +- .../application/creation_media_publication.py | 2 +- .../application/tool_operations.py | 8 +-- .../application/tool_video_recipes.py | 24 +++---- .../opendirector/domain/creation/editors.py | 2 +- .../{blockout.py => structure_reference.py} | 6 +- src/canvas/NodeSelectionToolbar.tsx | 6 +- src/canvas/VideoActionEditor.tsx | 27 +++++--- src/canvas/toolCatalog.ts | 8 +-- src/canvas/toolTaskText.ts | 11 ++-- src/canvas/toolText.ts | 6 +- src/canvas/videoActionRuntime.ts | 11 ++-- src/contracts/creation.schema.json | 4 +- src/contracts/generated.ts | 4 +- src/i18n/messages/en-US/canvasShell.ts | 2 +- src/i18n/messages/en-US/errors.ts | 16 ++--- src/i18n/messages/en-US/tools.ts | 10 +-- src/i18n/messages/zh-CN/canvasShell.ts | 2 +- src/i18n/messages/zh-CN/errors.ts | 15 ++--- src/i18n/messages/zh-CN/tools.ts | 10 +-- tests/test_creation_media_publication.py | 8 +-- tests/test_localization.py | 8 +-- ...lockout.py => test_structure_reference.py} | 12 ++-- tests/test_tool_tasks.py | 62 ++++++++++--------- tests/toolCatalog.test.ts | 4 +- tests/toolTaskText.test.ts | 23 +++++-- tests/videoActionRuntime.test.ts | 18 ++++-- 29 files changed, 183 insertions(+), 136 deletions(-) rename packages/core/src/opendirector/media/{blockout.py => structure_reference.py} (91%) rename tests/{test_blockout.py => test_structure_reference.py} (84%) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index ef9350a41..97c71f375 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -75,9 +75,9 @@ 'capability_connection_changed': 'The model connection changed during the capability check. Submit again.', 'tool_concept_translation': 'Use a short English subject description, or add a chat model in Models to translate it automatically.', 'tool_no_video_match': 'The requested subject was not found in the video. Try a different description.', - 'tool_blockout_duration': 'Video blockout needs a clip no longer than 30 seconds. Trim the video first.', - 'tool_blockout_frames': 'Video blockout processes at most 2048 frames at a time. Trim the video or lower its frame rate first.', - 'tool_blockout_misaligned': 'Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.', + 'tool_structure_reference_duration': 'Structure reference needs a clip no longer than 30 seconds. Trim the video first.', + 'tool_structure_reference_frames': 'Structure reference processes at most 2048 frames at a time. Trim the video or lower its frame rate first.', + 'tool_structure_reference_misaligned': 'Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.', 'voice_upload_type': 'Upload the voice recording using multipart/form-data.', 'voice_upload_form': 'Check the recording, form fields and text lengths, then try the upload again.', 'voice_model_unsupported': 'This checkpoint does not accept uploaded voices. Choose a Base model for voice cloning or a compatible built-in voice.', diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 1674680d6..e201ca60a 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -84,7 +84,7 @@ To make music from a reference recording, connect an audio node to a YuE2 music To use **Depth motion capture** on a video, add a video model with the **vLLM-Omni depth** protocol, for example `depth-anything/Video-Depth-Anything-Small` served by `vllm serve --omni`. The tool turns a clip of up to 30 seconds into a grayscale depth video at 480P or 720P, frame for frame, with near objects bright and far ones dark, ready to use as a motion and structure reference. The depth model does not generate video. -**Video blockout** turns a video of up to 30 seconds into a blockout video aligned frame by frame with the source: the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame rate and duration match the source, and so does the frame count of a constant-frame-rate clip; a variable-frame-rate clip is first resampled at its nominal rate, so the blockout lines up with the source by time. The output is silent and capped at 8 Mbit/s. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The blockout is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The blockout is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. +**Structure reference** turns a video of up to 30 seconds into a reference for regenerating it with the same motion, timing and camera: a video aligned frame by frame with the source, in which the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame rate and duration match the source, and so does the frame count of a constant-frame-rate clip; a variable-frame-rate clip is first resampled at its nominal rate, so the structure reference lines up with the source by time. The output is silent and capped at 8 Mbit/s. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The structure reference is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The structure reference is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. In **General** settings, you can switch themes and adjust the watermark removal option. Watermark settings affect only content generated afterward, and the actual effect depends on support from the model service. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 08d0ac168..55997c84a 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -71,7 +71,7 @@ HTTP 400。 使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。 -**视频脱模** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的白模视频:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧率和时长与原片一致,恒定帧率的素材帧数也一致;可变帧率的素材会先按其标称帧率重采样,白模按时间与原片对齐。输出没有声音,码率上限为 8 Mbit/s。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。白模视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。白模由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的白模。 +**结构参考** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的结构参考视频,用于以相同的动作、节奏和机位重新生成:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧率和时长与原片一致,恒定帧率的素材帧数也一致;可变帧率的素材会先按其标称帧率重采样,结构参考按时间与原片对齐。输出没有声音,码率上限为 8 Mbit/s。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。结构参考视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。结构参考由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的结构参考。 在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。 diff --git a/packages/core/src/opendirector/application/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index 15f0499d1..ab84c3ccb 100644 --- a/packages/core/src/opendirector/application/creation_media_publication.py +++ b/packages/core/src/opendirector/application/creation_media_publication.py @@ -37,7 +37,7 @@ def publish_media(service, data, payload): expected, allowed = 'video', {'audio'} if not actual.metadata.hasAudio: raise ContractError('invalid_input', '来源视频没有可提取的音轨。', actual.id) - elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite', 'video-blockout'}: + elif tool in {'video-depth-capture', 'video-extend', 'video-partial-reshoot', 'video-trim', 'video-crop', 'video-edit', 'video-upscale', 'video-frame-interpolation', 'video-subtitle-erasure', 'video-matting', 'video-translation', 'video-mask-composite', 'video-structure-reference'}: expected, allowed = 'video', {'video'} elif tool in {'audio-trim', 'audio-separation'}: expected, allowed = ('video' if tool == 'audio-separation' and actual.kind == 'video' else 'audio'), {'audio'} diff --git a/packages/core/src/opendirector/application/tool_operations.py b/packages/core/src/opendirector/application/tool_operations.py index a2b0fb16d..7513f786d 100644 --- a/packages/core/src/opendirector/application/tool_operations.py +++ b/packages/core/src/opendirector/application/tool_operations.py @@ -16,7 +16,7 @@ from opendirector.domain.image_presets import PRESETS, preset_instructions from opendirector.application.tool_video_recipes import ( AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot, - subtitle_erasure, video_blockout, video_edit, video_matting, video_upscale, + structure_reference, subtitle_erasure, video_edit, video_matting, video_upscale, ) # Editor previews and tool tasks import this helper from the catalog module. @@ -108,7 +108,7 @@ def _preset_select(): note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'), ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture, note='逐帧估计景深,输出灰度深度视频(近处亮、远处暗),可作为视频生成的动作与结构参考;最长 30 秒。'), - ToolSpec('video-blockout', ('video',), _needs('video.matting', 'video.motion_capture'), video_blockout, - note='去除外观,只保留原片的动作、时序、机位和场景结构:场景渲染为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色;' - '输出与原片逐帧对齐的无声白模视频,最长 30 秒。'), + ToolSpec('video-structure-reference', ('video',), _needs('video.matting', 'video.motion_capture'), structure_reference, + note='去除外观,只保留原片的动作、时序、机位和场景结构,作为以相同动作、节奏和机位重新生成视频的参考:' + '场景渲染为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色;输出与原片逐帧对齐的无声结构参考视频,最长 30 秒。'), ]} diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index 4a140f1ee..a9f997165 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -8,7 +8,7 @@ from opendirector.domain.projects import ProjectError from opendirector.media import processing as media from opendirector.media.async_work import blocking -from opendirector.media.blockout import write_blockout +from opendirector.media.structure_reference import write_structure_reference def _source_video(ctx: ToolContext) -> Source: @@ -243,20 +243,20 @@ async def depth_capture(ctx: ToolContext): data = await ctx.depth(clip.read_bytes()) return [Output('video', data, 'mp4', f'深度动作捕捉 {resolution}')] -BLOCKOUT_CRF = 20 +STRUCTURE_REFERENCE_CRF = 20 -BLOCKOUT_MAX_MEGABITS = 8 +STRUCTURE_REFERENCE_MAX_MEGABITS = 8 -async def video_blockout(ctx: ToolContext): +async def structure_reference(ctx: ToolContext): source = _source_video(ctx) resolution = ctx.choice('resolution', tuple(DEPTH_SHORT_EDGES), '480P') with media.Workspace() as work: raw = work.write('source', source.data) info = await blocking(media.video_info, raw) if not 0 < info['duration'] <= DEPTH_MAX_SECONDS + 0.05: - raise ProjectError(f'视频脱模需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422, code='tool_blockout_duration') + raise ProjectError(f'结构参考需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422, code='tool_structure_reference_duration') if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES: - raise ProjectError(f'视频脱模单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422, code='tool_blockout_frames') + raise ProjectError(f'结构参考单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422, code='tool_structure_reference_frames') named = await ctx.concepts(ctx.text('prompt'), ()) pairs = named or await ctx.concepts('', ('人物',)) label = '、'.join(label for _, label in pairs) @@ -269,14 +269,14 @@ async def video_blockout(ctx: ToolContext): raise ToolInputError(f'视频中没有识别到「{label}」,请换一种描述后重试。', code='tool_no_video_match', label=label) await ctx.progress('正在估计每一帧的深度') depth = work.write('depth.mp4', await ctx.depth(clip.read_bytes())) - await ctx.progress('正在渲染白模') + await ctx.progress('正在渲染结构参考') frames = await blocking(media.frames_of, depth, work.path / 'depth-frames', gray=True) if abs(len(frames) - len(tracks.frames)) > 1: - raise ProjectError('跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。', 502, code='tool_blockout_misaligned') - await blocking(write_blockout, frames, tracks, work.path / 'blockout') - data = await blocking(media.encode_frames, str(work.path / 'blockout' / '%05d.png'), info['fps'], work.path / 'blockout.mp4', - crf=BLOCKOUT_CRF, max_megabits=BLOCKOUT_MAX_MEGABITS) - return [Output('video', data, 'mp4', f'视频脱模 {resolution}')] + raise ProjectError('跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。', 502, code='tool_structure_reference_misaligned') + await blocking(write_structure_reference, frames, tracks, work.path / 'reference') + data = await blocking(media.encode_frames, str(work.path / 'reference' / '%05d.png'), info['fps'], work.path / 'reference.mp4', + crf=STRUCTURE_REFERENCE_CRF, max_megabits=STRUCTURE_REFERENCE_MAX_MEGABITS) + return [Output('video', data, 'mp4', f'结构参考 {resolution}')] async def video_edit(ctx: ToolContext): source = _source_video(ctx) diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index fe1ea37a0..4876bea0e 100644 --- a/packages/core/src/opendirector/domain/creation/editors.py +++ b/packages/core/src/opendirector/domain/creation/editors.py @@ -488,7 +488,7 @@ class SelectionBox(Contract): 'dynamic-poster', 'ecommerce-main', 'image-presets', 'grid-split', 'composition', 'annotation', 'video-edit', 'video-extend', 'video-partial-reshoot', 'video-upscale', 'video-frame-interpolation', 'video-depth-capture', 'video-subtitle-erasure', 'video-matting', 'video-crop', 'video-translation', - 'video-mask-composite', 'video-blockout', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] + 'video-mask-composite', 'video-structure-reference', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] class ToolDraftBinding(Contract): diff --git a/packages/core/src/opendirector/media/blockout.py b/packages/core/src/opendirector/media/structure_reference.py similarity index 91% rename from packages/core/src/opendirector/media/blockout.py rename to packages/core/src/opendirector/media/structure_reference.py index f450bd65b..105f17ef0 100644 --- a/packages/core/src/opendirector/media/blockout.py +++ b/packages/core/src/opendirector/media/structure_reference.py @@ -40,7 +40,7 @@ def _contours(depth: Image.Image) -> Image.Image: return step.point(lambda value: min(96, max(0, (value - 12) * 3))).resize(depth.size, Image.Resampling.BILINEAR) -def blockout_frame(depth: Image.Image, subjects) -> Image.Image: +def structure_frame(depth: Image.Image, subjects) -> Image.Image: fog, slope = _relief(depth) light = ImageChops.subtract(ImageChops.add(fog, slope, 1, -128), _contours(depth)) albedo = Image.new('RGB', depth.size, SCENE) @@ -53,7 +53,7 @@ def blockout_frame(depth: Image.Image, subjects) -> Image.Image: return ImageChops.multiply(albedo, Image.merge('RGB', (light, light, light))) -def write_blockout(depth_frames: list[Path], tracks, folder: Path) -> None: +def write_structure_reference(depth_frames: list[Path], tracks, folder: Path) -> None: if not depth_frames: raise ProjectError('视频中没有可处理的画面。', 422) identities = tracks.identities or tuple(tuple(range(len(frame))) for frame in tracks.frames) @@ -65,7 +65,7 @@ def render(index): if index < len(tracks.frames): subjects = [(colors[identity], rle_mask(counts, tracks.width, tracks.height)) for identity, counts in zip(identities[index], tracks.frames[index])] - blockout_frame(Image.open(depth_frames[index]).convert('L'), subjects).save(folder / f'{index:05d}.png', compress_level=1) + structure_frame(Image.open(depth_frames[index]).convert('L'), subjects).save(folder / f'{index:05d}.png', compress_level=1) with ThreadPoolExecutor(max_workers=WORKERS) as pool: list(pool.map(render, range(len(depth_frames)))) diff --git a/src/canvas/NodeSelectionToolbar.tsx b/src/canvas/NodeSelectionToolbar.tsx index da4c8001f..d36341190 100644 --- a/src/canvas/NodeSelectionToolbar.tsx +++ b/src/canvas/NodeSelectionToolbar.tsx @@ -452,7 +452,11 @@ export function NodeSelectionToolbar({ t("canvas.selection.depthCapture"), "subject", ); - addTool("video-blockout", t("canvas.selection.videoBlockout"), "subject"); + addTool( + "video-structure-reference", + t("canvas.selection.structureReference"), + "subject", + ); addEditor("video-trim", t("canvas.selection.trimVideo"), "trim", "trim"); addMenu( "sound-separation", diff --git a/src/canvas/VideoActionEditor.tsx b/src/canvas/VideoActionEditor.tsx index 683b8473d..a2dbc3106 100644 --- a/src/canvas/VideoActionEditor.tsx +++ b/src/canvas/VideoActionEditor.tsx @@ -791,11 +791,12 @@ function VideoActionSession({ label: "tools.videoEditor.prompt.mattingLabel", placeholder: "tools.videoEditor.prompt.mattingPlaceholder", } - : tool === "video-blockout" + : tool === "video-structure-reference" ? { key: "prompt", - label: "tools.videoEditor.prompt.blockoutLabel", - placeholder: "tools.videoEditor.prompt.blockoutPlaceholder", + label: "tools.videoEditor.prompt.structureReferenceLabel", + placeholder: + "tools.videoEditor.prompt.structureReferencePlaceholder", } : tool === "audio-separation" && parameters.mode === "description" ? { @@ -1251,13 +1252,19 @@ function VideoActionSession({ ["480P", "480P"], ["720P", "720P"], ])} - {tool === "video-blockout" && - choices(t("tools.videoEditor.blockout.resolution"), "resolution", [ - ["480P", "480P"], - ["720P", "720P"], - ])} - {tool === "video-blockout" && ( -

{t("tools.videoEditor.blockout.hint")}

+ {tool === "video-structure-reference" && + choices( + t("tools.videoEditor.structureReference.resolution"), + "resolution", + [ + ["480P", "480P"], + ["720P", "720P"], + ], + )} + {tool === "video-structure-reference" && ( +

+ {t("tools.videoEditor.structureReference.hint")} +

)} {tool === "video-frame-interpolation" && choices(t("tools.videoEditor.interpolation.fps"), "fps", [ diff --git a/src/canvas/toolCatalog.ts b/src/canvas/toolCatalog.ts index 198704917..a1e3ac4de 100644 --- a/src/canvas/toolCatalog.ts +++ b/src/canvas/toolCatalog.ts @@ -35,7 +35,7 @@ export type CanvasToolId = | "video-crop" | "video-translation" | "video-mask-composite" - | "video-blockout" + | "video-structure-reference" | "extract-audio" | "audio-separation" | "video-trim" @@ -450,9 +450,9 @@ export const CANVAS_TOOLS: readonly CanvasToolDefinition[] = [ { category: "video", sources: ["video"], parameterCoverage: "entry-only" }, ), tool( - "video-blockout", - "视频脱模", - "去除外观,只保留原片的动作、时序、机位和场景结构:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 480P / 720P、与原片逐帧对齐的白模视频,素材最长 30 秒;需要接入视频跟踪和深度模型。", + "video-structure-reference", + "结构参考", + "去除外观,只保留原片的动作、时序、机位和场景结构,作为以相同动作、节奏和机位重新生成视频的参考:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 480P / 720P、与原片逐帧对齐的结构参考视频,素材最长 30 秒;需要接入视频跟踪和深度模型。", [choice("resolution", "清晰度", ["480P", "720P"])], { category: "video", sources: ["video"], parameterCoverage: "entry-only" }, ), diff --git a/src/canvas/toolTaskText.ts b/src/canvas/toolTaskText.ts index 0938542fd..d9e20526d 100644 --- a/src/canvas/toolTaskText.ts +++ b/src/canvas/toolTaskText.ts @@ -16,9 +16,12 @@ export interface ToolTaskFailure { const CODE: Record = { tool_concept_translation: "errors.tools.error.conceptTranslation", tool_no_video_match: "errors.tools.error.noVideoMatch", - tool_blockout_duration: "errors.tools.error.blockoutDuration", - tool_blockout_frames: "errors.tools.error.blockoutFrames", - tool_blockout_misaligned: "errors.tools.error.blockoutMisaligned", + tool_structure_reference_duration: + "errors.tools.error.structureReferenceDuration", + tool_structure_reference_frames: + "errors.tools.error.structureReferenceFrames", + tool_structure_reference_misaligned: + "errors.tools.error.structureReferenceMisaligned", }; const PHASE: Record = { @@ -39,7 +42,7 @@ const PHASE: Record = { 正在整理视频: "errors.tools.phase.organizeVideo", 正在合成抠像视频: "errors.tools.phase.matteVideo", 正在估计每一帧的深度: "errors.tools.phase.depth", - 正在渲染白模: "errors.tools.phase.blockout", + 正在渲染结构参考: "errors.tools.phase.structureReference", 正在分离音轨: "errors.tools.phase.separateAudio", 正在放大视频: "errors.tools.phase.upscaleVideo", 正在保存结果: "errors.tools.phase.save", diff --git a/src/canvas/toolText.ts b/src/canvas/toolText.ts index 7228db0d2..75156e67e 100644 --- a/src/canvas/toolText.ts +++ b/src/canvas/toolText.ts @@ -152,9 +152,9 @@ const EN: Record = { "选择黑色、绿色或透明背景,或输出黑底白色的对象遮罩;输出格式由服务提供。": "Choose a black, green, or transparent background, or output a white-on-black object mask; output formats depend on the service.", "遮罩": "Mask", - "视频脱模": "Video Blockout", - "去除外观,只保留原片的动作、时序、机位和场景结构:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 480P / 720P、与原片逐帧对齐的白模视频,素材最长 30 秒;需要接入视频跟踪和深度模型。": - "Strips appearance and keeps the source's motion, timing, camera and scene structure: the scene becomes gray relief and each tracked subject one solid color. Outputs a 480P / 720P blockout video aligned frame by frame with the source, up to 30 seconds; requires a video tracking model and a depth model.", + "结构参考": "Structure Reference", + "去除外观,只保留原片的动作、时序、机位和场景结构,作为以相同动作、节奏和机位重新生成视频的参考:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 480P / 720P、与原片逐帧对齐的结构参考视频,素材最长 30 秒;需要接入视频跟踪和深度模型。": + "Strips appearance and keeps the source's motion, timing, camera and scene structure, as a reference for regenerating the clip with the same motion, pacing and camera: the scene becomes gray relief and each tracked subject one solid color. Outputs a 480P / 720P structure reference video aligned frame by frame with the source, up to 30 seconds; requires a video tracking model and a depth model.", "遮罩合成": "Mask Composite", "保留内容视频在遮罩视频白色区域内的画面,其余变黑;可拉伸遮罩内的明暗范围。本地处理,不调用模型。": "Keeps the content video inside the white area of the mask video and blacks out the rest; can stretch brightness inside the mask. Local processing, no model.", diff --git a/src/canvas/videoActionRuntime.ts b/src/canvas/videoActionRuntime.ts index 65c69cdcd..217146b3b 100644 --- a/src/canvas/videoActionRuntime.ts +++ b/src/canvas/videoActionRuntime.ts @@ -112,7 +112,7 @@ export function initialVideoActionParameters( return { resolution: "4K" }; case "video-depth-capture": return { resolution: "480P" }; - case "video-blockout": + case "video-structure-reference": return { resolution: "480P", prompt: "" }; case "video-frame-interpolation": return { fps: 30 }; @@ -144,7 +144,10 @@ export function videoActionInputError( > = { "video-upscale": { key: "resolution", values: ["2K", "4K"] }, "video-depth-capture": { key: "resolution", values: ["480P", "720P"] }, - "video-blockout": { key: "resolution", values: ["480P", "720P"] }, + "video-structure-reference": { + key: "resolution", + values: ["480P", "720P"], + }, "video-frame-interpolation": { key: "fps", values: [30, 60] }, "video-matting": { key: "background", @@ -191,10 +194,10 @@ export function videoActionInputError( ) return tNow("errors.videoAction.depthDuration"); if ( - tool === "video-blockout" && + tool === "video-structure-reference" && (!Number.isFinite(duration) || duration <= 0 || duration > 30) ) - return tNow("errors.videoAction.blockoutDuration"); + return tNow("errors.videoAction.structureReferenceDuration"); if ( tool === "audio-separation" && parameters.mode === "description" && diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 2bdba0eaa..a3333ee75 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -9484,7 +9484,7 @@ "video-crop", "video-translation", "video-mask-composite", - "video-blockout", + "video-structure-reference", "extract-audio", "audio-separation", "video-trim", @@ -28156,7 +28156,7 @@ "video-crop", "video-translation", "video-mask-composite", - "video-blockout", + "video-structure-reference", "extract-audio", "audio-separation", "video-trim", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 9ffc07b40..89b6aeaf4 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -939,7 +939,7 @@ export interface MediaCanvasItemInput extends CanvasItemBaseInput { } export interface MediaEditDataInput extends ContractInput { - readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "video-blockout" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; + readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "video-structure-reference" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; readonly sources?: ReadonlyArray; readonly sourceItems?: ReadonlyArray; readonly parameters?: Readonly>; @@ -2835,7 +2835,7 @@ export interface MediaCanvasItem extends CanvasItemBase { } export interface MediaEditData extends Contract { - readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "video-blockout" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; + readonly tool: "layers" | "crop" | "smart-edit" | "outpaint" | "cutout" | "inpainting-remove" | "image-hd" | "view-control" | "lighting" | "layer-decompose" | "panorama" | "product-replacement" | "multi-size" | "dynamic-poster" | "ecommerce-main" | "image-presets" | "grid-split" | "composition" | "annotation" | "video-edit" | "video-extend" | "video-partial-reshoot" | "video-upscale" | "video-frame-interpolation" | "video-depth-capture" | "video-subtitle-erasure" | "video-matting" | "video-crop" | "video-translation" | "video-mask-composite" | "video-structure-reference" | "extract-audio" | "audio-separation" | "video-trim" | "audio-trim" | "video-frame-capture" | "director-stage"; readonly sources: ReadonlyArray; readonly sourceItems: ReadonlyArray; readonly parameters: Readonly>; diff --git a/src/i18n/messages/en-US/canvasShell.ts b/src/i18n/messages/en-US/canvasShell.ts index 739d11fb5..54745aeec 100644 --- a/src/i18n/messages/en-US/canvasShell.ts +++ b/src/i18n/messages/en-US/canvasShell.ts @@ -127,7 +127,7 @@ export const canvasShell = { "canvas.selection.lastFrame": "Last frame", "canvas.selection.customFrame": "Capture custom frame", "canvas.selection.depthCapture": "Depth motion capture", - "canvas.selection.videoBlockout": "Video blockout", + "canvas.selection.structureReference": "Structure reference", "canvas.selection.trimVideo": "Trim duration", "canvas.selection.audioSeparation": "Separate audio", "canvas.selection.extractAudio": "Extract audio", diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index 5a222f60e..0454398d6 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -328,7 +328,7 @@ export const errors = { "errors.tools.phase.track": 'Detecting and tracking "{labels}"', "errors.tools.phase.matteVideo": "Compositing the matte video", "errors.tools.phase.depth": "Estimating depth for every frame", - "errors.tools.phase.blockout": "Rendering the blockout", + "errors.tools.phase.structureReference": "Rendering the structure reference", "errors.tools.phase.separateAudio": "Separating the audio track", "errors.tools.phase.upscaleVideo": "Upscaling the video", "errors.tools.phase.interpolate": "Interpolating to {fps} fps", @@ -337,11 +337,11 @@ export const errors = { "errors.tools.error.interrupted": "The service restarted and the task was interrupted. Submit it again.", "errors.tools.error.cancelled": "Cancelled.", - "errors.tools.error.blockoutDuration": - "Video blockout needs a clip no longer than 30 seconds. Trim the video first.", - "errors.tools.error.blockoutFrames": - "Video blockout processes at most 2048 frames at a time. Trim the video or lower its frame rate first.", - "errors.tools.error.blockoutMisaligned": + "errors.tools.error.structureReferenceDuration": + "Structure reference needs a clip no longer than 30 seconds. Trim the video first.", + "errors.tools.error.structureReferenceFrames": + "Structure reference processes at most 2048 frames at a time. Trim the video or lower its frame rate first.", + "errors.tools.error.structureReferenceMisaligned": "Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.", "errors.tools.error.failed": "The tool failed. Check the media and parameters and try again.", @@ -465,8 +465,8 @@ export const errors = { "errors.videoAction.maskSource": "Choose a mask video from the canvas.", "errors.videoAction.depthDuration": "Depth motion capture needs media no longer than 30 seconds.", - "errors.videoAction.blockoutDuration": - "Video blockout needs media no longer than 30 seconds.", + "errors.videoAction.structureReferenceDuration": + "Structure reference needs media no longer than 30 seconds.", "errors.videoAction.audioDescription": "Describe the sound to separate.", "errors.videoAction.confirmSubtitles": "Confirm subtitle removal.", "errors.videoAction.frameNotReady": diff --git a/src/i18n/messages/en-US/tools.ts b/src/i18n/messages/en-US/tools.ts index def9323b3..7149ab7ea 100644 --- a/src/i18n/messages/en-US/tools.ts +++ b/src/i18n/messages/en-US/tools.ts @@ -226,8 +226,8 @@ export const tools = { "tools.videoEditor.prompt.mattingLabel": "Subjects to matte", "tools.videoEditor.prompt.mattingPlaceholder": "People are matted by default; list several subjects separated by commas, e.g. person, dog", - "tools.videoEditor.prompt.blockoutLabel": "Colored subjects", - "tools.videoEditor.prompt.blockoutPlaceholder": + "tools.videoEditor.prompt.structureReferenceLabel": "Colored subjects", + "tools.videoEditor.prompt.structureReferencePlaceholder": "People are colored by default; list several subjects separated by commas, e.g. person, dog", "tools.videoEditor.prompt.soundLabel": "Sound description", "tools.videoEditor.prompt.soundPlaceholder": @@ -273,9 +273,9 @@ export const tools = { "The box covers the lower subtitle band by default; drag it to the actual subtitle position. Sound is unchanged.", "tools.videoEditor.upscale.resolution": "Output resolution", "tools.videoEditor.depth.resolution": "Output resolution", - "tools.videoEditor.blockout.resolution": "Output resolution", - "tools.videoEditor.blockout.hint": - "Outputs a silent blockout video aligned frame by frame with the source: the scene as gray relief and each tracked subject in one fixed color, with none of the source's appearance. Use it as a reference video so generation follows the source's motion, pacing and camera.", + "tools.videoEditor.structureReference.resolution": "Output resolution", + "tools.videoEditor.structureReference.hint": + "Outputs a silent structure reference video aligned frame by frame with the source: the scene as gray relief and each tracked subject in one fixed color, with none of the source's appearance. Use it as a reference video to regenerate the clip with the source's motion, pacing and camera.", "tools.videoEditor.interpolation.fps": "Target frame rate", "tools.videoEditor.matting.mask": "Mask (white object on black)", "tools.videoEditor.composite.mask": "Mask video", diff --git a/src/i18n/messages/zh-CN/canvasShell.ts b/src/i18n/messages/zh-CN/canvasShell.ts index 535c4ea2c..53d0a90ee 100644 --- a/src/i18n/messages/zh-CN/canvasShell.ts +++ b/src/i18n/messages/zh-CN/canvasShell.ts @@ -125,7 +125,7 @@ export const canvasShell = { "canvas.selection.lastFrame": "尾帧", "canvas.selection.customFrame": "自定义截帧", "canvas.selection.depthCapture": "深度动作捕捉", - "canvas.selection.videoBlockout": "视频脱模", + "canvas.selection.structureReference": "结构参考", "canvas.selection.trimVideo": "时长修剪", "canvas.selection.audioSeparation": "声音分离", "canvas.selection.extractAudio": "提取音频", diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index f1dd9700f..cd00a6831 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -251,7 +251,7 @@ export const errors = { "errors.tools.phase.track": "正在识别并跟踪「{labels}」", "errors.tools.phase.matteVideo": "正在合成抠像视频", "errors.tools.phase.depth": "正在估计每一帧的深度", - "errors.tools.phase.blockout": "正在渲染白模", + "errors.tools.phase.structureReference": "正在渲染结构参考", "errors.tools.phase.separateAudio": "正在分离音轨", "errors.tools.phase.upscaleVideo": "正在放大视频", "errors.tools.phase.interpolate": "正在补帧到 {fps} fps", @@ -259,11 +259,11 @@ export const errors = { "errors.tools.phase.generic": "正在处理素材…", "errors.tools.error.interrupted": "服务重启,任务已中断,请重新提交。", "errors.tools.error.cancelled": "已取消。", - "errors.tools.error.blockoutDuration": - "视频脱模需要不超过 30 秒的素材,请先裁剪视频。", - "errors.tools.error.blockoutFrames": - "视频脱模单次最多处理 2048 帧,请先裁剪视频或降低帧率。", - "errors.tools.error.blockoutMisaligned": + "errors.tools.error.structureReferenceDuration": + "结构参考需要不超过 30 秒的素材,请先裁剪视频。", + "errors.tools.error.structureReferenceFrames": + "结构参考单次最多处理 2048 帧,请先裁剪视频或降低帧率。", + "errors.tools.error.structureReferenceMisaligned": "跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。", "errors.tools.error.failed": "工具执行出错,请检查素材和参数后重试。", "errors.tools.error.resultProcessing": @@ -361,7 +361,8 @@ export const errors = { "errors.videoAction.minDuration": "视频编辑需要 4–30 秒的素材。", "errors.videoAction.maskSource": "请选择画布上的遮罩视频。", "errors.videoAction.depthDuration": "深度动作捕捉需要不超过 30 秒的素材。", - "errors.videoAction.blockoutDuration": "视频脱模需要不超过 30 秒的素材。", + "errors.videoAction.structureReferenceDuration": + "结构参考需要不超过 30 秒的素材。", "errors.videoAction.audioDescription": "请描述要分离的声音。", "errors.videoAction.confirmSubtitles": "请确认擦除字幕。", "errors.videoAction.frameNotReady": "当前视频帧尚未解码完成,请稍候再截取。", diff --git a/src/i18n/messages/zh-CN/tools.ts b/src/i18n/messages/zh-CN/tools.ts index 319212600..3319da4ac 100644 --- a/src/i18n/messages/zh-CN/tools.ts +++ b/src/i18n/messages/zh-CN/tools.ts @@ -210,8 +210,8 @@ export const tools = { "tools.videoEditor.prompt.mattingLabel": "抠像对象", "tools.videoEditor.prompt.mattingPlaceholder": "默认抠出人物;可写多个对象,用逗号分隔,如:人物,狗", - "tools.videoEditor.prompt.blockoutLabel": "着色对象", - "tools.videoEditor.prompt.blockoutPlaceholder": + "tools.videoEditor.prompt.structureReferenceLabel": "着色对象", + "tools.videoEditor.prompt.structureReferencePlaceholder": "默认给人物着色;可写多个对象,用逗号分隔,如:人物,狗", "tools.videoEditor.prompt.soundLabel": "声音描述", "tools.videoEditor.prompt.soundPlaceholder": @@ -255,9 +255,9 @@ export const tools = { "选框默认覆盖底部字幕带,可拖动到字幕实际位置;声音保持不变。", "tools.videoEditor.upscale.resolution": "输出清晰度", "tools.videoEditor.depth.resolution": "输出清晰度", - "tools.videoEditor.blockout.resolution": "输出清晰度", - "tools.videoEditor.blockout.hint": - "输出与原片逐帧对齐的无声白模视频:场景为灰色浮雕,每个跟踪到的对象固定一种颜色,不带原片的外观。可作为参考视频,让生成沿用原片的动作、节奏和机位。", + "tools.videoEditor.structureReference.resolution": "输出清晰度", + "tools.videoEditor.structureReference.hint": + "输出与原片逐帧对齐的无声结构参考视频:场景为灰色浮雕,每个跟踪到的对象固定一种颜色,不带原片的外观。可作为参考视频,以原片的动作、节奏和机位重新生成画面。", "tools.videoEditor.interpolation.fps": "目标帧率", "tools.videoEditor.matting.mask": "遮罩(黑底白色对象)", "tools.videoEditor.composite.mask": "遮罩视频", diff --git a/tests/test_creation_media_publication.py b/tests/test_creation_media_publication.py index 6a925d4af..84a4f61fb 100644 --- a/tests/test_creation_media_publication.py +++ b/tests/test_creation_media_publication.py @@ -128,7 +128,7 @@ def node(item_id): assert (node(previous_id).visible, node(output_id).visible) == expected -def test_a_blockout_published_from_a_video_item_stays_a_video_with_its_source(project): +def test_a_structure_reference_published_from_a_video_item_stays_a_video_with_its_source(project): store, pid, session = project assets = CreationToolAssets(store) @@ -140,11 +140,11 @@ def upload(name): assert send(store, pid, 'canvas.show', session=session, item=dict(id=uuid4(), projectId=pid, kind='video', binding=dict(role='material', objectRef=asset_ref(source)))).status == 'applied' item = store.snapshot(pid).canvasItems[0] - result = assets.import_file(pid, uuid4(), 'blockout.mp4', mp4(1, size='96x54'), session, provenance=AssetProvenance(source='upload')) + result = assets.import_file(pid, uuid4(), 'structure-reference.mp4', mp4(1, size='96x54'), session, provenance=AssetProvenance(source='upload')) output = assets.assets.get(pid, result['id']) - payload = dict(itemId=item.id, source=asset_ref(source), outputs=[dict(itemId=uuid4(), asset=asset_ref(output), title='Blockout')], + payload = dict(itemId=item.id, source=asset_ref(source), outputs=[dict(itemId=uuid4(), asset=asset_ref(output), title='Structure reference')], document=dict(id=uuid4(), projectId=pid, kind='media_edit', data=dict( - tool='video-blockout', sources=[asset_ref(source)], sourceItems=[item.id], parameters={'resolution': '480P'}))) + tool='video-structure-reference', sources=[asset_ref(source)], sourceItems=[item.id], parameters={'resolution': '480P'}))) receipt = send(store, pid, 'canvas.publishMedia', session=session, versions=[ver('canvas_item', item), ver('asset', output)], **payload) assert receipt.status == 'applied', receipt saved = next(asset for asset in store.snapshot(pid).assets if asset.id == output.id) diff --git a/tests/test_localization.py b/tests/test_localization.py index 2d6ca7f93..c6e1348bf 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -47,11 +47,11 @@ def test_matting_error_codes_remain_localized_when_backend_copy_changes() -> Non assert localized_error(request('zh-CN'), chinese='更新后的中文', status=422, code=code) == '更新后的中文' -def test_blockout_error_codes_have_english_copy() -> None: +def test_structure_reference_error_codes_have_english_copy() -> None: for code, expected in [ - ('tool_blockout_duration', 'no longer than 30 seconds'), - ('tool_blockout_frames', 'at most 2048 frames'), - ('tool_blockout_misaligned', 'different frame counts'), + ('tool_structure_reference_duration', 'no longer than 30 seconds'), + ('tool_structure_reference_frames', 'at most 2048 frames'), + ('tool_structure_reference_misaligned', 'different frame counts'), ]: assert expected in localized_error(request('en-US'), chinese='更新后的中文', status=422, code=code) assert localized_error(request('zh-CN'), chinese='更新后的中文', status=422, code=code) == '更新后的中文' diff --git a/tests/test_blockout.py b/tests/test_structure_reference.py similarity index 84% rename from tests/test_blockout.py rename to tests/test_structure_reference.py index 0e0209b0d..b78725f22 100644 --- a/tests/test_blockout.py +++ b/tests/test_structure_reference.py @@ -3,7 +3,7 @@ from opendirector.domain.capabilities import Tracks from opendirector.domain.projects import ProjectError -from opendirector.media.blockout import SCENE, SUBJECTS, blockout_frame, subject_colors, write_blockout +from opendirector.media.structure_reference import SCENE, SUBJECTS, structure_frame, subject_colors, write_structure_reference pytestmark = [pytest.mark.cpu, pytest.mark.ready] @@ -37,7 +37,7 @@ def test_colours_follow_identities_in_order_of_first_appearance(): def test_one_identity_keeps_its_colour_when_its_position_among_instances_changes(tmp_path): tracks = Tracks(WIDTH, HEIGHT, 24.0, ((LEFT, RIGHT), (RIGHT, LEFT)), ((5, 9), (9, 5))) - write_blockout(depth_frames(tmp_path / 'depth', 2), tracks, tmp_path / 'out') + write_structure_reference(depth_frames(tmp_path / 'depth', 2), tracks, tmp_path / 'out') first, second = (Image.open(tmp_path / 'out' / f'{index:05d}.png').convert('RGB') for index in range(2)) assert tint(first.getpixel((3, 8))) == tint(second.getpixel((3, 8))) == 0 assert tint(first.getpixel((28, 8))) == tint(second.getpixel((28, 8))) == 1 @@ -46,19 +46,19 @@ def test_one_identity_keeps_its_colour_when_its_position_among_instances_changes def test_every_depth_frame_is_rendered_and_untracked_frames_keep_the_scene(tmp_path): tracks = Tracks(WIDTH, HEIGHT, 24.0, ((LEFT,), ())) - write_blockout(depth_frames(tmp_path / 'depth', 3), tracks, tmp_path / 'out') + write_structure_reference(depth_frames(tmp_path / 'depth', 3), tracks, tmp_path / 'out') frames = [Image.open(path).convert('RGB') for path in sorted((tmp_path / 'out').glob('*.png'))] assert len(frames) == 3 and all(frame.size == (WIDTH, HEIGHT) for frame in frames) assert tint(frames[0].getpixel((3, 8))) == 0 and not is_gray(frames[0].getpixel((3, 8))) assert all(is_gray(frame.getpixel((3, 8))) for frame in frames[1:]) with pytest.raises(ProjectError): - write_blockout([], tracks, tmp_path / 'empty') + write_structure_reference([], tracks, tmp_path / 'empty') def test_relief_is_neutral_with_nearer_surfaces_lighter_and_depth_steps_outlined(): step = Image.new('L', (64, 32), 40) step.paste(200, (32, 0, 64, 32)) - frame = blockout_frame(step, []) + frame = structure_frame(step, []) far, near, edge = frame.getpixel((8, 16)), frame.getpixel((56, 16)), frame.getpixel((31, 16)) assert is_gray(far) and is_gray(near) and near[0] > far[0] + 30 assert edge[0] < far[0] @@ -68,5 +68,5 @@ def test_relief_is_neutral_with_nearer_surfaces_lighter_and_depth_steps_outlined def test_a_mask_of_another_size_is_fitted_to_the_depth_frame(): mask = Image.new('L', (16, 8), 0) mask.paste(255, (0, 0, 8, 8)) - frame = blockout_frame(Image.new('L', (64, 32), 96), [(SUBJECTS[1], mask)]) + frame = structure_frame(Image.new('L', (64, 32), 96), [(SUBJECTS[1], mask)]) assert tint(frame.getpixel((12, 16))) == 1 and is_gray(frame.getpixel((52, 16))) diff --git a/tests/test_tool_tasks.py b/tests/test_tool_tasks.py index 57affbda2..a85a60fad 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -978,7 +978,7 @@ def test_depth_capture_rejects_long_clips_and_unknown_resolutions_before_calling assert log == [] -def configure_blockout(store): +def configure_structure_reference(store): configs = configure(store, SAM3) configs.save(*VDA, '', connection_type='self_hosted', protocol='vllm_omni_depth') return configs @@ -992,7 +992,7 @@ def uploaded_frames(request, tmp_path, name): return int(probe(path, 'stream=nb_read_frames', '-count_frames')['nb_read_frames']) -def blockout_server(prompts, depths, tmp_path, *, empty=False, extra_tracked_frames=0): +def structure_reference_server(prompts, depths, tmp_path, *, empty=False, extra_tracked_frames=0): depth = depth_server(depths, tmp_path) def track(request): @@ -1006,15 +1006,15 @@ def track(request): def output_frames(store, project_id, task, tmp_path): - path = tmp_path / f"blockout-{task['id']}.mp4" + path = tmp_path / f"reference-{task['id']}.mp4" path.write_bytes(CreationToolAssets(store).read_bytes(project_id, task['outputs'][0]['id'])) frames = [Image.open(item).convert('RGB') for item in processing.frames_of(path, tmp_path / f"frames-{task['id']}")] return frames, probe(path, 'stream=r_frame_rate,codec_name:format=duration') -def blockout(store, configs, server, project_id, session, source, **parameters): +def structure_reference(store, configs, server, project_id, session, source, **parameters): return run(store, configs, httpx.MockTransport(server), project_id, session, - {'tool': 'video-blockout', 'sourceAssetIds': [source], 'parameters': parameters}) + {'tool': 'video-structure-reference', 'sourceAssetIds': [source], 'parameters': parameters}) @pytest.mark.parametrize(('instance', 'expected'), [({'id': 4}, ((4,),) * 24), ({}, ()), ({'id': '4'}, ())], @@ -1033,25 +1033,27 @@ def handle(request): assert tracks.identities == expected and len(tracks.frames) == 24 -def test_video_blockout_needs_both_a_tracking_and_a_depth_model(project): +def test_structure_reference_needs_both_a_tracking_and_a_depth_model(project): store, _, _ = project tools = {item['id']: item for item in ToolTasks(store.local, configure(store, SAM3), None, projects=store).catalog()['tools']} - assert not tools['video-blockout']['available'] and tools['video-blockout']['reason'] == '需要接入具备「深度动作捕捉」能力的模型。' - tools = {item['id']: item for item in ToolTasks(store.local, configure_blockout(store), None, projects=store).catalog()['tools']} - assert tools['video-blockout']['available'] - assert [item['capability'] for item in tools['video-blockout']['requires']] == ['video.matting', 'video.motion_capture'] + assert not tools['video-structure-reference']['available'] + assert tools['video-structure-reference']['reason'] == '需要接入具备「深度动作捕捉」能力的模型。' + tools = {item['id']: item for item in ToolTasks(store.local, configure_structure_reference(store), None, projects=store).catalog()['tools']} + assert tools['video-structure-reference']['available'] + assert [item['capability'] for item in tools['video-structure-reference']['requires']] == ['video.matting', 'video.motion_capture'] -def test_video_blockout_keeps_every_frame_and_colours_the_tracked_subject(project, tmp_path): +def test_structure_reference_keeps_every_frame_and_colours_the_tracked_subject(project, tmp_path): store, project_id, session = project source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) prompts, depths = [], [] - task = blockout(store, configure_blockout(store), blockout_server(prompts, depths, tmp_path), project_id, session, source, resolution='480P') + server = structure_reference_server(prompts, depths, tmp_path) + task = structure_reference(store, configure_structure_reference(store), server, project_id, session, source, resolution='480P') assert task['status'] == 'succeeded', task['error'] assert prompts == ['person'] and [(item['width'], item['height'], item['frames']) for item in depths] == [(64, 36, 24)] assert task['modelConfigIds'].keys() == {'video.matting', 'video.motion_capture'} output = task['outputs'][0] - assert output['type'] == 'video/mp4' and (output['width'], output['height']) == (64, 36) and output['title'] == '视频脱模 480P' + assert output['type'] == 'video/mp4' and (output['width'], output['height']) == (64, 36) and output['title'] == '结构参考 480P' frames, stream = output_frames(store, project_id, task, tmp_path) assert len(frames) == 24 and (stream['codec_name'], stream['r_frame_rate']) == ('h264', '24/1') for frame in (frames[0], frames[-1]): @@ -1061,7 +1063,7 @@ def test_video_blockout_keeps_every_frame_and_colours_the_tracked_subject(projec assert abs(red - green) < 12 and abs(green - blue) < 12 and 90 < green < 200 -def test_video_blockout_puts_a_variable_frame_rate_source_on_a_constant_timeline(project, tmp_path): +def test_structure_reference_puts_a_variable_frame_rate_source_on_a_constant_timeline(project, tmp_path): store, project_id, session = project path = tmp_path / 'variable.mp4' subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=64x36:rate=10:duration=2', @@ -1071,37 +1073,38 @@ def test_video_blockout_puts_a_variable_frame_rate_source_on_a_constant_timeline assert [float(frame['best_effort_timestamp_time']) for frame in shown] == pytest.approx([0, 0.1, 0.2, 0.9, 1.4, 1.9], abs=0.0001) source = upload(store, project_id, session, 'variable.mp4', path.read_bytes()) depths = [] - task = blockout(store, configure_blockout(store), blockout_server([], depths, tmp_path), project_id, session, source) + server = structure_reference_server([], depths, tmp_path) + task = structure_reference(store, configure_structure_reference(store), server, project_id, session, source) assert task['status'] == 'succeeded', task['error'] frames, stream = output_frames(store, project_id, task, tmp_path) assert len(frames) == depths[0]['frames'] == 20 and stream['r_frame_rate'] == '10/1' assert float(stream['duration']) == pytest.approx(2.0, abs=0.01) -def test_video_blockout_without_a_subject_keeps_the_scene_unless_one_was_named(project, tmp_path): +def test_structure_reference_without_a_subject_keeps_the_scene_unless_one_was_named(project, tmp_path): store, project_id, session = project source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) - configs = configure_blockout(store) + configs = configure_structure_reference(store) prompts, depths = [], [] - server = blockout_server(prompts, depths, tmp_path, empty=True) + server = structure_reference_server(prompts, depths, tmp_path, empty=True) for parameters in ({}, {'prompt': ' ,, '}): - task = blockout(store, configs, server, project_id, session, source, **parameters) + task = structure_reference(store, configs, server, project_id, session, source, **parameters) assert task['status'] == 'succeeded', task['error'] frames, _ = output_frames(store, project_id, task, tmp_path) red, green, blue = frames[0].getpixel((12, 18)) assert len(frames) == 24 and abs(red - green) < 12 and abs(green - blue) < 12 - task = blockout(store, configs, server, project_id, session, source, prompt='猫咪') + task = structure_reference(store, configs, server, project_id, session, source, prompt='猫咪') assert task['status'] == 'failed' and task['errorDetails'] == {'code': 'tool_no_video_match', 'params': {'label': '猫咪'}} assert prompts == ['person', 'person', 'cat'] and len(depths) == 2 @pytest.mark.parametrize(('clip', 'parameters', 'code', 'text'), [ - ((31, '24'), {}, 'tool_blockout_duration', '不超过 30 秒'), - ((25, '90'), {}, 'tool_blockout_frames', '最多处理 2048 帧'), + ((31, '24'), {}, 'tool_structure_reference_duration', '不超过 30 秒'), + ((25, '90'), {}, 'tool_structure_reference_frames', '最多处理 2048 帧'), ((1, '24'), {'resolution': '1080P'}, 'invalid_input', '不在可选范围内'), - ((31, '24'), {'prompt': '三花猫'}, 'tool_blockout_duration', '不超过 30 秒'), + ((31, '24'), {'prompt': '三花猫'}, 'tool_structure_reference_duration', '不超过 30 秒'), ], ids=['too-long', 'too-many-frames', 'unknown-resolution', 'too-long-with-a-subject-to-translate']) -def test_video_blockout_rejects_unusable_input_before_calling_any_model(project, tmp_path, clip, parameters, code, text): +def test_structure_reference_rejects_unusable_input_before_calling_any_model(project, tmp_path, clip, parameters, code, text): store, project_id, session = project seconds, rate = clip data = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', f'color=c=gray:size=64x36:rate={rate}', '-t', str(seconds), @@ -1114,22 +1117,23 @@ def server(request): requests.append(request.url.path) return httpx.Response(500) - configs = configure_blockout(store) + configs = configure_structure_reference(store) configs.save(*CHAT, '', connection_type='self_hosted', protocol='openai') - task = blockout(store, configs, server, project_id, session, source, **parameters) + task = structure_reference(store, configs, server, project_id, session, source, **parameters) assert task['status'] == 'failed' and text in task['error'] and task['errorDetails']['code'] == code assert requests == [] and task['outputs'] == [] @pytest.mark.parametrize(('extra', 'status'), [(1, 'succeeded'), (-1, 'succeeded'), (2, 'failed')]) -def test_video_blockout_tolerates_one_frame_of_difference_and_refuses_more(project, tmp_path, extra, status): +def test_structure_reference_tolerates_one_frame_of_difference_and_refuses_more(project, tmp_path, extra, status): store, project_id, session = project source = upload(store, project_id, session, 'clip.mp4', mp4(1)) depths = [] - task = blockout(store, configure_blockout(store), blockout_server([], depths, tmp_path, extra_tracked_frames=extra), project_id, session, source) + server = structure_reference_server([], depths, tmp_path, extra_tracked_frames=extra) + task = structure_reference(store, configure_structure_reference(store), server, project_id, session, source) assert task['status'] == status, task['error'] if status == 'failed': - assert task['errorDetails']['code'] == 'tool_blockout_misaligned' and task['outputs'] == [] + assert task['errorDetails']['code'] == 'tool_structure_reference_misaligned' and task['outputs'] == [] else: assert len(output_frames(store, project_id, task, tmp_path)[0]) == depths[0]['frames'] == 24 diff --git a/tests/toolCatalog.test.ts b/tests/toolCatalog.test.ts index bbcf36da9..d11f2a6b9 100644 --- a/tests/toolCatalog.test.ts +++ b/tests/toolCatalog.test.ts @@ -354,7 +354,7 @@ test("video edit uses actual 4–30 second source metadata and rejects invented for (const resolution of ["480P", "720P"]) assert.deepEqual( validateToolTask( - createCanvasToolTask("video-blockout", [video.nodeId], { + createCanvasToolTask("video-structure-reference", [video.nodeId], { resolution, prompt: "人物,狗", }), @@ -365,7 +365,7 @@ test("video edit uses actual 4–30 second source metadata and rejects invented ); assert.ok( validateToolTask( - createCanvasToolTask("video-blockout", [video.nodeId], { + createCanvasToolTask("video-structure-reference", [video.nodeId], { resolution: "1080P", }), [video], diff --git a/tests/toolTaskText.test.ts b/tests/toolTaskText.test.ts index e4cc41c99..29e5c2f54 100644 --- a/tests/toolTaskText.test.ts +++ b/tests/toolTaskText.test.ts @@ -15,7 +15,10 @@ test("tool progress messages are localized, including counters", () => { ); assert.equal(toolTaskPhase("正在补帧到 60 fps"), "Interpolating to 60 fps"); assert.equal(toolTaskPhase("正在识别并跟踪「猫、狗」"), 'Detecting and tracking "猫、狗"'); - assert.equal(toolTaskPhase("正在渲染白模"), "Rendering the blockout"); + assert.equal( + toolTaskPhase("正在渲染结构参考"), + "Rendering the structure reference", + ); assert.equal(toolTaskPhase("provider custom text"), "provider custom text"); assert.equal(toolTaskPhase(null), undefined); assert.equal(toolTaskPhase("正在生成人物三视图(1/1)"), "Generating Character three-view (1/1)"); @@ -39,9 +42,21 @@ test("tool task errors never leak persisted Chinese", () => { "The tool failed. Check the media and parameters and try again.", ); for (const [code, english, chinese] of [ - ["tool_blockout_duration", /no longer than 30 seconds/, /不超过 30 秒/], - ["tool_blockout_frames", /at most 2048 frames/, /最多处理 2048 帧/], - ["tool_blockout_misaligned", /different frame counts/, /帧数不一致/], + [ + "tool_structure_reference_duration", + /no longer than 30 seconds/, + /不超过 30 秒/, + ], + [ + "tool_structure_reference_frames", + /at most 2048 frames/, + /最多处理 2048 帧/, + ], + [ + "tool_structure_reference_misaligned", + /different frame counts/, + /帧数不一致/, + ], ] as const) { assert.match(toolTaskError("后端文案已更新", undefined, { code })!, english); setActiveLocale("zh-CN"); diff --git a/tests/videoActionRuntime.test.ts b/tests/videoActionRuntime.test.ts index 1e70c8d7a..783b7384e 100644 --- a/tests/videoActionRuntime.test.ts +++ b/tests/videoActionRuntime.test.ts @@ -42,7 +42,7 @@ test("dedicated video settings survive the shared task persistence boundary", () for (const tool of [ "video-upscale", "video-depth-capture", - "video-blockout", + "video-structure-reference", "video-frame-interpolation", "video-matting", "audio-separation", @@ -122,11 +122,21 @@ test("AI video controls reject incomplete descriptions, invalid restored choices /30/, ); assert.match( - videoActionInputError("video-blockout", { resolution: "720P" }, 31, range)!, - /视频脱模.*30/, + videoActionInputError( + "video-structure-reference", + { resolution: "720P" }, + 31, + range, + )!, + /结构参考.*30/, ); assert.match( - videoActionInputError("video-blockout", { resolution: "1080P" }, 6, range)!, + videoActionInputError( + "video-structure-reference", + { resolution: "1080P" }, + 6, + range, + )!, /选项/, ); assert.match( From 5779b98a8ec7bfae7a10a48bdb01c6024bd05372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Fri, 4 Dec 2026 04:39:17 +0000 Subject: [PATCH 5/5] [feat] canvas: run structure reference from the agent and CLI, and bound and align it on the clip it sends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Review of #612 left three points open: the tool could only be run from the canvas, the 2048-frame limit was estimated from the container's duration, and tracking and depth were allowed to differ by one frame. - Agent tools `video_structure_reference` (`taskId`, `sourceAssetId`, `resolution`, optional `subjects`) and `structure_reference_task` (`get`, `cancel`, `publish`), and CLI commands `opendirector video structure-reference` and `video structure-reference-task`, in the shape #652 gave video compression. The two task tools share one tool-id and refusal lookup (`TASK_TOOLS`), and the body of `video compression-task` moved into `tool_task_command`, which both task commands call. Compression's behaviour is unchanged. - The recipe counts the frames of the constant-rate clip it is about to send and refuses more than 2048 before any model call, the subject translation included. The estimate from duration and frame rate stays as the cheap first check. - Tracking and depth must each return exactly that number of frames. A different count fails the task with `tool_structure_reference_misaligned`; a tracking mismatch is refused before the depth call. The one-frame tolerance is gone, and the message names the video as the reference in both locales. - `docs/guides/cli.md` has a section for the commands in both languages, and both user guides point to it. - Tests: the agent tools from submit through a replayed submit, publish and cancel, with the refusal in both directions between the two task tools; command discovery for the two CLI commands; one frame more or fewer from tracking or from depth; a variable-rate clip of 2048 and of 2049 frames whose container states a shorter duration. Refs #444 Co-Authored-By: Claude Fable 5.2 Signed-off-by: 汪志鹏 --- apps/api/src/opendirector_api/localization.py | 2 +- docs/guides/cli.md | 16 ++++ docs/guides/user-guide.md | 2 +- docs/guides/user-guide.zh-CN.md | 2 +- packages/core/src/opendirector/agent/tools.py | 29 +++++- .../application/tool_video_recipes.py | 21 +++-- packages/core/src/opendirector/cli.py | 39 ++++++-- .../core/src/opendirector/media/processing.py | 6 ++ src/i18n/messages/en-US/errors.ts | 2 +- src/i18n/messages/zh-CN/errors.ts | 2 +- tests/test_cli.py | 6 +- tests/test_localization.py | 2 +- tests/test_tool_tasks.py | 93 ++++++++++++++++--- tests/toolTaskText.test.ts | 4 +- 14 files changed, 190 insertions(+), 36 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 99cfaa77f..c3ff3339b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -84,7 +84,7 @@ 'tool_no_video_match': 'The requested subject was not found in the video. Try a different description.', 'tool_structure_reference_duration': 'Structure reference needs a clip no longer than 30 seconds. Trim the video first.', 'tool_structure_reference_frames': 'Structure reference processes at most 2048 frames at a time. Trim the video or lower its frame rate first.', - 'tool_structure_reference_misaligned': 'Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.', + 'tool_structure_reference_misaligned': 'Tracking or depth returned a different number of frames than the video, so the frames cannot be aligned. Try again.', 'voice_upload_type': 'Upload the voice recording using multipart/form-data.', 'voice_upload_form': 'Check the recording, form fields and text lengths, then try the upload again.', 'voice_model_unsupported': 'This checkpoint does not accept uploaded voices. Choose a Base model for voice cloning or a compatible built-in voice.', diff --git a/docs/guides/cli.md b/docs/guides/cli.md index b5c29b91f..d7bc3e2cb 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -245,6 +245,22 @@ opendirector video compression-task TASK_ID opendirector video compression-task TASK_ID --action publish ``` +## Structure reference / 结构参考 + +**Structure reference** turns a clip of up to 30 seconds into a silent reference video on the source's timeline: the scene as gray relief and each tracked subject (people by default) in one solid color. It needs a video tracking model (such as SAM 3) and a model on the vLLM-Omni depth protocol. The task keeps the original; publishing a successful task places the structure reference on a new canvas node. + +**结构参考**把不超过 30 秒的视频转换成与原片时间对齐的无声参考视频:场景为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色。需要接入视频跟踪模型(如 SAM 3)和 vLLM-Omni 深度接口上的模型。任务保留原片;任务成功后发布,会把结构参考放到新的画布节点上。 + +From the CLI, supply the source asset ID and a stable operation ID, which is also the task ID. `--resolution` is `480P` (default) or `720P`; `--subjects` names the subjects to color, separated by commas. Query the task, request cancellation with `--action cancel`, or publish a successful result with `--action publish`. Agents use the `video_structure_reference` and `structure_reference_task` tools with the same fields. + +在 CLI 中传入源素材 ID 和固定的操作 ID,操作 ID 同时也是任务 ID。`--resolution` 为 `480P`(默认)或 `720P`;`--subjects` 填写要着色的对象,多个用逗号分隔。可以查询任务,用 `--action cancel` 请求取消,或用 `--action publish` 将成功结果发布到画布。Agent 使用字段相同的 `video_structure_reference` 和 `structure_reference_task` 工具。 + +```sh +opendirector video structure-reference --asset-id ASSET_ID --operation-id TASK_ID --resolution 720P --subjects "person, dog" +opendirector video structure-reference-task TASK_ID +opendirector video structure-reference-task TASK_ID --action publish +``` + ## Web Motion documents and rendering / 动效编辑文档与渲染 Motion nodes are saved as `editor` documents with `kind: "motion"` and managed via `editor create`, `editor save`, `canvas show`, and `canvas attach-editor`. Use the `motion` command group to inspect skills, run rendered frame diagnostics, export local MP4 files, or atomically publish the rendered MP4 as a video node linked to its source Motion node (`provenance.source: "rendered"` and `provenance.sourceItemId`) through the same server-side headless Chrome + FFmpeg pipeline used by Motion Studio: diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index eff8f8286..2bc75a5e4 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -89,7 +89,7 @@ To make music from a reference recording, connect an audio node to a YuE2 music To use **Depth motion capture** on a video, add a video model with the **vLLM-Omni depth** protocol, for example `depth-anything/Video-Depth-Anything-Small` served by `vllm serve --omni`. The tool turns a clip of up to 30 seconds into a grayscale depth video at 480P or 720P, frame for frame, with near objects bright and far ones dark, ready to use as a motion and structure reference. The depth model does not generate video. -**Structure reference** turns a video of up to 30 seconds into a reference for regenerating it with the same motion, timing and camera: a video aligned frame by frame with the source, in which the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame rate and duration match the source, and so does the frame count of a constant-frame-rate clip; a variable-frame-rate clip is first resampled at its nominal rate, so the structure reference lines up with the source by time. The output is silent and capped at 8 Mbit/s. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The structure reference is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The structure reference is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. +**Structure reference** turns a video of up to 30 seconds into a reference for regenerating it with the same motion, timing and camera: a video aligned frame by frame with the source, in which the scene is rendered as gray relief and each tracked subject (people by default; name other subjects separated by commas) gets one fixed solid color. The source's faces, clothing, materials, lighting and colors are not kept. Frame rate and duration match the source, and so does the frame count of a constant-frame-rate clip; a variable-frame-rate clip is first resampled at its nominal rate, so the structure reference lines up with the source by time. The output is silent and capped at 8 Mbit/s. It needs both a segmentation model that can track through video (such as SAM 3) and the depth model above. The structure reference is an ordinary video asset: connect it to a video node as a reference video so the new footage follows the source's motion, pacing, camera and scene structure, and set the new character and style with reference images or the prompt. The structure reference is rendered from per-frame depth and masks. It is not an editable 3D scene and does not infer occluded limbs. When no person is found for the default subject, the result still contains the scene. Agents and the CLI run the same task with the `video_structure_reference` and `structure_reference_task` tools or `opendirector video structure-reference` and `video structure-reference-task` (see the [CLI guide](cli.md)). In **General** settings, you can switch themes and adjust the watermark removal option. Watermark settings affect only content generated afterward, and the actual effect depends on support from the model service. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 98e515404..6f3498498 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -76,7 +76,7 @@ HTTP 400。 使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。 -**结构参考** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的结构参考视频,用于以相同的动作、节奏和机位重新生成:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧率和时长与原片一致,恒定帧率的素材帧数也一致;可变帧率的素材会先按其标称帧率重采样,结构参考按时间与原片对齐。输出没有声音,码率上限为 8 Mbit/s。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。结构参考视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。结构参考由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的结构参考。 +**结构参考** 把一段不超过 30 秒的视频转换成与原片逐帧对齐的结构参考视频,用于以相同的动作、节奏和机位重新生成:场景渲染为灰色浮雕,跟踪到的对象(默认人物,可填写其他对象,多个用逗号分隔)各用一种固定的纯色,不保留原片的人物外观、服装、材质和光色。帧率和时长与原片一致,恒定帧率的素材帧数也一致;可变帧率的素材会先按其标称帧率重采样,结构参考按时间与原片对齐。输出没有声音,码率上限为 8 Mbit/s。它需要同时接入具备视频跟踪能力的分割模型(如 SAM 3)和上面的深度模型。结构参考视频是普通的视频素材,可以连到视频节点作为参考视频,让新画面沿用原片的动作、节奏、机位和场景结构,再用参考图片或提示词指定新的人物和风格。结构参考由每帧深度和遮罩渲染得到,不是可编辑的三维场景,也不会推算被遮挡的肢体;没有识别到默认的人物时仍输出只有场景的结构参考。Agent 和 CLI 通过 `video_structure_reference`、`structure_reference_task` 工具或 `opendirector video structure-reference`、`video structure-reference-task` 命令执行同一任务(见 [CLI 指南](cli.md))。 在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。 diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index a78550032..81a5d7be4 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -356,6 +356,20 @@ def tools() -> list[dict]: {'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'}, 'action': {'type': 'string', 'enum': ['get', 'cancel', 'publish']}}, 'required': ['taskId', 'action'], 'additionalProperties': False})) + result.append(tool_schema('video_structure_reference', + 'Start a structure reference of a video (gray relief scene and one solid color per tracked subject, frame-aligned and silent) ' + 'without overwriting the source. Needs video tracking and depth models; clips up to 30 seconds. ' + 'Returns a durable task; inspect with structure_reference_task and publish explicitly after success.', + {'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'}, + 'sourceAssetId': {'type': 'string', 'format': 'uuid'}, + 'resolution': {'type': 'string', 'enum': ['480P', '720P']}, + 'subjects': {'type': 'string', 'description': 'Comma-separated subjects to color, e.g. "person, dog". People when omitted.'}}, + 'required': ['taskId', 'sourceAssetId', 'resolution'], 'additionalProperties': False})) + result.append(tool_schema('structure_reference_task', + 'Inspect, request cancellation, or publish a successful structure reference as a new canvas node. Reuse the original task ID.', + {'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'}, + 'action': {'type': 'string', 'enum': ['get', 'cancel', 'publish']}}, + 'required': ['taskId', 'action'], 'additionalProperties': False})) result.append(tool_schema('prompt_optimize', 'Rewrite an image or video draft with its saved references and the configured text model. ' 'Return a draft only; does not edit the node or generate media. Use [[OD_REF_n]] and inlineReferences to retain inline reference positions.', @@ -404,6 +418,10 @@ async def cli_prompt_rewrite(runtime, model, thinking, messages): return await prompt_rewrite.rewrite(runtime, model, thinking, messages) +TASK_TOOLS = {'compression_task': ('video-compress', 'Select a video compression task.'), + 'structure_reference_task': ('video-structure-reference', 'Select a structure reference task.')} + + class AgentTools: def __init__(self, projects, generation, configs, chat_provider=None): self.prompt_optimization = PromptOptimization(projects, configs, chat_provider or ChatCompletions(), @@ -418,7 +436,7 @@ def __init__(self, projects, generation, configs, chat_provider=None): async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: str, name: str, arguments: dict, roots: list[Path], config: dict | None, native_runtime: str | None = None, execution_directory: Path | None = None, *, runtime_model=None, thinking='auto') -> JsonValue: - if name in {'video_compress', 'compression_task'}: + if name in {'video_compress', 'video_structure_reference', *TASK_TOOLS}: service = self.generation.tool_tasks task_id = str(UUID(arguments['taskId'])) pid = str(project_id) @@ -426,9 +444,14 @@ async def execute(self, project_id: UUID, turn_id: UUID, session: str, call_id: return await service.submit(pid, dict(id=task_id, tool='video-compress', sourceAssetIds=[str(UUID(arguments['sourceAssetId']))], parameters={'preset': arguments['preset']}), session) + if name == 'video_structure_reference': + return await service.submit(pid, dict(id=task_id, tool='video-structure-reference', + sourceAssetIds=[str(UUID(arguments['sourceAssetId']))], + parameters={'resolution': arguments['resolution'], 'prompt': arguments.get('subjects', '')}), session) + tool, refusal = TASK_TOOLS[name] task = await asyncio.to_thread(service.get, pid, task_id) - if task['tool'] != 'video-compress': - raise ProjectError('Select a video compression task.', 422, code='invalid_input') + if task['tool'] != tool: + raise ProjectError(refusal, 422, code='invalid_input') if arguments['action'] == 'cancel': return await service.cancel(pid, task_id, session, wait=False) if arguments['action'] == 'publish': diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index a9f997165..827e8264b 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -247,6 +247,10 @@ async def depth_capture(ctx: ToolContext): STRUCTURE_REFERENCE_MAX_MEGABITS = 8 +STRUCTURE_REFERENCE_FRAMES = f'结构参考单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。' + +STRUCTURE_REFERENCE_MISALIGNED = '跟踪或深度结果的帧数与视频不一致,无法逐帧对齐,请重试。' + async def structure_reference(ctx: ToolContext): source = _source_video(ctx) resolution = ctx.choice('resolution', tuple(DEPTH_SHORT_EDGES), '480P') @@ -256,23 +260,28 @@ async def structure_reference(ctx: ToolContext): if not 0 < info['duration'] <= DEPTH_MAX_SECONDS + 0.05: raise ProjectError(f'结构参考需要不超过 {DEPTH_MAX_SECONDS} 秒的素材,请先裁剪视频。', 422, code='tool_structure_reference_duration') if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES: - raise ProjectError(f'结构参考单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。', 422, code='tool_structure_reference_frames') - named = await ctx.concepts(ctx.text('prompt'), ()) - pairs = named or await ctx.concepts('', ('人物',)) - label = '、'.join(label for _, label in pairs) + raise ProjectError(STRUCTURE_REFERENCE_FRAMES, 422, code='tool_structure_reference_frames') await ctx.progress('正在整理视频') width, height = _depth_size(info['width'], info['height'], DEPTH_SHORT_EDGES[resolution]) clip = await blocking(media.constant_rate_picture, raw, work.path / 'clip.mp4', width=width, height=height, fps=info['fps']) + count = await blocking(media.frame_count, clip) + if count > DEPTH_MAX_FRAMES: + raise ProjectError(STRUCTURE_REFERENCE_FRAMES, 422, code='tool_structure_reference_frames') + named = await ctx.concepts(ctx.text('prompt'), ()) + pairs = named or await ctx.concepts('', ('人物',)) + label = '、'.join(label for _, label in pairs) await ctx.progress(f'正在识别并跟踪「{label}」') tracks = await ctx.track(clip.read_bytes(), tuple(concept for concept, _ in pairs)) + if len(tracks.frames) != count: + raise ProjectError(STRUCTURE_REFERENCE_MISALIGNED, 502, code='tool_structure_reference_misaligned') if named and not any(tracks.frames): raise ToolInputError(f'视频中没有识别到「{label}」,请换一种描述后重试。', code='tool_no_video_match', label=label) await ctx.progress('正在估计每一帧的深度') depth = work.write('depth.mp4', await ctx.depth(clip.read_bytes())) await ctx.progress('正在渲染结构参考') frames = await blocking(media.frames_of, depth, work.path / 'depth-frames', gray=True) - if abs(len(frames) - len(tracks.frames)) > 1: - raise ProjectError('跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。', 502, code='tool_structure_reference_misaligned') + if len(frames) != count: + raise ProjectError(STRUCTURE_REFERENCE_MISALIGNED, 502, code='tool_structure_reference_misaligned') await blocking(write_structure_reference, frames, tracks, work.path / 'reference') data = await blocking(media.encode_frames, str(work.path / 'reference' / '%05d.png'), info['fps'], work.path / 'reference.mp4', crf=STRUCTURE_REFERENCE_CRF, max_megabits=STRUCTURE_REFERENCE_MAX_MEGABITS) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 2982c1daf..a0e31c5dc 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -498,17 +498,15 @@ def video_compress(ctx: typer.Context, asset_id: Annotated[UUID, typer.Option()] emit(value) -@group("video").command("compression-task", help="Query a compression task, request cancellation or publish its successful output.") -def compression_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument()], - action: Annotated[Literal['get', 'cancel', 'publish'], typer.Option()] = 'get'): +def tool_task_command(ctx: typer.Context, name: str, tool: str, refusal: str, task_id: UUID, action: str): client = ctx.obj client.command = ctx.command_path if client.live: - value = client.call('compression_task', dict(taskId=str(task_id), action=action)) + value = client.call(name, dict(taskId=str(task_id), action=action)) else: value = client.request('GET', client.path(f'/tool-tasks/{task_id}')) - if value['tool'] != 'video-compress': - raise ProjectError('Select a video compression task.', 422) + if value['tool'] != tool: + raise ProjectError(refusal, 422) if action != 'get': client.open() suffix = 'cancel' if action == 'cancel' else 'placement' @@ -517,6 +515,35 @@ def compression_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument emit(value) +@group("video").command("compression-task", help="Query a compression task, request cancellation or publish its successful output.") +def compression_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument()], + action: Annotated[Literal['get', 'cancel', 'publish'], typer.Option()] = 'get'): + tool_task_command(ctx, 'compression_task', 'video-compress', 'Select a video compression task.', task_id, action) + + +@group("video").command("structure-reference", help="Render one video as a structure reference in the background; keeps the original. Query the returned task ID.") +def video_structure_reference(ctx: typer.Context, asset_id: Annotated[UUID, typer.Option()], + operation_id: Annotated[UUID, typer.Option()], + resolution: Annotated[Literal['480P', '720P'], typer.Option()] = '480P', + subjects: Annotated[str, typer.Option(help='Comma-separated subjects to color; people when omitted.')] = ''): + client = ctx.obj + client.command = ctx.command_path + if client.live: + value = client.call('video_structure_reference', dict(taskId=str(operation_id), sourceAssetId=str(asset_id), + resolution=resolution, subjects=subjects), identity=operation_id) + else: + client.open() + value = client.request('POST', client.path('/tool-tasks'), json=dict(id=str(operation_id), + tool='video-structure-reference', sourceAssetIds=[str(asset_id)], parameters={'resolution': resolution, 'prompt': subjects})) + emit(value) + + +@group("video").command("structure-reference-task", help="Query a structure reference task, request cancellation or publish its successful output.") +def structure_reference_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument()], + action: Annotated[Literal['get', 'cancel', 'publish'], typer.Option()] = 'get'): + tool_task_command(ctx, 'structure_reference_task', 'video-structure-reference', 'Select a structure reference task.', task_id, action) + + TAKE_OVER_HINT = { "en": ("Or, with the user's agreement, run the command again with --take-over before the subcommand; that window " "then switches to preview and can take editing back with \u201cEdit in this window\u201d."), diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index b50c37f02..2deaf0930 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -260,6 +260,12 @@ def constant_rate_picture(source: Path, out: Path, *, width: int, height: int, f return out +def frame_count(path: Path) -> int: + output = _run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-count_frames', '-show_entries', 'stream=nb_read_frames', + '-of', 'csv=p=0', str(path)], timeout=300) + return int(output.decode().strip().split(',')[0]) + + def frames_of(source: Path, folder: Path, *, gray=False) -> list[Path]: """Every decoded frame of source as a PNG, in order (grayscale when gray).""" folder.mkdir() diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index db623a3d1..9a380ec07 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -342,7 +342,7 @@ export const errors = { "errors.tools.error.structureReferenceFrames": "Structure reference processes at most 2048 frames at a time. Trim the video or lower its frame rate first.", "errors.tools.error.structureReferenceMisaligned": - "Tracking and depth returned different frame counts, so the frames cannot be aligned. Try again.", + "Tracking or depth returned a different number of frames than the video, so the frames cannot be aligned. Try again.", "errors.tools.error.failed": "The tool failed. Check the media and parameters and try again.", "errors.tools.error.resultProcessing": diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index c88b4f629..c3a461f0b 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -264,7 +264,7 @@ export const errors = { "errors.tools.error.structureReferenceFrames": "结构参考单次最多处理 2048 帧,请先裁剪视频或降低帧率。", "errors.tools.error.structureReferenceMisaligned": - "跟踪结果与深度结果的帧数不一致,无法逐帧对齐,请重试。", + "跟踪或深度结果的帧数与视频不一致,无法逐帧对齐,请重试。", "errors.tools.error.failed": "工具执行出错,请检查素材和参数后重试。", "errors.tools.error.resultProcessing": "生成结果处理失败,请检查服务协议;不会自动重新提交。", diff --git a/tests/test_cli.py b/tests/test_cli.py index aba07fb0e..502962fb8 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -719,7 +719,7 @@ def test_capabilities_names_commands_that_have_no_command_model(help_color): listed = {entry["command"]: entry for entry in json.loads(result.output)["commands"]} assert {"job wait", "job show", "project show", "query", "model list", "model show", "model availability", "asset import", "video create", "video compress", - "video compression-task", "canvas add-material", + "video compression-task", "video structure-reference", "video structure-reference-task", "canvas add-material", "canvas text create", "timeline import", "timeline export", "timeline default-font", "voice list", "voice create", "voice delete"} <= set(listed) assert listed["canvas add-material"]["required"] == ["asset", "x", "y"] @@ -727,6 +727,8 @@ def test_capabilities_names_commands_that_have_no_command_model(help_color): assert "options" not in listed["job show"] assert set(listed["video compress"]["required"]) == {"asset_id", "operation_id"} assert listed["video compression-task"]["required"] == ["task_id"] + assert set(listed["video structure-reference"]["required"]) == {"asset_id", "operation_id"} + assert listed["video structure-reference-task"]["required"] == ["task_id"] result = CliRunner().invoke(cli.app, ["capabilities"]) assert result.exit_code == 0, result.output detailed = {entry["command"]: entry for entry in json.loads(result.output)["commands"]} @@ -735,6 +737,8 @@ def test_capabilities_names_commands_that_have_no_command_model(help_color): assert "--object-id" in query_options assert {"--asset-id", "--operation-id", "--preset"} <= set(detailed["video compress"]["options"]) assert "--action" in detailed["video compression-task"]["options"] + assert {"--asset-id", "--operation-id", "--resolution", "--subjects"} <= set(detailed["video structure-reference"]["options"]) + assert "--action" in detailed["video structure-reference-task"]["options"] @pytest.mark.parametrize("live", [False, True], ids=["http", "agent"]) diff --git a/tests/test_localization.py b/tests/test_localization.py index c6e1348bf..d7fbd5f16 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -51,7 +51,7 @@ def test_structure_reference_error_codes_have_english_copy() -> None: for code, expected in [ ('tool_structure_reference_duration', 'no longer than 30 seconds'), ('tool_structure_reference_frames', 'at most 2048 frames'), - ('tool_structure_reference_misaligned', 'different frame counts'), + ('tool_structure_reference_misaligned', 'different number of frames than the video'), ]: assert expected in localized_error(request('en-US'), chinese='更新后的中文', status=422, code=code) assert localized_error(request('zh-CN'), chinese='更新后的中文', status=422, code=code) == '更新后的中文' diff --git a/tests/test_tool_tasks.py b/tests/test_tool_tasks.py index a85a60fad..c148ecc08 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -5,12 +5,14 @@ import random import subprocess import time -from uuid import uuid4 +from types import SimpleNamespace +from uuid import UUID, uuid4 import httpx import pytest from PIL import Image +from opendirector.agent.tools import AgentTools from opendirector.application.tool_tasks import ToolTasks from opendirector.domain.capabilities import TrackRequest from opendirector.domain.projects import ProjectError @@ -880,7 +882,7 @@ def configure_depth(store): return configs -def depth_server(log, tmp_path, *, metric=False, shade=40, meters=(0.0, 1.0)): +def depth_server(log, tmp_path, *, metric=False, shade=40, meters=(0.0, 1.0), extra_frames=0): """Answers /videos/depth with a flat gray clip of the uploaded clip's size and frame count.""" def handle(request): assert request.url.path == '/v1/videos/depth' @@ -902,7 +904,7 @@ def handle(request): log.append({**fields, 'width': info['width'], 'height': info['height'], 'frames': int(info['nb_read_frames'])}) color = f'0x{shade:02x}{shade:02x}{shade:02x}' video = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', f"color=c={color}:size={info['width']}x{info['height']}:rate=24", - '-frames:v', str(info['nb_read_frames']), '-pix_fmt', 'yuv420p', '-f', 'mp4', + '-frames:v', str(int(info['nb_read_frames']) + extra_frames), '-pix_fmt', 'yuv420p', '-f', 'mp4', '-movflags', 'frag_keyframe+empty_moov', 'pipe:1'], capture_output=True, check=True).stdout return httpx.Response(200, json={'width': info['width'], 'height': info['height'], 'num_frames': int(info['nb_read_frames']), 'fps': 24.0, 'metric': metric, 'depth_min': meters[0], 'depth_max': meters[1], @@ -992,8 +994,8 @@ def uploaded_frames(request, tmp_path, name): return int(probe(path, 'stream=nb_read_frames', '-count_frames')['nb_read_frames']) -def structure_reference_server(prompts, depths, tmp_path, *, empty=False, extra_tracked_frames=0): - depth = depth_server(depths, tmp_path) +def structure_reference_server(prompts, depths, tmp_path, *, empty=False, extra_tracked_frames=0, extra_depth_frames=0): + depth = depth_server(depths, tmp_path, extra_frames=extra_depth_frames) def track(request): prompt = request.read().split(b'name="prompt"\r\n\r\n', 1)[1].split(b'\r\n', 1)[0].decode() @@ -1124,18 +1126,85 @@ def server(request): assert requests == [] and task['outputs'] == [] -@pytest.mark.parametrize(('extra', 'status'), [(1, 'succeeded'), (-1, 'succeeded'), (2, 'failed')]) -def test_structure_reference_tolerates_one_frame_of_difference_and_refuses_more(project, tmp_path, extra, status): +@pytest.mark.parametrize(('service', 'extra'), [('tracked', 1), ('tracked', -1), ('depth', 1), ('depth', -1)]) +def test_structure_reference_refuses_a_tracking_or_depth_answer_with_another_frame_count_than_the_clip(project, tmp_path, service, extra): store, project_id, session = project source = upload(store, project_id, session, 'clip.mp4', mp4(1)) depths = [] - server = structure_reference_server([], depths, tmp_path, extra_tracked_frames=extra) + server = structure_reference_server([], depths, tmp_path, **{f'extra_{service}_frames': extra}) task = structure_reference(store, configure_structure_reference(store), server, project_id, session, source) - assert task['status'] == status, task['error'] - if status == 'failed': - assert task['errorDetails']['code'] == 'tool_structure_reference_misaligned' and task['outputs'] == [] + assert task['status'] == 'failed' and task['errorDetails']['code'] == 'tool_structure_reference_misaligned' and task['outputs'] == [] + assert len(depths) == (1 if service == 'depth' else 0) + + +@pytest.mark.parametrize(('last', 'refused'), [(2047, False), (2048, True)], ids=['2048-frames', '2049-frames']) +def test_structure_reference_bounds_the_frames_it_sends_when_the_container_understates_its_length(project, tmp_path, monkeypatch, last, refused): + store, project_id, session = project + path = tmp_path / 'variable.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', f'color=c=gray:size=64x36:rate=100:duration={(last + 1) / 100}', + '-vf', f"select='lt(n,8)+eq(n,{last})'", processing._frame_sync_option(), 'passthrough', + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(path)], check=True, capture_output=True) + source = upload(store, project_id, session, 'variable.mp4', path.read_bytes()) + stated = processing.video_info + monkeypatch.setattr(processing, 'video_info', lambda clip: {**stated(clip), 'duration': 10.0}) + requests = [] + + def server(request): + requests.append((request.url.path, uploaded_frames(request, tmp_path, 'sent.mp4'))) + return httpx.Response(500) + + configs = configure_structure_reference(store) + configs.save(*CHAT, '', connection_type='self_hosted', protocol='openai') + task = structure_reference(store, configs, server, project_id, session, source, **({'prompt': '三花猫'} if refused else {})) + assert task['status'] == 'failed' and task['outputs'] == [] + if refused: + assert task['errorDetails']['code'] == 'tool_structure_reference_frames' and requests == [] else: - assert len(output_frames(store, project_id, task, tmp_path)[0]) == depths[0]['frames'] == 24 + assert requests == [('/v1/videos/segmentations', 2048)] + + +def test_structure_reference_runs_from_the_agent_tools_and_publishes_a_video_node(project, tmp_path): + store, project_id, session = project + source = upload(store, project_id, session, 'clip.mp4', sound_mp4(1)) + configs = configure_structure_reference(store) + assets = CreationToolAssets(store) + transport = httpx.MockTransport(structure_reference_server([], [], tmp_path)) + + async def go(): + service = ToolTasks(store.local, configs, assets, transport=transport, poll_interval=0, projects=store) + agent = AgentTools(store, SimpleNamespace(tool_tasks=service), configs) + + async def call(name, **arguments): + return await agent.execute(UUID(project_id), uuid4(), session, str(uuid4()), name, arguments, [], None) + try: + task_id = str(uuid4()) + arguments = dict(taskId=task_id, sourceAssetId=source, resolution='480P', subjects='person, dog') + assert (await call('video_structure_reference', **arguments))['status'] in {'queued', 'running'} + await asyncio.gather(*service.jobs.values()) + done = await call('structure_reference_task', taskId=task_id, action='get') + assert done['status'] == 'succeeded', done + assert done['tool'] == 'video-structure-reference' and done['parameters'] == {'resolution': '480P', 'prompt': 'person, dog'} + assert (await call('video_structure_reference', **arguments))['outputs'] == done['outputs'] and len(service.list(project_id)) == 1 + output = done['outputs'][0] + assert output['type'] == 'video/mp4' and (output['width'], output['height']) == (64, 36) + assert (await call('structure_reference_task', taskId=task_id, action='publish'))['placement'] == 'placed' + placed = [item for item in store.snapshot(project_id).canvasItems if item.kind == 'video'] + assert [str(item.binding.objectRef.assetId) for item in placed] == [output['id']] + with pytest.raises(ProjectError, match='Select a video compression task.'): + await call('compression_task', taskId=task_id, action='get') + compression = str(uuid4()) + await call('video_compress', taskId=compression, sourceAssetId=source, preset='preview') + await asyncio.gather(*service.jobs.values()) + with pytest.raises(ProjectError, match='Select a structure reference task.'): + await call('structure_reference_task', taskId=compression, action='publish') + waiting = str(uuid4()) + await call('video_structure_reference', taskId=waiting, sourceAssetId=source, resolution='720P') + await call('structure_reference_task', taskId=waiting, action='cancel') + await asyncio.gather(*service.jobs.values(), return_exceptions=True) + assert (await call('structure_reference_task', taskId=waiting, action='get'))['status'] == 'cancelled' + finally: + await service.close() + asyncio.run(go()) def test_a_bitrate_ceiling_bounds_the_size_of_an_encoded_frame_sequence(tmp_path): diff --git a/tests/toolTaskText.test.ts b/tests/toolTaskText.test.ts index 29e5c2f54..711b075e1 100644 --- a/tests/toolTaskText.test.ts +++ b/tests/toolTaskText.test.ts @@ -54,8 +54,8 @@ test("tool task errors never leak persisted Chinese", () => { ], [ "tool_structure_reference_misaligned", - /different frame counts/, - /帧数不一致/, + /different number of frames than the video/, + /帧数与视频不一致/, ], ] as const) { assert.match(toolTaskError("后端文案已更新", undefined, { code })!, english);