diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index d826de4e3..c3ff3339b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -82,6 +82,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_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 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 ed656a50b..2bc75a5e4 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -89,6 +89,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. +**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. ## Make your first short film diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 277a4096b..6f3498498 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -76,6 +76,8 @@ HTTP 400。 使用视频的 **深度动作捕捉** 时,添加视频模型并选择 **vLLM-Omni 深度接口** 协议,例如用 `vllm serve --omni` 部署的 `depth-anything/Video-Depth-Anything-Small`。该工具把不超过 30 秒的视频逐帧转换为 480P 或 720P 的灰度深度视频,近处亮、远处暗,可作为动作和结构参考。深度模型不参与视频生成。 +**结构参考** 把一段不超过 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))。 + 在设置的“通用”页中可切换主题、调整去除水印选项。水印设置仅影响后续生成的内容,实际效果取决于模型服务是否支持。 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/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/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index 4db1eb96a..eb6c48d79 100644 --- a/packages/core/src/opendirector/application/creation_media_publication.py +++ b/packages/core/src/opendirector/application/creation_media_publication.py @@ -59,7 +59,7 @@ def publish_media(service, data, payload, *, staged=frozenset()): 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-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 b41173623..96ef36195 100644 --- a/packages/core/src/opendirector/application/tool_operations.py +++ b/packages/core/src/opendirector/application/tool_operations.py @@ -17,7 +17,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, + structure_reference, subtitle_erasure, video_edit, video_matting, video_upscale, ) # Editor previews and tool tasks import this helper from the catalog module. @@ -111,4 +111,7 @@ def _preset_select(): note='本地处理:保留内容视频在遮罩白色区域内的画面,其余变黑;可把遮罩内的明暗拉伸到完整范围(适合人物深度控制视频)。'), ToolSpec('video-depth-capture', ('video',), _needs('video.motion_capture'), depth_capture, 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 6cff2d032..827e8264b 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.structure_reference import write_structure_reference def _source_video(ctx: ToolContext) -> Source: @@ -242,6 +243,50 @@ async def depth_capture(ctx: ToolContext): data = await ctx.depth(clip.read_bytes()) return [Output('video', data, 'mp4', f'深度动作捕捉 {resolution}')] +STRUCTURE_REFERENCE_CRF = 20 + +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') + 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_structure_reference_duration') + if info['duration'] * info['fps'] > DEPTH_MAX_FRAMES: + 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 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) + 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/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/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 95c33fffb..99d7d0ba3 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-compress', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] + 'video-mask-composite', 'video-compress', '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/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index e882b0171..31ce5de9a 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -952,7 +952,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/processing.py b/packages/core/src/opendirector/media/processing.py index 2e461537b..2deaf0930 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -253,6 +253,19 @@ 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 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() @@ -261,10 +274,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) -> 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', '12', '-movflags', '+faststart', str(out)]) + '-c:v', 'libx264', '-preset', 'veryfast', '-crf', str(crf), *ceiling, '-movflags', '+faststart', str(out)]) return out.read_bytes() diff --git a/packages/core/src/opendirector/media/structure_reference.py b/packages/core/src/opendirector/media/structure_reference.py new file mode 100644 index 000000000..105f17ef0 --- /dev/null +++ b/packages/core/src/opendirector/media/structure_reference.py @@ -0,0 +1,71 @@ +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 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) + 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_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) + 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])] + 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/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 2bbc75b81..5b50d0365 100644 --- a/src/canvas/NodeSelectionToolbar.tsx +++ b/src/canvas/NodeSelectionToolbar.tsx @@ -453,6 +453,11 @@ export function NodeSelectionToolbar({ t("canvas.selection.depthCapture"), "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 ac24950f6..551ee7eb6 100644 --- a/src/canvas/VideoActionEditor.tsx +++ b/src/canvas/VideoActionEditor.tsx @@ -794,6 +794,13 @@ function VideoActionSession({ label: "tools.videoEditor.prompt.mattingLabel", placeholder: "tools.videoEditor.prompt.mattingPlaceholder", } + : tool === "video-structure-reference" + ? { + key: "prompt", + label: "tools.videoEditor.prompt.structureReferenceLabel", + placeholder: + "tools.videoEditor.prompt.structureReferencePlaceholder", + } : tool === "audio-separation" && parameters.mode === "description" ? { key: "description", @@ -1248,6 +1255,20 @@ function VideoActionSession({ ["480P", "480P"], ["720P", "720P"], ])} + {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", [ [30, "30 FPS"], diff --git a/src/canvas/toolCatalog.ts b/src/canvas/toolCatalog.ts index 3f3626cb5..29afe415b 100644 --- a/src/canvas/toolCatalog.ts +++ b/src/canvas/toolCatalog.ts @@ -36,6 +36,7 @@ export type CanvasToolId = | "video-crop" | "video-translation" | "video-mask-composite" + | "video-structure-reference" | "extract-audio" | "audio-separation" | "video-trim" @@ -451,6 +452,13 @@ export const CANVAS_TOOLS: readonly CanvasToolDefinition[] = [ [choice("resolution", "清晰度", ["480P", "720P"])], { category: "video", sources: ["video"], parameterCoverage: "entry-only" }, ), + tool( + "video-structure-reference", + "结构参考", + "去除外观,只保留原片的动作、时序、机位和场景结构,作为以相同动作、节奏和机位重新生成视频的参考:场景为灰色浮雕,跟踪到的对象各用一种纯色。输出 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 0c73d8f63..4c6bb979f 100644 --- a/src/canvas/toolTaskText.ts +++ b/src/canvas/toolTaskText.ts @@ -18,6 +18,12 @@ const CODE: Record = { video_compression_source: "errors.tools.error.compressionSource", tool_concept_translation: "errors.tools.error.conceptTranslation", tool_no_video_match: "errors.tools.error.noVideoMatch", + 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,6 +45,7 @@ const PHASE: Record = { 正在整理视频: "errors.tools.phase.organizeVideo", 正在合成抠像视频: "errors.tools.phase.matteVideo", 正在估计每一帧的深度: "errors.tools.phase.depth", + 正在渲染结构参考: "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 6c548fde8..a4a9b26cc 100644 --- a/src/canvas/toolText.ts +++ b/src/canvas/toolText.ts @@ -160,6 +160,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", + "结构参考": "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 6ca48df27..17558a992 100644 --- a/src/canvas/videoActionRuntime.ts +++ b/src/canvas/videoActionRuntime.ts @@ -114,6 +114,8 @@ export function initialVideoActionParameters( return { resolution: "4K" }; case "video-depth-capture": return { resolution: "480P" }; + case "video-structure-reference": + return { resolution: "480P", prompt: "" }; case "video-frame-interpolation": return { fps: 30 }; case "video-matting": @@ -144,6 +146,10 @@ export function videoActionInputError( > = { "video-upscale": { key: "resolution", values: ["2K", "4K"] }, "video-depth-capture": { 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", @@ -189,6 +195,11 @@ export function videoActionInputError( (!Number.isFinite(duration) || duration <= 0 || duration > 30) ) return tNow("errors.videoAction.depthDuration"); + if ( + tool === "video-structure-reference" && + (!Number.isFinite(duration) || duration <= 0 || duration > 30) + ) + 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 90c059d80..961ce6f44 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -9634,6 +9634,7 @@ "video-translation", "video-mask-composite", "video-compress", + "video-structure-reference", "extract-audio", "audio-separation", "video-trim", @@ -29821,6 +29822,7 @@ "video-translation", "video-mask-composite", "video-compress", + "video-structure-reference", "extract-audio", "audio-separation", "video-trim", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 5bc0d437d..4417d9b42 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -953,7 +953,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-compress" | "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-compress" | "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>; @@ -2991,7 +2991,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-compress" | "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-compress" | "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 7bb3bf744..54745aeec 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.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 2858c5028..9a380ec07 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.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", @@ -336,6 +337,12 @@ 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.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 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": @@ -458,6 +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.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 f02119df9..35e0c9d8f 100644 --- a/src/i18n/messages/en-US/tools.ts +++ b/src/i18n/messages/en-US/tools.ts @@ -234,6 +234,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.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": "e.g. rain, footsteps, or voices in the scene…", @@ -278,6 +281,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.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 b813463fc..53d0a90ee 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.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 0fdf760f9..c3a461f0b 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.structureReference": "正在渲染结构参考", "errors.tools.phase.separateAudio": "正在分离音轨", "errors.tools.phase.upscaleVideo": "正在放大视频", "errors.tools.phase.interpolate": "正在补帧到 {fps} fps", @@ -258,6 +259,12 @@ export const errors = { "errors.tools.phase.generic": "正在处理素材…", "errors.tools.error.interrupted": "服务重启,任务已中断,请重新提交。", "errors.tools.error.cancelled": "已取消。", + "errors.tools.error.structureReferenceDuration": + "结构参考需要不超过 30 秒的素材,请先裁剪视频。", + "errors.tools.error.structureReferenceFrames": + "结构参考单次最多处理 2048 帧,请先裁剪视频或降低帧率。", + "errors.tools.error.structureReferenceMisaligned": + "跟踪或深度结果的帧数与视频不一致,无法逐帧对齐,请重试。", "errors.tools.error.failed": "工具执行出错,请检查素材和参数后重试。", "errors.tools.error.resultProcessing": "生成结果处理失败,请检查服务协议;不会自动重新提交。", @@ -354,6 +361,8 @@ export const errors = { "errors.videoAction.minDuration": "视频编辑需要 4–30 秒的素材。", "errors.videoAction.maskSource": "请选择画布上的遮罩视频。", "errors.videoAction.depthDuration": "深度动作捕捉需要不超过 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 4b7edef47..1b0c87415 100644 --- a/src/i18n/messages/zh-CN/tools.ts +++ b/src/i18n/messages/zh-CN/tools.ts @@ -218,6 +218,9 @@ export const tools = { "tools.videoEditor.prompt.mattingLabel": "抠像对象", "tools.videoEditor.prompt.mattingPlaceholder": "默认抠出人物;可写多个对象,用逗号分隔,如:人物,狗", + "tools.videoEditor.prompt.structureReferenceLabel": "着色对象", + "tools.videoEditor.prompt.structureReferencePlaceholder": + "默认给人物着色;可写多个对象,用逗号分隔,如:人物,狗", "tools.videoEditor.prompt.soundLabel": "声音描述", "tools.videoEditor.prompt.soundPlaceholder": "例如:雨声、脚步声或画面中的人声…", @@ -260,6 +263,9 @@ export const tools = { "选框默认覆盖底部字幕带,可拖动到字幕实际位置;声音保持不变。", "tools.videoEditor.upscale.resolution": "输出清晰度", "tools.videoEditor.depth.resolution": "输出清晰度", + "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_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_creation_media_publication.py b/tests/test_creation_media_publication.py index 4d27ef00c..b9a8bd6d6 100644 --- a/tests/test_creation_media_publication.py +++ b/tests/test_creation_media_publication.py @@ -13,6 +13,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 @@ -206,3 +207,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_structure_reference_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(), '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='Structure reference')], + document=dict(id=uuid4(), projectId=pid, kind='media_edit', data=dict( + 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) + 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..d7fbd5f16 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_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 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) == '更新后的中文' + + def test_chinese_and_english_messages_do_not_mix() -> None: assert ( localized_error( diff --git a/tests/test_structure_reference.py b/tests/test_structure_reference.py new file mode 100644 index 000000000..b78725f22 --- /dev/null +++ b/tests/test_structure_reference.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.structure_reference import SCENE, SUBJECTS, structure_frame, subject_colors, write_structure_reference + +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 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))) + 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 + 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,), ())) + 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_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 = 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] + 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 = 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 9dae12a07..c148ecc08 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -2,21 +2,26 @@ import base64 import io import json +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 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 +840,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): @@ -876,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' @@ -898,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], @@ -974,6 +980,242 @@ def test_depth_capture_rejects_long_clips_and_unknown_resolutions_before_calling assert log == [] +def configure_structure_reference(store): + configs = configure(store, SAM3) + configs.save(*VDA, '', connection_type='self_hosted', protocol='vllm_omni_depth') + return configs + + +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 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() + 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 / 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 structure_reference(store, configs, server, project_id, session, source, **parameters): + return run(store, configs, httpx.MockTransport(server), project_id, session, + {'tool': 'video-structure-reference', 'sourceAssetIds': [source], 'parameters': parameters}) + + +@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}) + + 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_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-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_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 = [], [] + 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' + 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]): + 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_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', + '-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 = [] + 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_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_structure_reference(store) + prompts, depths = [], [] + server = structure_reference_server(prompts, depths, tmp_path, empty=True) + for parameters in ({}, {'prompt': ' ,, '}): + 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 = 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_structure_reference_duration', '不超过 30 秒'), + ((25, '90'), {}, 'tool_structure_reference_frames', '最多处理 2048 帧'), + ((1, '24'), {'resolution': '1080P'}, 'invalid_input', '不在可选范围内'), + ((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_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), + '-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_structure_reference(store) + configs.save(*CHAT, '', connection_type='self_hosted', protocol='openai') + 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(('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, **{f'extra_{service}_frames': extra}) + task = structure_reference(store, configure_structure_reference(store), server, project_id, session, source) + 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 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): + 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): """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..d11f2a6b9 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-structure-reference", [video.nodeId], { + resolution, + prompt: "人物,狗", + }), + [video], + confirmed, + ), + [], + ); + assert.ok( + validateToolTask( + createCanvasToolTask("video-structure-reference", [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..711b075e1 100644 --- a/tests/toolTaskText.test.ts +++ b/tests/toolTaskText.test.ts @@ -15,6 +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 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)"); @@ -37,6 +41,28 @@ test("tool task errors never leak persisted Chinese", () => { toolTaskError("工具执行出错,请检查素材和参数后重试。"), "The tool failed. Check the media and parameters and try again.", ); + for (const [code, english, chinese] of [ + [ + "tool_structure_reference_duration", + /no longer than 30 seconds/, + /不超过 30 秒/, + ], + [ + "tool_structure_reference_frames", + /at most 2048 frames/, + /最多处理 2048 帧/, + ], + [ + "tool_structure_reference_misaligned", + /different number of frames than the video/, + /帧数与视频不一致/, + ], + ] 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", diff --git a/tests/videoActionRuntime.test.ts b/tests/videoActionRuntime.test.ts index 422a71ece..783b7384e 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-structure-reference", "video-frame-interpolation", "video-matting", "audio-separation", @@ -120,6 +121,24 @@ test("AI video controls reject incomplete descriptions, invalid restored choices )!, /30/, ); + assert.match( + videoActionInputError( + "video-structure-reference", + { resolution: "720P" }, + 31, + range, + )!, + /结构参考.*30/, + ); + assert.match( + videoActionInputError( + "video-structure-reference", + { resolution: "1080P" }, + 6, + range, + )!, + /选项/, + ); assert.match( videoActionInputError("video-frame-interpolation", { fps: 48 }, 6, range)!, /选项/,