diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 439b6b3bb..94914358a 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -85,6 +85,10 @@ '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.', + '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_people': 'Video blockout handles at most 8,192 person-frames (each person on each frame counts once) at a time. Trim the video or use a shot with fewer people.', + 'tool_blockout_misaligned': 'Tracking and the video differ in frame count or picture size, so they cannot be aligned frame by frame. Re-export the video as a constant-frame-rate H.264 MP4 and process that.', '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/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index a095e33f5..889dde41a 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -29,7 +29,7 @@ class UrlSource(Model): class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' - protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] | None = None + protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] | None = None authMode: Literal['none', 'bearer'] | None = None proxyMode: Literal['system', 'direct'] | None = None capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None) diff --git a/docs/architecture/capability-contract.md b/docs/architecture/capability-contract.md index 5fdce95c1..40c74c36b 100644 --- a/docs/architecture/capability-contract.md +++ b/docs/architecture/capability-contract.md @@ -94,7 +94,7 @@ One boundary is left, and it now cuts the other way: a route this table cannot p ## Routes without an operation -`/v1/images/segmentations`, `/v1/videos/segmentations` and `/v1/videos/depth` are registered endpoints that no operation owns; upstream's docs state that "segmentation and depth estimation do not acquire one of these operations merely by being present in a registry" (`docs/serving/capabilities.md:41-43`). `image.segment`, `video.matting` and `video.motion_capture` therefore stay `unknown` with `no_upstream_profile` — the endpoint does not publish the ability, so it cannot be judged, and it must never read as `missing`. `audio.score` is `no_upstream_operation`; `image.cutout` is `parameter_only` (a request field of a published operation, granted per adapter rather than per profile); `audio.separate` is `no_local_adapter`. None of these six ids is a value of `OPERATION_PROFILES`, so `unknown` falls out of "no evidence" rather than a special case. +`/v1/images/segmentations`, `/v1/videos/segmentations` and `/v1/videos/depth` are registered endpoints that no operation owns; upstream's docs state that "segmentation and depth estimation do not acquire one of these operations merely by being present in a registry" (`docs/serving/capabilities.md:41-43`). `/v1/videos/bodies` (3D body reconstruction) is likewise an endpoint without an operation. `image.segment`, `video.matting`, `video.motion_capture`, `video.camera` (cameras and depth from `/v1/videos/depth`) and `video.body_capture` therefore stay `unknown` with `no_upstream_profile` — the endpoint does not publish the ability, so it cannot be judged, and it must never read as `missing`. `audio.score` is `no_upstream_operation`; `image.cutout` is `parameter_only` (a request field of a published operation, granted per adapter rather than per profile); `audio.separate` is `no_local_adapter`. None of these eight ids is a value of `OPERATION_PROFILES`, so `unknown` falls out of "no evidence" rather than a special case. ## ASR: an upstream gap, not a missing row diff --git a/docs/guides/cli.md b/docs/guides/cli.md index ec0b02020..3ace1e3e1 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -263,6 +263,22 @@ opendirector video structure-reference-task TASK_ID opendirector video structure-reference-task TASK_ID --action publish ``` +## Video blockout / 视频脱模 + +**Video blockout** rebuilds a clip of up to 30 seconds in 3D and renders it from the source camera: a gray scene and one solid-colored body model per person, with the source's frame rate and size, plus a layout file with the cameras, the scale and each person's body parameters. A constant-frame-rate clip keeps its frame count; a variable-frame-rate clip is resampled at the rate its frame timestamps show, so the blockout lines up with the source by time, and the layout lists which source frame each output frame shows. It needs a video tracking model (SAM 3), Depth Anything 3 on the vLLM-Omni depth protocol and SAM 3D Body on the vLLM-Omni 3D body protocol. The task keeps the original; when it succeeds, publishing places the blockout video and the layout file on new canvas nodes at the default position. Unlike a run from the canvas toolbar, these nodes are not linked to the source node. + +**视频脱模**把不超过 30 秒的视频在三维中重建,并按原片机位渲染:灰色场景,每个人物一个固定颜色的人体模型,帧率和尺寸与原片一致,另附一个记录相机、比例和每个人物人体参数的布局文件。恒定帧率的素材帧数也一致;可变帧率的素材按其帧时间戳体现的帧率重采样,白模按时间与原片对齐,布局会列出每个输出帧显示的原片帧号。需要接入视频跟踪模型(SAM 3)、vLLM-Omni 深度接口上的 Depth Anything 3 和 vLLM-Omni 三维人体接口上的 SAM 3D Body。任务保留原片;成功后发布,会把白模视频和布局文件放到默认位置的新画布节点上。与从画布工具栏运行不同,这些节点不会与来源节点相连。 + +From the CLI, supply the source asset ID and a stable operation ID, which is also the task ID. Query the task, request cancellation with `--action cancel`, or publish its successful outputs with `--action publish`. Agents use the `video_blockout` and `blockout_task` tools with the same fields. + +在 CLI 中传入源素材 ID 和固定的操作 ID,操作 ID 同时也是任务 ID。可以查询任务,用 `--action cancel` 请求取消,或用 `--action publish` 发布成功的结果。Agent 使用字段相同的 `video_blockout` 和 `blockout_task` 工具。 + +```sh +opendirector video blockout --asset-id ASSET_ID --operation-id TASK_ID +opendirector video blockout-task TASK_ID +opendirector video blockout-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 d0516b6d1..8a92a227c 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -91,6 +91,8 @@ To use **Depth motion capture** on a video, add a video model with the **vLLM-Om **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)). +**Video blockout** rebuilds a clip of up to 30 seconds in 3D and renders it from the source camera: the scene becomes gray geometry and each person a body model in one fixed color (the first person red), with the same frame rate and size as the source and no sound. The frame rate is read from the gaps between the source's frame timestamps, not from the container's own guess. A constant-frame-rate clip keeps its frame count; a variable-frame-rate clip is resampled at that rate, so the blockout lines up with the source by time. It needs three models: a segmentation model that tracks through video (SAM 3), **Depth Anything 3** on the **vLLM-Omni depth** protocol (for example `depth-anything/DA3-LARGE-1.1`; it estimates the camera of every frame and the scene's depth), and **SAM 3D Body** on the **vLLM-Omni 3D body** protocol (for example `jetjodh/sam-3d-body-dinov3`; it reconstructs each tracked person's pose in meters). A Depth Anything 3 configuration serves video blockout only, not depth motion capture. The scene is built from the estimated depth of up to eight frames with the people, and what they hold, removed, so it stays fixed while the camera moves; areas the depth model is least sure of, such as sky and distant foliage, are left as background. Depth Anything 3 measures depth in a unit of its own, so each person's depth is matched to the depth of their own pixels and the scale in meters is recorded. When no person is tracked there is nothing to set the scale, and the layout says so (`unit` is `depth_model_unit`). Next to the video, the tool saves a layout file (named after the source, `-blockout-layout.json`) with every frame's camera, the scale, and each person's position and body parameters per frame. Its frame `i` is at `i / fps` seconds of the source; `timeline` records the source's own frame count, whether any output frame shows another source frame than its own number, and in that case `sourceFrameOf`, the source frame each output frame shows. The layout's intrinsics and boxes are in the pixels of its own `width` and `height`; for a source above 720 pixels on the short edge that is the working size, smaller than the video. A clip may hold at most 8,192 person-frames (each person on each frame counts once; for example 4 people over 2,048 frames). Bodies that the tracker does not follow, objects other than people, and limbs hidden throughout are not reconstructed, and the layout cannot be edited on the canvas yet. Use the blockout as a reference video so new footage follows the source's motion, timing and camera. Agents and the CLI run the same task with the `video_blockout` and `blockout_task` tools or `opendirector video blockout` and `video blockout-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 88b538b6a..e45221103 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -78,6 +78,8 @@ HTTP 400。 **结构参考** 把一段不超过 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))。 +**视频脱模** 把一段不超过 30 秒的视频在三维中重建,并按原片机位逐帧渲染:场景为灰色模型,每个人物为一个固定颜色的人体模型(第一个人物为红色),帧率和尺寸与原片一致,没有声音。帧率由原片相邻帧时间戳的间隔得出,而不是容器自报的帧率。恒定帧率的素材帧数也一致;可变帧率的素材按这个帧率重采样,白模按时间与原片对齐。它需要三个模型:可跟踪视频的分割模型(SAM 3)、在 **vLLM-Omni 深度接口** 上部署的 **Depth Anything 3**(如 `depth-anything/DA3-LARGE-1.1`,估计每一帧的相机和场景深度),以及在 **vLLM-Omni 三维人体接口** 上部署的 **SAM 3D Body**(如 `jetjodh/sam-3d-body-dinov3`,以米为单位重建每个被跟踪人物的姿态)。Depth Anything 3 的配置只用于视频脱模,不用于深度动作捕捉。场景由最多八帧去掉人物及其手持物后的深度构成,因此镜头移动时场景保持不动;深度模型最不确定的区域(如天空和远处的树丛)留作背景。Depth Anything 3 的深度单位不固定,因此每个人物的深度会与其自身像素的深度对齐,并记录换算成米的比例。没有跟踪到人物时无法确定比例,布局会注明(`unit` 为 `depth_model_unit`)。工具会在视频旁另存一个布局文件(以素材命名,`<素材名>-blockout-layout.json`),记录每一帧的相机、比例,以及每个人物逐帧的位置和人体参数。布局的第 `i` 帧对应原片第 `i / fps` 秒;`timeline` 记录原片自身的帧数、是否有输出帧显示的不是同号的原片帧,以及在这种情况下每个输出帧显示的原片帧号(`sourceFrameOf`)。布局中的内参和人物框以布局自身的 `width`、`height` 为像素单位;短边超过 720 像素的素材会按工作尺寸处理,这个尺寸小于视频尺寸。一段素材最多包含 8192 个人物帧(每帧每人计一次,例如 4 个人、2048 帧)。未被跟踪的人物、人物以外的物体和始终被遮挡的肢体不会重建,布局暂不能在画布上编辑。可将白模视频作为参考视频,让新画面沿用原片的动作、节奏和机位。Agent 和 CLI 通过 `video_blockout`、`blockout_task` 工具或 `opendirector video blockout`、`video blockout-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 8db4840ea..43cfb1456 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -370,6 +370,19 @@ 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_blockout', + 'Start a 3D blockout of a video (gray scene and one colored body model per person, rendered from the source camera, ' + 'plus a layout file) without overwriting the source. Needs video tracking, Depth Anything 3 and SAM 3D Body models; ' + 'clips up to 30 seconds. Returns a durable task; inspect with blockout_task and publish explicitly after success.', + {'type': 'object', 'properties': {'taskId': {'type': 'string', 'format': 'uuid'}, + 'sourceAssetId': {'type': 'string', 'format': 'uuid'}}, + 'required': ['taskId', 'sourceAssetId'], 'additionalProperties': False})) + result.append(tool_schema('blockout_task', + 'Inspect, request cancellation, or publish a successful video blockout (its video and layout file) as new canvas nodes. ' + '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.', @@ -419,7 +432,8 @@ async def cli_prompt_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.')} + 'structure_reference_task': ('video-structure-reference', 'Select a structure reference task.'), + 'blockout_task': ('video-blockout', 'Select a video blockout task.')} class AgentTools: @@ -436,7 +450,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', 'video_structure_reference', *TASK_TOOLS}: + if name in {'video_compress', 'video_structure_reference', 'video_blockout', *TASK_TOOLS}: service = self.generation.tool_tasks task_id = str(UUID(arguments['taskId'])) pid = str(project_id) @@ -448,6 +462,9 @@ 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-structure-reference', sourceAssetIds=[str(UUID(arguments['sourceAssetId']))], parameters={'resolution': arguments['resolution'], 'prompt': arguments.get('subjects', '')}), session) + if name == 'video_blockout': + return await service.submit(pid, dict(id=task_id, tool='video-blockout', + sourceAssetIds=[str(UUID(arguments['sourceAssetId']))], parameters={}), session) tool, refusal = TASK_TOOLS[name] task = await asyncio.to_thread(service.get, pid, task_id) if task['tool'] != tool: diff --git a/packages/core/src/opendirector/application/creation_media_publication.py b/packages/core/src/opendirector/application/creation_media_publication.py index eb6c48d79..9c00acbe5 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', 'video-structure-reference'}: + 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', '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_context.py b/packages/core/src/opendirector/application/tool_context.py index 6fdce8f5b..cadb38222 100644 --- a/packages/core/src/opendirector/application/tool_context.py +++ b/packages/core/src/opendirector/application/tool_context.py @@ -11,8 +11,8 @@ from PIL import Image from opendirector.domain.capabilities import ( - ChatRequest, CutoutRequest, DepthRequest, ImageRequest, SegmentRequest, TrackRequest, - Tracks, VideoEditRequest, VideoRequest, + BodyCapture, BodyRequest, CameraRequest, CameraTrack, ChatRequest, CutoutRequest, DepthRequest, ImageRequest, + SegmentRequest, TrackRequest, Tracks, VideoEditRequest, VideoRequest, ) from opendirector.domain.projects import ProjectError from opendirector.media import processing as media @@ -45,7 +45,7 @@ class ToolContext: def __init__(self, *, sources, mask, boxes, parameters, image_model, video_model, progress, video_submitted=None, cutout_model=None, edit_model=None, edit_seconds=(4.0, 15.0), chat_model=None, segment_model=None, track_model=None, edit_keeps_layout=True, annotation=None, edit_max_images=1, segment_available=False, depth_model=None, - native_mask=False, video_execution=None): + native_mask=False, video_execution=None, camera_model=None, body_model=None): self.sources: list[Source] = sources self.mask: bytes | None = mask self.annotation: bytes | None = annotation @@ -57,6 +57,7 @@ def __init__(self, *, sources, mask, boxes, parameters, image_model, video_model self.parameters: dict = parameters self._image, self._video, self._cutout, self._edit = image_model, video_model, cutout_model, edit_model self._segment, self._track, self._depth = segment_model, track_model, depth_model + self._camera, self._bodies = camera_model, body_model # img2img models redraw in place by strength; instruction editors recompose the picture. self.edit_keeps_layout = edit_keeps_layout # Shortest and longest clip one redraw accepts; longer sources are processed piecewise. @@ -119,6 +120,12 @@ async def depth(self, clip: bytes) -> bytes: """A grayscale depth video of clip at its size and rate; near is bright.""" return (await self._depth(DepthRequest(video=clip))).data + async def camera(self, clip: bytes, frames: int) -> CameraTrack: + return await self._camera(CameraRequest(video=clip, frames=frames)) + + async def bodies(self, clip: bytes, tracks: Tracks, intrinsics) -> BodyCapture: + return await self._bodies(BodyRequest(video=clip, tracks=tracks, intrinsics=intrinsics)) + async def concepts(self, text: str, default: tuple[str, ...]) -> list[tuple[str, str]]: """(English concept, label) pairs from a comma-separated description; segmentation models read English.""" parts = list(dict.fromkeys(item.strip() for item in re.split(r'[,,、;;\n]+', text) if item.strip())) diff --git a/packages/core/src/opendirector/application/tool_operations.py b/packages/core/src/opendirector/application/tool_operations.py index 96ef36195..303cdde80 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, - structure_reference, subtitle_erasure, video_edit, video_matting, video_upscale, + structure_reference, subtitle_erasure, video_blockout, video_edit, video_matting, video_upscale, ) # Editor previews and tool tasks import this helper from the catalog module. @@ -114,4 +114,7 @@ def _preset_select(): ToolSpec('video-structure-reference', ('video',), _needs('video.matting', 'video.motion_capture'), structure_reference, note='去除外观,只保留原片的动作、时序、机位和场景结构,作为以相同动作、节奏和机位重新生成视频的参考:' '场景渲染为灰色浮雕,跟踪到的对象(默认人物)各用一种纯色;输出与原片逐帧对齐的无声结构参考视频,最长 30 秒。'), + ToolSpec('video-blockout', ('video',), _needs('video.matting', 'video.camera', 'video.body_capture'), video_blockout, + note='在三维中重建原片的机位、场景和人物:场景为灰色白模,每个人物为一个固定颜色的人体模型,按原机位逐帧渲染;' + '输出与原片帧率和尺寸一致、按时间对齐的无声视频(恒定帧率素材帧数也一致),并保存相机、尺度和人体参数布局;最长 30 秒。'), ]} diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 4b139324b..39b4ecffb 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -514,6 +514,14 @@ async def depth_model(request): config, adapter = frozen_model('video.motion_capture') return await self._model_call(task, 'video.motion_capture', lambda _: adapter.depth(config, request)) + async def camera_model(request): + config, adapter = frozen_model('video.camera') + return await self._model_call(task, 'video.camera', lambda _: adapter.camera(config, request)) + + async def body_model(request): + config, adapter = frozen_model('video.body_capture') + return await self._model_call(task, 'video.body_capture', lambda _: adapter.bodies(config, request)) + keeps_layout, edit_max_images = True, 1 if 'image.edit' in task['requires']: _, painter = frozen_model('image.edit') @@ -536,7 +544,8 @@ async def chat_model(request): segment_model=segment_model, track_model=track_model, edit_keeps_layout=keeps_layout, annotation=annotation, edit_max_images=edit_max_images, native_mask=task.get('imageExecutionPolicy') is not None and task.get('imageExecution', {}).get('mode') == 'native_mask', - segment_available='image.segment' in task['requires'], depth_model=depth_model) + segment_available='image.segment' in task['requires'], depth_model=depth_model, + camera_model=camera_model, body_model=body_model) outputs = await spec.recipe(context) # Preserve already-produced bytes even if cancellation arrives # during registration. Each asset is checkpointed independently. diff --git a/packages/core/src/opendirector/application/tool_video_recipes.py b/packages/core/src/opendirector/application/tool_video_recipes.py index 827e8264b..30601d929 100644 --- a/packages/core/src/opendirector/application/tool_video_recipes.py +++ b/packages/core/src/opendirector/application/tool_video_recipes.py @@ -1,11 +1,13 @@ """Video recipes over local media steps and video-model capabilities.""" import math +from pathlib import PurePath from PIL import Image, ImageChops, ImageFilter from opendirector.application.tool_context import Output, Source, ToolContext, ToolInputError from opendirector.domain.capabilities import EditMask, Tracks from opendirector.domain.projects import ProjectError +from opendirector.media import blockout from opendirector.media import processing as media from opendirector.media.async_work import blocking from opendirector.media.structure_reference import write_structure_reference @@ -287,6 +289,72 @@ async def structure_reference(ctx: ToolContext): crf=STRUCTURE_REFERENCE_CRF, max_megabits=STRUCTURE_REFERENCE_MAX_MEGABITS) return [Output('video', data, 'mp4', f'结构参考 {resolution}')] +BLOCKOUT_SHORT_EDGE = 720 + +BLOCKOUT_CRF = 20 + +BLOCKOUT_MAX_MEGABITS = 8 + +BLOCKOUT_MAX_PEOPLE_FRAMES = 8192 + +BLOCKOUT_BODIES_PER_REQUEST = 256 + +BLOCKOUT_FRAMES = f'视频脱模单次最多处理 {DEPTH_MAX_FRAMES} 帧,请先裁剪视频或降低帧率。' + +BLOCKOUT_MISALIGNED = '跟踪结果与视频的帧数或画面尺寸不一致,无法逐帧对齐。请将视频重新导出为恒定帧率的 H.264 MP4 后再处理。' + +async def video_blockout(ctx: ToolContext): + source = _source_video(ctx) + 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') + times = await blocking(media.frame_times, raw) + rate, regular = media.nominal_rate(times, info['fps']) + if info['duration'] * rate > DEPTH_MAX_FRAMES: + raise ProjectError(BLOCKOUT_FRAMES, 422, code='tool_blockout_frames') + await ctx.progress('正在整理视频') + width, height = _depth_size(info['width'], info['height'], BLOCKOUT_SHORT_EDGE) + path = await blocking(media.constant_rate_picture, raw, work.path / 'clip.mp4', width=width, height=height, fps=rate, + regular=regular) + clip, frames = path.read_bytes(), await blocking(media.frame_count, path) + if frames > DEPTH_MAX_FRAMES: + raise ProjectError(BLOCKOUT_FRAMES, 422, code='tool_blockout_frames') + source_frames = len(times) + shown = list(range(source_frames)) if regular else await blocking(media.source_frame_map, raw, fps=rate) + if len(shown) != frames: + raise ProjectError(BLOCKOUT_MISALIGNED, 502, code='tool_blockout_misaligned') + await ctx.progress('正在跟踪人物') + tracks = await blocking(blockout.people_tracks, await ctx.track(clip, ('person',))) + if sum(len(people) for people in tracks.frames) > BLOCKOUT_MAX_PEOPLE_FRAMES: + raise ProjectError(f'视频脱模单次最多处理 {BLOCKOUT_MAX_PEOPLE_FRAMES} 个人物帧(每帧每人计一次),请缩短视频或换用人物更少的镜头。', + 422, code='tool_blockout_people') + if (tracks.width, tracks.height) != (width, height) or len(tracks.frames) != frames: + raise ProjectError(BLOCKOUT_MISALIGNED, 502, code='tool_blockout_misaligned') + await ctx.progress('正在估计相机和场景') + camera = await ctx.camera(clip, frames) + render = await blocking(blockout.BlockoutRender, tracks, camera, work.path / 'frames', fps=rate, source_frames=source_frames, + shown=shown) + camera, intrinsics = render.capture, render.intrinsics + await ctx.progress('正在重建三维人体') + for part in blockout.body_chunks(tracks, camera.frame_indices, BLOCKOUT_BODIES_PER_REQUEST): + if any(tracks.frames[frame] for frame in part): + await blocking(render.measure, await ctx.bodies(clip, blockout.only_frames(tracks, part), intrinsics)) + await blocking(render.settle) + await ctx.progress('正在渲染白模') + for part in blockout.body_chunks(tracks, range(frames), BLOCKOUT_BODIES_PER_REQUEST): + bodies = (await ctx.bodies(clip, blockout.only_frames(tracks, part), intrinsics) + if any(tracks.frames[frame] for frame in part) else None) + await blocking(render.draw, bodies, part) + del bodies + layout = await blocking(render.layout) + size = (info['width'] - info['width'] % 2, info['height'] - info['height'] % 2) + data = await blocking(media.encode_frames, str(work.path / 'frames' / '%05d.png'), rate, work.path / 'blockout.mp4', + crf=BLOCKOUT_CRF, max_megabits=BLOCKOUT_MAX_MEGABITS, size=size) + stem = PurePath(source.name).stem + return [Output('video', data, 'mp4', f'{stem}-blockout'), Output('file', layout, 'json', f'{stem}-blockout-layout')] + 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 1fc317c2a..f1b7da639 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -545,6 +545,26 @@ def structure_reference_task(ctx: typer.Context, task_id: Annotated[UUID, typer. tool_task_command(ctx, 'structure_reference_task', 'video-structure-reference', 'Select a structure reference task.', task_id, action) +@group("video").command("blockout", help="Rebuild one video as a 3D blockout in the background; keeps the original. Query the returned task ID.") +def video_blockout(ctx: typer.Context, asset_id: Annotated[UUID, typer.Option()], + operation_id: Annotated[UUID, typer.Option()]): + client = ctx.obj + client.command = ctx.command_path + if client.live: + value = client.call('video_blockout', dict(taskId=str(operation_id), sourceAssetId=str(asset_id)), identity=operation_id) + else: + client.open() + value = client.request('POST', client.path('/tool-tasks'), json=dict(id=str(operation_id), + tool='video-blockout', sourceAssetIds=[str(asset_id)], parameters={})) + emit(value) + + +@group("video").command("blockout-task", help="Query a video blockout task, request cancellation or publish its successful outputs.") +def blockout_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument()], + action: Annotated[Literal['get', 'cancel', 'publish'], typer.Option()] = 'get'): + tool_task_command(ctx, 'blockout_task', 'video-blockout', 'Select a video blockout 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 9e010b379..a3ea683f9 100644 --- a/packages/core/src/opendirector/domain/capabilities.py +++ b/packages/core/src/opendirector/domain/capabilities.py @@ -13,6 +13,7 @@ Capability = Literal[ 'text.chat', 'image.generate', 'image.edit', 'image.cutout', 'video.generate', 'video.first_frame', 'video.edit', 'audio.speech', 'audio.music', 'audio.score', 'image.segment', 'video.matting', 'video.motion_capture', + 'video.camera', 'video.body_capture', # Declared so operations can name what they lack; no current adapter offers it. 'audio.separate', ] @@ -32,6 +33,8 @@ 'video.matting': '视频抠像', 'audio.separate': '音轨分离', 'video.motion_capture': '深度动作捕捉', + 'video.camera': '相机与场景估计', + 'video.body_capture': '三维人体重建', } @@ -96,6 +99,7 @@ class Tracks: fps: float frames: tuple[tuple[tuple[int, ...], ...], ...] identities: tuple[tuple[int, ...], ...] = () + boxes: tuple[tuple[tuple[float, float, float, float], ...], ...] = () @dataclass(frozen=True) @@ -104,6 +108,38 @@ class DepthRequest: video: bytes +@dataclass(frozen=True) +class CameraRequest: + video: bytes + frames: int + + +@dataclass(frozen=True) +class CameraTrack: + model: str + width: int + height: int + frame_indices: tuple[int, ...] + intrinsics: tuple[tuple[tuple[float, ...], ...], ...] + extrinsics: tuple[tuple[tuple[float, ...], ...], ...] + maps: bytes + + +@dataclass(frozen=True) +class BodyRequest: + video: bytes + tracks: Tracks + intrinsics: tuple[tuple[tuple[float, ...], ...], ...] + + +@dataclass(frozen=True) +class BodyCapture: + model: str + keypoint_names: tuple[str, ...] + bodies: tuple[dict, ...] + meshes: tuple[bytes, ...] + + @dataclass(frozen=True) class VideoRequest: prompt: str diff --git a/packages/core/src/opendirector/domain/capability_contract.py b/packages/core/src/opendirector/domain/capability_contract.py index 5d6a3e5a0..b459dda0c 100644 --- a/packages/core/src/opendirector/domain/capability_contract.py +++ b/packages/core/src/opendirector/domain/capability_contract.py @@ -434,6 +434,8 @@ 'image.segment': NO_UPSTREAM_PROFILE, 'video.matting': NO_UPSTREAM_PROFILE, 'video.motion_capture': NO_UPSTREAM_PROFILE, + 'video.camera': NO_UPSTREAM_PROFILE, + 'video.body_capture': NO_UPSTREAM_PROFILE, # Upstream publishes no transcription operation at all. 'audio.score': NO_UPSTREAM_OPERATION, # Request field of an operation that does publish a profile. diff --git a/packages/core/src/opendirector/domain/capability_messages.py b/packages/core/src/opendirector/domain/capability_messages.py index 2e509a738..120ee7884 100644 --- a/packages/core/src/opendirector/domain/capability_messages.py +++ b/packages/core/src/opendirector/domain/capability_messages.py @@ -11,7 +11,8 @@ 'video.first_frame': 'first-frame video generation', 'video.edit': 'video inpainting', 'audio.speech': 'speech synthesis', 'audio.music': 'music generation', 'audio.score': 'music transcription', 'image.segment': 'image segmentation', 'video.matting': 'video matting', - 'video.motion_capture': 'depth motion capture', 'audio.separate': 'audio separation', + 'video.motion_capture': 'depth motion capture', 'video.camera': 'camera and scene estimation', + 'video.body_capture': '3D body reconstruction', 'audio.separate': 'audio separation', } diff --git a/packages/core/src/opendirector/domain/creation/editors.py b/packages/core/src/opendirector/domain/creation/editors.py index 99d7d0ba3..b97343050 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', 'video-structure-reference', 'extract-audio', 'audio-separation', 'video-trim', 'audio-trim', 'video-frame-capture', 'director-stage'] + 'video-mask-composite', 'video-compress', 'video-structure-reference', '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/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index b0877872f..89677c440 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -419,6 +419,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc raise ValueError('视觉分割模型仅用于选区、分割和抠像,请选择生成模型。') if model.inputRules.profile == 'vllm-omni-depth': raise ValueError('视频深度模型仅用于深度动作捕捉,请选择生成模型。') + if model.inputRules.profile == 'vllm-omni-bodies': + raise ValueError('三维人体模型仅用于视频脱模,请选择生成模型。') if model.inputRules.profile == 'vllm-omni-score': raise ValueError('扒谱模型仅用于参照音乐生成,请选择音乐生成模型。') written = (any(isinstance(part, PromptReference) or part.text.strip() for part in spec.promptContent) diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index cd72c26af..2cb59901f 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -13,7 +13,7 @@ from .base import Contract ModelKind = Literal['agent', 'image', 'video', 'audio', 'vision'] -Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] +Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] VideoMode = Literal['first_frame', 'reference', 'continuation', 'control'] ImageQuality = Literal['auto', 'low', 'medium', 'high'] Count = Annotated[int, Field(strict=True, ge=0)] @@ -144,7 +144,7 @@ def model_name(cls, value): @model_validator(mode='after') def connection(self): allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, + 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} if self.protocol not in allowed[self.kind]: raise ValueError('Protocol is incompatible with model category') diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index b5889807a..81c47e6ff 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -75,6 +75,9 @@ def _adapter_rules(config): # Video depth estimation service (Video Depth Anything), never a generator. rules.update(profile='vllm-omni-depth', allowedKinds=[], maxImages=0, videoModes=[]) return rules + if config.get('protocol') == 'vllm_omni_bodies': + rules.update(profile='vllm-omni-bodies', allowedKinds=[], maxImages=0, videoModes=[]) + return rules if config.get('protocol') == 'vllm_omni_score': # SheetSage2 transcription service: it turns a reference recording into # a score for music generation and never generates audio itself. diff --git a/packages/core/src/opendirector/domain/model_connection.py b/packages/core/src/opendirector/domain/model_connection.py index 0e7ffd3f0..e94ecca57 100644 --- a/packages/core/src/opendirector/domain/model_connection.py +++ b/packages/core/src/opendirector/domain/model_connection.py @@ -10,7 +10,7 @@ def connection_fields(kind, connection_type='api', protocol=None, auth_mode=None protocol = protocol or ('openai' if kind == 'agent' or connection_type == 'self_hosted' and kind not in {'video', 'vision'} else 'vllm_omni' if connection_type == 'self_hosted' else 'volcengine') allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, + 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} auth_mode = auth_mode or ('none' if connection_type == 'self_hosted' else 'bearer') proxy_mode = proxy_mode if proxy_mode is not None else 'system' diff --git a/packages/core/src/opendirector/domain/video_capabilities.py b/packages/core/src/opendirector/domain/video_capabilities.py index ea9aac979..ac9ae1170 100644 --- a/packages/core/src/opendirector/domain/video_capabilities.py +++ b/packages/core/src/opendirector/domain/video_capabilities.py @@ -139,6 +139,8 @@ def check_video_config(kind, protocol, adapter, capabilities): raise ProjectError('视觉分割接口不支持视频生成输出规格。') if protocol == 'vllm_omni_depth' and (adapter != 'auto' or capabilities is not None): raise ProjectError('视频深度接口不支持视频生成输出规格。') + if protocol == 'vllm_omni_bodies' and (adapter != 'auto' or capabilities is not None): + raise ProjectError('三维人体接口不支持视频生成输出规格。') if adapter != 'auto' and protocol != 'vllm_omni': raise ProjectError('所选视频适配方式需要 /videos 接口协议。') if capabilities is not None: diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index 7f6f6a274..25aa73823 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -11,17 +11,19 @@ import json import math import re +import zipfile from io import BytesIO from urllib.parse import quote, urlsplit import httpx +import numpy as np from PIL import Image, UnidentifiedImageError from opendirector.domain.assets import MAX_ASSET_BYTES from opendirector.domain.capability_messages import constraint_rejection -from opendirector.domain.capabilities import (ChatRequest, CutoutRequest, DepthRequest, EditMask, ImageRequest, MediaResult, MusicRequest, - ScoreRequest, Segment, SegmentRequest, SpeechRequest, TrackRequest, Tracks, VideoEditRequest, - VideoRequest) +from opendirector.domain.capabilities import (BodyCapture, BodyRequest, CameraRequest, CameraTrack, ChatRequest, CutoutRequest, + DepthRequest, EditMask, ImageRequest, MediaResult, MusicRequest, ScoreRequest, Segment, + SegmentRequest, SpeechRequest, TrackRequest, Tracks, VideoEditRequest, VideoRequest) from opendirector.domain.input_rules import input_rules from opendirector.domain.image_inputs import image_input_policy, validate_image_request from opendirector.domain.bigmodel_image import validate_bigmodel_image @@ -160,6 +162,12 @@ async def track(self, config, request: TrackRequest) -> Tracks: async def depth(self, config, request: DepthRequest) -> MediaResult: raise ProjectError('所选模型不支持深度动作捕捉。', 409) + async def camera(self, config, request: CameraRequest) -> CameraTrack: + raise ProjectError('所选模型不支持相机与场景估计。', 409) + + async def bodies(self, config, request: BodyRequest) -> BodyCapture: + raise ProjectError('所选模型不支持三维人体重建。', 409) + class BigModelImages(ModelAdapter): """BigModel's synchronous GLM-Image API, with a recoverable result locator.""" @@ -996,6 +1004,129 @@ def _inverse(data, near, far): return media.disparity(work.write('meters.mp4', data), work.path / 'inverse.mp4', near=near, far=far) +def npz_shapes(data: bytes) -> dict[str, tuple[int, ...]]: + shapes = {} + try: + with zipfile.ZipFile(io.BytesIO(data)) as archive: + for name in archive.namelist(): + with archive.open(name) as member: + version = np.lib.format.read_magic(member) + reader = np.lib.format.read_array_header_1_0 if version == (1, 0) else np.lib.format.read_array_header_2_0 + shapes[name.removesuffix('.npy')] = tuple(reader(member)[0]) + except zipfile.BadZipFile: + raise ValueError('not an NPZ archive') from None + return shapes + + +BODY_VECTORS = {'box': 4, 'camera_translation': 3, 'global_rotation': 3} +BODY_PARAMETERS = ('body_pose', 'hand_pose', 'shape', 'scale') + + +def _numbers(values, length=None) -> bool: + return (isinstance(values, list) and (length is None or len(values) == length) + and all(isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) for value in values)) + + +def checked_bodies(value, requested: set[tuple[int, int]]) -> tuple[list[dict], bytes]: + found = [dict(body, frame_index=int(frame['frame_index'])) for frame in value['frames'] for body in frame['bodies']] + keys = [(body['frame_index'], int(body['id'])) for body in found] + if len(keys) != len(set(keys)) or set(keys) != requested: + raise ValueError('bodies answer covers other people') + for body in found: + if (any(not _numbers(body.get(name), length) for name, length in BODY_VECTORS.items()) + or any(not _numbers(body.get(name)) for name in BODY_PARAMETERS) + or not isinstance(body.get('keypoints_3d'), list) or not all(_numbers(point, 3) for point in body['keypoints_3d'])): + raise ValueError('bodies answer record') + archive = base64.b64decode(value['vertices'], validate=True) + shapes, rows = npz_shapes(archive), len(found) + vertices, faces = shapes.get('vertices', ()), shapes.get('faces', ()) + if (len(vertices) != 3 or vertices[0] != rows or vertices[2] != 3 or len(faces) != 2 or faces[1] != 3 + or shapes.get('frame_index') != (rows,) or shapes.get('id') != (rows,)): + raise ValueError('bodies answer meshes') + with np.load(io.BytesIO(archive), allow_pickle=False) as arrays: + meshes = list(zip(arrays['frame_index'].tolist(), arrays['id'].tolist())) + if len(set(meshes)) != rows or set(meshes) != requested: + raise ValueError('bodies answer meshes cover other people') + return found, archive + + +def is_camera_model(config) -> bool: + name = config['modelId'].rstrip('/').rsplit('/', 1)[-1].lower() + return name.startswith('da3') or 'depth-anything-3' in name + + +class VllmOmniCamera(ModelAdapter): + + capabilities = frozenset({'video.camera'}) + MAP_EDGE = 504 + RESPONSE_BYTES = 384 * 1024 * 1024 + + async def camera(self, config, request: CameraRequest) -> CameraTrack: + form = {'model': config['modelId'], 'max_res': str(self.MAP_EDGE), 'return_depth': 'true', 'colormap': 'grayscale'} + + async def work(): + async with _client(self, config, timeout=1800) as client: + async with client.stream('POST', endpoint(config['url'], '/videos/depth'), headers=auth_headers(config), + data=form, files=[('video', ('clip.mp4', request.video, 'video/mp4'))], + extensions={'model_parameters': {'fields': form, 'file_count': 1}}) as response: + value = json.loads(await bounded(response, stage='submit', secrets=(config.get('apiKey', ''),), + limit=self.RESPONSE_BYTES)) + cameras = value['cameras'] + indices = tuple(int(item) for item in value['frame_indices']) + intrinsics = tuple(tuple(tuple(float(number) for number in row) for row in matrix) for matrix in cameras['intrinsics']) + extrinsics = tuple(tuple(tuple(float(number) for number in row) for row in matrix) for matrix in cameras['extrinsics']) + shapes = {len(indices), len(intrinsics), len(extrinsics), int(value['num_frames'])} + if (value['inverse'] is not False or cameras.get('convention') != 'opencv_world_to_camera' or len(shapes) != 1 + or not indices or list(indices) != sorted(set(indices)) or indices[0] < 0 or indices[-1] >= request.frames + or any(len(matrix) != 3 or any(len(row) != 3 for row in matrix) for matrix in intrinsics) + or any(not math.isfinite(number) for matrix in (*intrinsics, *extrinsics) for row in matrix for number in row) + or any(matrix[axis][axis] <= 0 for matrix in intrinsics for axis in (0, 1)) + or any(len(matrix) != 3 or any(len(row) != 4 for row in matrix) for matrix in extrinsics)): + raise ValueError('camera response') + maps = base64.b64decode(value['depth'], validate=True) + expected = (len(indices), int(value['height']), int(value['width'])) + arrays = npz_shapes(maps) + if (not 0 < min(expected[1:]) <= max(expected[1:]) <= self.MAP_EDGE + or arrays.get('depth') != expected or arrays.get('conf') != expected): + raise ValueError('camera maps') + return CameraTrack(str(value['model']), expected[2], expected[1], indices, intrinsics, extrinsics, maps) + return await _call('submit', work) + + +class VllmOmniBodies(ModelAdapter): + + capabilities = frozenset({'video.body_capture'}) + RESPONSE_BYTES = 192 * 1024 * 1024 + + async def bodies(self, config, request: BodyRequest) -> BodyCapture: + tracks = request.tracks + frames = [] + for index, counts in enumerate(tracks.frames): + if counts: + frames.append({'frame_index': index, 'instances': [ + {'id': int(tracks.identities[index][slot]), 'box': [round(value, 2) for value in tracks.boxes[index][slot]], + 'mask': {'size': [tracks.height, tracks.width], 'counts': list(counts[slot])}} + for slot in range(len(counts))]}) + listed = json.dumps(frames) + matrices = json.dumps({str(frame['frame_index']): request.intrinsics[frame['frame_index']] for frame in frames}) + form = {'model': config['modelId'], 'use_masks': 'true', 'return_vertices': 'true'} + + async def work(): + async with _client(self, config, timeout=1800) as client: + async with client.stream('POST', endpoint(config['url'], '/videos/bodies'), headers=auth_headers(config), data=form, + files=[('video', ('clip.mp4', request.video, 'video/mp4')), + ('frames', ('frames.json', listed.encode(), 'application/json')), + ('intrinsics', ('intrinsics.json', matrices.encode(), 'application/json'))], + extensions={'model_parameters': {'fields': form, 'file_count': 3}}) as response: + value = json.loads(await bounded(response, stage='submit', secrets=(config.get('apiKey', ''),), + limit=self.RESPONSE_BYTES)) + requested = {(int(frame['frame_index']), int(item['id'])) for frame in frames for item in frame['instances']} + found, archive = checked_bodies(value, requested) + return str(value['model']), tuple(str(name) for name in value['keypoint_names']), found, archive + model, names, found, archive = await _call('submit', work) + return BodyCapture(model, names, tuple(found), (archive,)) + + def adapter_for(config, transport=None, poll_interval=3, *, image_policy=None, legacy_image_policy=False) -> ModelAdapter | None: """The adapter serving a configuration, chosen from its explicit profile and protocol.""" kind, protocol = config['kind'], config.get('protocol') @@ -1011,7 +1142,9 @@ def adapter_for(config, transport=None, poll_interval=3, *, image_policy=None, l if profile == 'vllm-omni-segmentation': return VllmOmniSegmentation(transport, poll_interval) if profile == 'vllm-omni-depth': - return VllmOmniDepth(transport, poll_interval) + return (VllmOmniCamera if is_camera_model(config) else VllmOmniDepth)(transport, poll_interval) + if profile == 'vllm-omni-bodies': + return VllmOmniBodies(transport, poll_interval) if profile == 'vllm-omni-score': return VllmOmniScore(transport, poll_interval) if kind == 'agent': diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index e6d90cf8b..37328115d 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -71,6 +71,8 @@ def validate(self, kind, config): raise ProjectError('视觉分割模型仅用于选区、分割和抠像,请选择生成模型。') if input_rules(config)['profile'] == 'vllm-omni-depth': raise ProjectError('视频深度模型仅用于深度动作捕捉,请选择生成模型。') + if input_rules(config)['profile'] == 'vllm-omni-bodies': + raise ProjectError('三维人体模型仅用于视频脱模,请选择生成模型。') if input_rules(config)['profile'] == 'vllm-omni-score': raise ProjectError('扒谱模型仅用于参照音乐生成,请选择音乐生成模型。') adapter = self._profile_adapter(config) diff --git a/packages/core/src/opendirector/media/blockout.py b/packages/core/src/opendirector/media/blockout.py new file mode 100644 index 000000000..e0165ba95 --- /dev/null +++ b/packages/core/src/opendirector/media/blockout.py @@ -0,0 +1,535 @@ +import io +import json +from array import array +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, replace +from pathlib import Path + +import numpy as np +from PIL import Image, ImageFilter + +from opendirector.domain.capabilities import BodyCapture, CameraTrack, Tracks +from opendirector.domain.projects import ProjectError +from opendirector.media.rasterizer import face_normals, rasterize + +SCENE_STEP = 4 +SCENE_SEAM = 0.12 +SCENE_KEYFRAMES = 8 +SCENE_SMOOTHING = 3 +SCENE_PRIORITY = 1.03 +MIN_CONFIDENCE = 1.05 +MASK_GROWTH = 5 +HELD_MARGIN = 0.2 +HELD_DEPTH = 1.08 +SCENE_ALBEDO = np.array([0.86, 0.86, 0.87]) +BACKGROUND = np.array([0.93, 0.93, 0.94]) +PEOPLE = ((0.86, 0.17, 0.12), (0.16, 0.42, 0.86), (0.93, 0.68, 0.10), (0.18, 0.62, 0.32), + (0.58, 0.30, 0.80), (0.92, 0.45, 0.14), (0.12, 0.66, 0.70), (0.86, 0.34, 0.62)) +LIGHT = np.array([-0.3, -0.45, -1.0]) / np.linalg.norm([-0.3, -0.45, -1.0]) +AMBIENT, DIFFUSE = 0.5, 0.5 +EDGE_DEPTH = 0.035 +EDGE_CREASE = 0.5 +WORKERS = 4 +LAYOUT_FORMAT = 'opendirector.video-blockout.layout' +MIN_SHARED_PIXELS = 24 + + +@dataclass(frozen=True) +class Camera: + intrinsics: np.ndarray + rotation: np.ndarray + translation: np.ndarray + + +def square_intrinsics(intrinsics, source_size, target_size) -> np.ndarray: + (source_width, source_height), (width, height) = source_size, target_size + focal = (intrinsics[0, 0] * width / source_width if width >= height else intrinsics[1, 1] * height / source_height) + return np.array([[focal, 0, width / 2], [0, focal, height / 2], [0, 0, 1]], dtype=np.float64) + + +def _quaternion(rotation): + m = rotation + trace = np.trace(m) + if trace > 0: + s = 2 * np.sqrt(trace + 1) + q = np.array([s / 4, (m[2, 1] - m[1, 2]) / s, (m[0, 2] - m[2, 0]) / s, (m[1, 0] - m[0, 1]) / s]) + else: + i = int(np.argmax(np.diag(m))) + j, k = (i + 1) % 3, (i + 2) % 3 + s = 2 * np.sqrt(1 + m[i, i] - m[j, j] - m[k, k]) + q = np.empty(4) + q[0] = (m[k, j] - m[j, k]) / s + q[1 + i] = s / 4 + q[1 + j] = (m[j, i] + m[i, j]) / s + q[1 + k] = (m[k, i] + m[i, k]) / s + return q / np.linalg.norm(q) + + +def _rotation(q): + w, x, y, z = q / np.linalg.norm(q) + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +def _slerp(a, b, weight): + dot = float(np.dot(a, b)) + if dot < 0: + b, dot = -b, -dot + if dot > 0.9995: + return (1 - weight) * a + weight * b + angle = np.arccos(dot) + return (np.sin((1 - weight) * angle) * a + np.sin(weight * angle) * b) / np.sin(angle) + + +def frame_poses(frame_indices, extrinsics, count) -> list[tuple[np.ndarray, np.ndarray]]: + extrinsics = np.asarray(extrinsics, dtype=np.float64) + rotations = extrinsics[:, :, :3] + centers = -np.einsum('nji,nj->ni', rotations, extrinsics[:, :, 3]) + quaternions = [_quaternion(item) for item in rotations] + indices = list(frame_indices) + poses = [] + for frame in range(count): + upper = int(np.searchsorted(indices, frame)) + if upper < len(indices) and indices[upper] == frame: + rotation, center = rotations[upper], centers[upper] + elif upper == 0 or upper == len(indices): + nearest = 0 if upper == 0 else len(indices) - 1 + rotation, center = rotations[nearest], centers[nearest] + else: + lower = upper - 1 + weight = (frame - indices[lower]) / (indices[upper] - indices[lower]) + rotation = _rotation(_slerp(quaternions[lower], quaternions[upper], weight)) + center = (1 - weight) * centers[lower] + weight * centers[upper] + poses.append((rotation, -rotation @ center)) + return poses + + +def _block_mean(values, valid, step): + height, width = values.shape[0] // step * step, values.shape[1] // step * step + values, valid = values[:height, :width], valid[:height, :width] + shape = (height // step, step, width // step, step) + weight = valid.reshape(shape).sum(axis=(1, 3)) + total = np.where(valid, values, 0).reshape(shape).sum(axis=(1, 3)) + return np.where(weight > step * step // 2, total / np.maximum(weight, 1), np.nan) + + +def _box(values, radius): + padded = np.pad(values, radius, mode='edge') + total = np.pad(padded.cumsum(0).cumsum(1), ((1, 0), (1, 0))) + size = 2 * radius + 1 + return total[size:, size:] - total[:-size, size:] - total[size:, :-size] + total[:-size, :-size] + + +def smooth_depth(depth, valid, radius=SCENE_SMOOTHING): + inverse = np.where(valid, 1 / np.where(valid, depth, 1), 0) + weight = valid.astype(np.float64) + for _ in range(2): + count = _box(weight, radius) + inverse = np.where(count > 0, _box(inverse * weight, radius) / np.maximum(count, 1e-9), 0) + return np.where(valid, 1 / np.where(inverse > 0, inverse, 1), np.nan) + + +def depth_mesh(depth, excluded, camera: Camera, step=SCENE_STEP, seam=SCENE_SEAM): + valid = np.isfinite(depth) & (depth > 0) & ~excluded + grid = _block_mean(smooth_depth(depth.astype(np.float64), valid), valid, step) + rows, cols = grid.shape + v, u = np.mgrid[:rows, :cols] + focal, cx, cy = camera.intrinsics[0, 0], camera.intrinsics[0, 2], camera.intrinsics[1, 2] + u, v = (u + 0.5) * step, (v + 0.5) * step + points = np.stack([(u - cx) / focal * grid, (v - cy) / focal * grid, grid], axis=-1).reshape(-1, 3) + world = (points - camera.translation) @ camera.rotation + index = np.arange(rows * cols).reshape(rows, cols) + a, b, c, d = index[:-1, :-1].ravel(), index[:-1, 1:].ravel(), index[1:, :-1].ravel(), index[1:, 1:].ravel() + faces = np.concatenate([np.stack([a, b, c], 1), np.stack([b, d, c], 1)]) + z = grid.ravel()[faces] + keep = np.isfinite(z).all(axis=1) + faces, z = faces[keep], z[keep] + faces = faces[z.max(axis=1) <= z.min(axis=1) * (1 + seam)] + used, faces = np.unique(faces, return_inverse=True) + return world[used], faces.reshape(-1, 3) + + +def grow(mask: np.ndarray, pixels: int) -> np.ndarray: + if pixels <= 0 or not mask.any(): + return mask + image = Image.fromarray(mask.astype(np.uint8) * 255).filter(ImageFilter.MaxFilter(2 * pixels + 1)) + return np.asarray(image) > 127 + + +def resize_mask(mask: np.ndarray, width: int, height: int) -> np.ndarray: + if mask.shape == (height, width): + return mask + image = Image.fromarray(mask.astype(np.uint8) * 255).resize((width, height), Image.Resampling.BILINEAR) + return np.asarray(image) > 63 + + +@dataclass(frozen=True) +class Scene: + vertices: np.ndarray + faces: np.ndarray + normals: np.ndarray + keyframes: np.ndarray + + +def scene_proxy(depths, people_masks, cameras: list[Camera], keyframes, confidences=None) -> Scene: + vertices, faces, normals, sources, offset = [], [], [], [], 0 + for index in keyframes: + depth = np.asarray(depths[index], dtype=np.float32) + excluded = grow(resize_mask(people_masks[index], depth.shape[1], depth.shape[0]), MASK_GROWTH) + if confidences is not None: + excluded |= np.asarray(confidences[index], dtype=np.float32) < MIN_CONFIDENCE + world, triangles = depth_mesh(depth, excluded, cameras[index]) + if not len(triangles): + continue + camera = cameras[index] + local = world @ camera.rotation.T + camera.translation + normals.append(face_normals(local, triangles) @ camera.rotation) + vertices.append(world) + sources.append(np.full(len(world), index)) + faces.append(triangles + offset) + offset += len(world) + if not faces: + return Scene(np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), np.zeros(0, dtype=np.int64)) + return Scene(np.concatenate(vertices), np.concatenate(faces), np.concatenate(normals), np.concatenate(sources)) + + +def held_objects(depth, mask, margin=HELD_MARGIN, depth_slack=HELD_DEPTH) -> np.ndarray: + depth = np.asarray(depth, dtype=np.float32) + height, width = depth.shape + mask = resize_mask(mask, width, height) + if not mask.any(): + return np.zeros((height, width), dtype=bool) + rows, cols = np.nonzero(mask) + grow_y, grow_x = (rows.max() - rows.min() + 1) * margin, (cols.max() - cols.min() + 1) * margin + region = np.zeros((height, width), dtype=bool) + region[max(0, int(rows.min() - grow_y)):int(rows.max() + grow_y) + 1, max(0, int(cols.min() - grow_x)):int(cols.max() + grow_x) + 1] = True + return region & (depth <= np.median(depth[mask]) * depth_slack) + + +def keyframes_of(count: int, limit=SCENE_KEYFRAMES) -> list[int]: + if count <= limit: + return list(range(count)) + return sorted({round(item) for item in np.linspace(0, count - 1, limit)}) + + +def depth_ratio(depth, mask, body_depth) -> tuple[float, int] | None: + depth = np.asarray(depth, dtype=np.float64) + height, width = depth.shape + shared = resize_mask(mask, width, height) & np.isfinite(body_depth) & np.isfinite(depth) & (depth > 0) + shared &= ~grow(~resize_mask(mask, width, height), 1) + if shared.sum() < MIN_SHARED_PIXELS: + return None + return float(np.median(depth[shared] / body_depth[shared])), int(shared.sum()) + + +def smooth_series(frames, values, count, window=2) -> np.ndarray: + if not len(frames): + return np.full(count, np.nan) + frames, values = np.asarray(frames), np.asarray(values, dtype=np.float64) + order = np.argsort(frames) + frames, values = frames[order], values[order] + smoothed = np.array([np.median(values[max(0, i - window):i + window + 1]) for i in range(len(values))]) + return np.interp(np.arange(count), frames, smoothed) + + +def render_frame(scene: Scene, bodies, faces, camera: Camera, width: int, height: int, keyframe=None) -> np.ndarray: + rotation, translation, intrinsics = camera.rotation, camera.translation, camera.intrinsics + local = scene.vertices @ rotation.T + translation + if keyframe is not None: + local = local * np.where(scene.keyframes == keyframe, 1.0, SCENE_PRIORITY)[:, None] + layers = [(local, scene.faces, scene.normals @ rotation.T, SCENE_ALBEDO)] + for vertices, color in bodies: + layers.append((vertices, faces, face_normals(vertices, faces), np.asarray(color))) + vertices = np.concatenate([layer[0] for layer in layers]) + offsets = np.cumsum([0] + [len(layer[0]) for layer in layers]) + triangles = np.concatenate([layer[1] + offsets[index] for index, layer in enumerate(layers)]) + normals = np.concatenate([layer[2] for layer in layers]) + if not len(triangles): + return np.full((height, width, 3), (BACKGROUND * 255 + 0.5).astype(np.uint8)) + albedo = np.concatenate([np.broadcast_to(layer[3], (len(layer[1]), 3)) for layer in layers]) + raster = rasterize(vertices, triangles, intrinsics, width, height) + hit = raster.triangle >= 0 + owner = np.where(hit, raster.triangle, 0) + light = rotation @ LIGHT + shade = AMBIENT + DIFFUSE * np.clip(normals[owner] @ light, 0, 1) + color = np.where(hit[..., None], albedo[owner] * shade[..., None], BACKGROUND) + color *= _edges(raster.depth, normals[owner], hit)[..., None] + return (np.clip(color, 0, 1) * 255 + 0.5).astype(np.uint8) + + +def _edges(depth, normals, hit): + factor = np.ones(depth.shape) + log = np.log(np.where(hit, depth, 1.0)) + for axis in (0, 1): + ahead = [slice(None), slice(None)] + behind = [slice(None), slice(None)] + ahead[axis], behind[axis] = slice(1, None), slice(None, -1) + ahead, behind = tuple(ahead), tuple(behind) + both = hit[ahead] & hit[behind] + step = both & (np.abs(log[ahead] - log[behind]) > EDGE_DEPTH) + crease = both & (np.einsum('...i,...i->...', normals[ahead], normals[behind]) < EDGE_CREASE) + rim = hit[ahead] != hit[behind] + line = np.where(step | rim, 0.55, np.where(crease, 0.8, 1.0)) + far_side = np.where(log[ahead] >= log[behind], 1, 0) + target = np.ones(depth.shape) + target[ahead] = np.where(far_side == 1, line, 1.0) + target[behind] = np.minimum(target[behind], np.where(far_side == 0, line, 1.0)) + factor = np.minimum(factor, target) + return factor + + +def decode_mask(counts, width: int, height: int) -> np.ndarray: + counts = np.asarray(counts, dtype=np.int64) + if counts.sum() != width * height: + raise ProjectError('分割结果与视频尺寸不一致。', 502) + flat = np.repeat(np.arange(len(counts)) % 2 == 1, counts) + return flat.reshape(width, height).T + + +def component_box(counts, width: int, height: int) -> tuple[float, float, float, float] | None: + ends = np.cumsum(counts) + starts = ends - np.asarray(counts) + segments = [] + for start, end in zip(starts[1::2], ends[1::2]): + while start < end: + column, row = divmod(int(start), height) + stop = min(int(end), (column + 1) * height) + segments.append((column, row, row + stop - start)) + start = stop + if not segments: + return None + parent = list(range(len(segments))) + + def root(item): + while parent[item] != item: + parent[item] = parent[parent[item]] + item = parent[item] + return item + previous, current, column = [], [], -1 + for index, (col, top, bottom) in enumerate(segments): + if col != column: + previous, current, column = (current if col == column + 1 else []), [], col + for other in previous: + if segments[other][1] < bottom and top < segments[other][2]: + parent[root(index)] = root(other) + current.append(index) + sizes, boxes = {}, {} + for index, (col, top, bottom) in enumerate(segments): + key = root(index) + sizes[key] = sizes.get(key, 0) + bottom - top + x0, y0, x1, y1 = boxes.get(key, (col, top, col, bottom - 1)) + boxes[key] = (min(x0, col), min(y0, top), max(x1, col), max(y1, bottom - 1)) + return tuple(float(value) for value in boxes[max(sizes, key=sizes.get)]) + + +def people_tracks(tracks: Tracks) -> Tracks: + identities = tracks.identities or tuple(tuple(range(len(frame))) for frame in tracks.frames) + frames, kept_identities, boxes = [], [], [] + for counts, names in zip(tracks.frames, identities): + kept = [(array('i', item), name, component_box(item, tracks.width, tracks.height)) for item, name in zip(counts, names)] + kept = [entry for entry in kept if entry[2] is not None] + frames.append(tuple(entry[0] for entry in kept)) + kept_identities.append(tuple(entry[1] for entry in kept)) + boxes.append(tuple(entry[2] for entry in kept)) + return replace(tracks, frames=tuple(frames), identities=tuple(kept_identities), boxes=tuple(boxes)) + + +def body_chunks(tracks: Tracks, frames, limit: int) -> list[list[int]]: + chunks, current, size = [], [], 0 + for frame in frames: + people = len(tracks.frames[frame]) + if current and size + people > limit: + chunks.append(current) + current, size = [], 0 + current.append(frame) + size += people + if current: + chunks.append(current) + return chunks + + +def only_frames(tracks: Tracks, frames) -> Tracks: + keep = set(frames) + return replace(tracks, frames=tuple(item if index in keep else () for index, item in enumerate(tracks.frames)), + identities=tuple(item if index in keep else () for index, item in enumerate(tracks.identities)), + boxes=tuple(item if index in keep else () for index, item in enumerate(tracks.boxes))) + + +def frame_cameras(capture: CameraTrack, width: int, height: int, count: int): + intrinsics = np.asarray(capture.intrinsics, dtype=np.float64) + extrinsics = np.asarray(capture.extrinsics, dtype=np.float64) + maps = [Camera(square_intrinsics(matrix, (capture.width, capture.height), (capture.width, capture.height)), + pose[:, :3], pose[:, 3]) for matrix, pose in zip(intrinsics, extrinsics)] + focal = [square_intrinsics(matrix, (capture.width, capture.height), (width, height))[0, 0] for matrix in intrinsics] + frames = [] + for frame, (rotation, translation) in enumerate(frame_poses(capture.frame_indices, extrinsics, count)): + length = float(np.interp(frame, capture.frame_indices, focal)) + frames.append(Camera(np.array([[length, 0, width / 2], [0, length, height / 2], [0, 0, 1]]), rotation, translation)) + return maps, frames + + +class _Bodies: + + def __init__(self, capture: BodyCapture | None): + self.records = {(int(body['frame_index']), int(body['id'])): body for body in (capture.bodies if capture else ())} + self.faces, self.vertices = None, {} + for archive in (capture.meshes if capture else ()): + with np.load(io.BytesIO(archive), allow_pickle=False) as values: + self.faces, points = values['faces'].astype(np.int64), values['vertices'] + for row, (frame, identity) in enumerate(zip(values['frame_index'], values['id'])): + if (int(frame), int(identity)) in self.records: + self.vertices[(int(frame), int(identity))] = points[row] + + def __contains__(self, key): + return key in self.vertices + + def placed(self, key) -> np.ndarray: + return self.vertices[key].astype(np.float64) + np.asarray(self.records[key]['camera_translation'], dtype=np.float64) + + +def _rounded(values, digits=4): + return np.round(np.asarray(values, dtype=np.float64), digits).tolist() + + +def _compact(value) -> str: + return json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False) + + +def _members(pairs) -> bytes: + return ','.join(f'{_compact(key)}:{_compact(value)}' for key, value in pairs).encode() + + +class BlockoutRender: + + def __init__(self, tracks: Tracks, capture: CameraTrack, folder: Path, *, fps: float, source_frames: int, shown: list[int]): + self.tracks, self.capture, self.folder, self.fps = tracks, replace(capture, maps=b''), folder, fps + self.source_frames, self.shown = source_frames, shown + self.width, self.height, self.count = tracks.width, tracks.height, len(tracks.frames) + with np.load(io.BytesIO(capture.maps), allow_pickle=False) as values: + self.depth, self.confidence = values['depth'], values['conf'] + estimated = len(capture.frame_indices) + self.map_cameras, self.cameras = frame_cameras(capture, self.width, self.height, self.count) + self.keyframes = keyframes_of(estimated) + self.slots = {frame: slot for slot, frame in enumerate(capture.frame_indices)} + self.samples, self.covered = {}, [] + for frame in capture.frame_indices: + masks = self._masks(frame) + people = np.any(list(masks.values()), axis=0) if masks else np.zeros((self.height, self.width), dtype=bool) + cut = resize_mask(people, capture.width, capture.height) + for mask in masks.values(): + cut |= held_objects(self.depth[self.slots[frame]], mask) + self.covered.append(cut) + first = {} + for frame, names in enumerate(tracks.identities): + for identity in names: + first.setdefault(identity, frame) + self.identities = sorted(first, key=lambda name: (first[name], name)) + self.colors = {identity: PEOPLE[index % len(PEOPLE)] for index, identity in enumerate(self.identities)} + self.entries = {identity: [] for identity in self.identities} + self.model, self.keypoint_names = None, [] + self.scene = self.series = self.overall = None + folder.mkdir() + + @property + def intrinsics(self): + return tuple(camera.intrinsics.tolist() for camera in self.cameras) + + def _masks(self, frame): + return {identity: decode_mask(counts, self.width, self.height) + for identity, counts in zip(self.tracks.identities[frame], self.tracks.frames[frame])} + + def _note(self, capture: BodyCapture | None): + if capture is not None and self.model is None: + self.model, self.keypoint_names = capture.model, list(capture.keypoint_names) + + def measure(self, capture: BodyCapture | None) -> None: + self._note(capture) + bodies = _Bodies(capture) + for frame in sorted({frame for frame, _ in bodies.vertices}): + slot = self.slots.get(frame) + if slot is None: + continue + masks = self._masks(frame) + for identity, mask in masks.items(): + if (frame, identity) not in bodies: + continue + raster = rasterize(bodies.placed((frame, identity)), bodies.faces, self.map_cameras[slot].intrinsics, + self.capture.width, self.capture.height) + self.covered[slot] |= raster.triangle >= 0 + found = depth_ratio(self.depth[slot], mask, raster.depth) + if found: + self.samples.setdefault(identity, []).append((frame, found[0])) + + def settle(self) -> None: + self.scene = scene_proxy(self.depth, self.covered, self.map_cameras, self.keyframes, self.confidence) + ratios = [ratio for values in self.samples.values() for _, ratio in values] + self.ratios = ratios + self.overall = float(np.median(ratios)) if ratios else None + self.series = {} + for identity in self.identities: + measured = sorted(self.samples.get(identity, [])) + self.series[identity] = (smooth_series([f for f, _ in measured], [r for _, r in measured], self.count) if measured + else np.full(self.count, self.overall if self.overall else 1.0)) + self.meters = 1 / self.overall if self.overall else None + + def draw(self, capture: BodyCapture | None, frames) -> None: + self._note(capture) + bodies = _Bodies(capture) + faces = bodies.faces if bodies.faces is not None else np.zeros((0, 3), dtype=np.int64) + + def draw_frame(frame): + shown = [(bodies.placed((frame, identity)) * self.series[identity][frame], self.colors[identity]) + for identity in self.tracks.identities[frame] if (frame, identity) in bodies] + nearest = min(self.keyframes, key=lambda slot: abs(self.capture.frame_indices[slot] - frame)) + image = render_frame(self.scene, shown, faces, self.cameras[frame], self.width, self.height, keyframe=nearest) + Image.fromarray(image).save(self.folder / f'{frame:05d}.png', compress_level=1) + + with ThreadPoolExecutor(max_workers=WORKERS) as pool: + list(pool.map(draw_frame, frames)) + unit = self.meters or 1.0 + for frame in frames: + for identity in self.tracks.identities[frame]: + body = bodies.records.get((frame, identity)) + if body is None or (frame, identity) not in bodies: + continue + correction = float(self.series[identity][frame] * self.meters) if self.meters else 1.0 + root = np.asarray(body['camera_translation'], dtype=np.float64) * correction + camera = self.cameras[frame] + world = camera.rotation.T @ (root - camera.translation * unit) + self.entries[identity].append((frame, _compact({ + 'frame': frame, 'box': _rounded(body['box'], 1), 'cameraTranslation': _rounded(body['camera_translation']), + 'depthCorrection': round(correction, 4), 'worldRoot': _rounded(world), + 'globalRotation': _rounded(body['global_rotation']), 'bodyPose': _rounded(body['body_pose']), + 'handPose': _rounded(body['hand_pose']), 'shape': _rounded(body['shape']), + 'skeletonScale': _rounded(body['scale']), 'keypoints3d': _rounded(body['keypoints_3d'])}).encode())) + + def layout(self) -> bytes: + meters, unit = self.meters, self.meters or 1.0 + camera_frames = [{'frame': frame, 'estimated': frame in self.slots, 'intrinsics': _rounded(camera.intrinsics, 3), + 'extrinsics': _rounded(np.concatenate([camera.rotation, camera.translation[:, None] * unit], 1), 5)} + for frame, camera in enumerate(self.cameras)] + spread = np.percentile(np.asarray(self.ratios) * meters, [10, 50, 90]).round(4).tolist() if meters else None + head = [('format', LAYOUT_FORMAT), ('version', 1), ('frames', self.count), ('fps', self.fps), ('width', self.width), + ('height', self.height), + ('timeline', {'frameSeconds': 'frame / fps', 'sourceFrames': self.source_frames, + 'resampled': self.shown != list(range(self.source_frames)), + **({} if self.shown == list(range(self.source_frames)) else {'sourceFrameOf': self.shown})}), + ('camera', {'model': self.capture.model, 'axes': 'opencv', 'extrinsics': 'world_to_camera', 'world': 'first_frame_camera', + 'unit': 'meter' if meters else 'depth_model_unit', + 'metersPerDepthUnit': round(meters, 6) if meters else None, + 'estimatedFrames': list(self.capture.frame_indices), 'frames': camera_frames}), + ('scene', {'keyframes': [self.capture.frame_indices[slot] for slot in self.keyframes], + 'triangles': int(len(self.scene.faces)), 'gridPixels': SCENE_STEP, 'minimumConfidence': MIN_CONFIDENCE}), + ('alignment', {'samples': len(self.ratios), + 'correctionPercentiles': {'p10': spread[0], 'p50': spread[1], 'p90': spread[2]} if spread else None})] + people = [('model', self.model), ('keypointNames', self.keypoint_names)] + pieces = [b'{', _members(head), b',"people":{', _members(people), b',"tracks":['] + for number, identity in enumerate(identity for identity in self.identities if self.entries[identity]): + color = '#%02x%02x%02x' % tuple(round(value * 255) for value in self.colors[identity]) + pieces.extend([b',' if number else b'', b'{', _members([('id', identity), ('color', color)]), b',"frames":[']) + for index, (_, entry) in enumerate(sorted(self.entries[identity], key=lambda item: item[0])): + pieces.extend([b',' if index else b'', entry]) + pieces.append(b']}') + pieces.append(b']}}') + return b''.join(pieces) diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index 2deaf0930..63b6615e6 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -2,8 +2,10 @@ import io import json +import math import subprocess import tempfile +from fractions import Fraction from functools import lru_cache from pathlib import Path @@ -253,13 +255,61 @@ 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: +def _rational(fps: float) -> str: + return str(Fraction(fps).limit_denominator(1001)) + + +def source_frame_map(source: Path, *, fps: float) -> list[int]: + raw = _run(['ffmpeg', '-v', 'error', '-i', str(source), '-vf', f'scale=4:4,format=gray16le,geq=lum=N,fps={_rational(fps)}', '-an', + _frame_sync_option(), 'passthrough', '-f', 'rawvideo', '-pix_fmt', 'gray16le', '-'], timeout=600) + return [int.from_bytes(raw[offset:offset + 2], 'little') for offset in range(0, len(raw), 32)] + + +def constant_rate_picture(source: Path, out: Path, *, width: int, height: int, fps: float, regular: bool = False) -> Path: + timing = f'settb=1/({_rational(fps)}),setpts=N,fps={_rational(fps)}' if regular else f'fps={_rational(fps)}' _run(['ffmpeg', '-v', 'error', '-y', '-i', str(source), - '-vf', f'scale={width}:{height},setsar=1,fps={fps:.6f},format=yuv420p', '-an', + '-vf', f'scale={width}:{height},setsar=1,{timing},format=yuv420p', '-an', _frame_sync_option(), 'passthrough', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '18', str(out)]) return out +COMMON_RATES = (24000 / 1001, 24.0, 25.0, 30000 / 1001, 30.0, 48.0, 50.0, 60000 / 1001, 60.0, 120.0) + + +def frame_times(path: Path) -> list[float]: + output = _run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'frame=best_effort_timestamp_time', + '-of', 'csv=p=0', str(path)], timeout=300).decode() + return sorted(float(line.split(',')[0]) for line in output.split() if line.split(',')[0] not in ('', 'N/A')) + + +def _on_grid(times: list[float], rate: float) -> bool: + offset = sorted(time - index / rate for index, time in enumerate(times))[len(times) // 2] + return all(round((time - offset) * rate) == index for index, time in enumerate(times)) + + +def nominal_rate(times: list[float], probed: float) -> tuple[float, bool]: + gaps = sorted(b - a for a, b in zip(times, times[1:]) if b > a) + if not gaps: + return probed, True + gap = gaps[len(gaps) // 4] + steady = [g for g in gaps if abs(g - gap) <= 0.15 * gap] + measured = len(steady) / sum(steady) + regular = [rate for rate in (probed, *COMMON_RATES) if _on_grid(times, rate)] + if regular: + middle, mean = (len(times) - 1) / 2, sum(times) / len(times) + spread = sum((index - middle) ** 2 for index in range(len(times))) + step = sum((index - middle) * (time - mean) for index, time in enumerate(times)) / spread + residual = sum((time - mean - step * (index - middle)) ** 2 for index, time in enumerate(times)) + uncertainty = math.sqrt(residual / max(len(times) - 2, 1) / spread) / step ** 2 + if probed in regular and abs(probed - 1 / step) <= 3 * uncertainty: + return probed, True + return min(regular, key=lambda rate: abs(rate - 1 / step)), True + matches = [rate for rate in (probed, *COMMON_RATES) if abs(rate - measured) <= 0.01 * measured] + if matches: + return (probed if probed in matches else min(matches, key=lambda rate: abs(rate - measured))), False + return round(measured, 3), False + + 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) @@ -274,10 +324,12 @@ 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, max_megabits: int | None = None) -> bytes: +def encode_frames(pattern: str, fps: float, out: Path, *, crf: int = 12, max_megabits: int | None = None, + size: tuple[int, 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', + scale = f'scale={size[0]}:{size[1]}:flags=lanczos,setsar=1,' if size else '' + _run(['ffmpeg', '-v', 'error', '-y', '-framerate', _rational(fps), '-i', pattern, '-vf', f'{scale}format=yuv420p', '-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/rasterizer.py b/packages/core/src/opendirector/media/rasterizer.py new file mode 100644 index 000000000..defd06fd3 --- /dev/null +++ b/packages/core/src/opendirector/media/rasterizer.py @@ -0,0 +1,104 @@ +from dataclasses import dataclass + +import numpy as np + +NEAR = 1e-3 +CANDIDATES_PER_PASS = 1 << 20 + + +@dataclass(frozen=True) +class Raster: + depth: np.ndarray + triangle: np.ndarray + + +def project(points: np.ndarray, intrinsics: np.ndarray) -> np.ndarray: + z = points[:, 2] + return np.stack([intrinsics[0, 0] * points[:, 0] / z + intrinsics[0, 2], + intrinsics[1, 1] * points[:, 1] / z + intrinsics[1, 2]], axis=1) + + +def rasterize(vertices: np.ndarray, faces: np.ndarray, intrinsics: np.ndarray, width: int, height: int) -> Raster: + vertices = np.asarray(vertices, dtype=np.float64) + faces = np.asarray(faces, dtype=np.int64) + depth = np.full(height * width, np.inf, dtype=np.float32) + triangle = np.full(height * width, -1, dtype=np.int64) + if not len(faces): + return Raster(depth.reshape(height, width), triangle.reshape(height, width)) + corners = vertices[faces] + front = (corners[:, :, 2] > NEAR).all(axis=1) + ids = np.nonzero(front)[0] + corners = corners[front] + pixels = project(corners.reshape(-1, 3), intrinsics).reshape(-1, 3, 2) - 0.5 + x, y, z = pixels[:, :, 0], pixels[:, :, 1], corners[:, :, 2] + area = (x[:, 1] - x[:, 0]) * (y[:, 2] - y[:, 0]) - (x[:, 2] - x[:, 0]) * (y[:, 1] - y[:, 0]) + x0 = np.maximum(np.ceil(x.min(axis=1)), 0) + x1 = np.minimum(np.floor(x.max(axis=1)), width - 1) + y0 = np.maximum(np.ceil(y.min(axis=1)), 0) + y1 = np.minimum(np.floor(y.max(axis=1)), height - 1) + keep = (np.abs(area) > 1e-12) & (x1 >= x0) & (y1 >= y0) + ids, x, y, z, area = ids[keep], x[keep], y[keep], z[keep], area[keep] + x0, y0, x1, y1 = x0[keep], y0[keep], x1[keep], y1[keep] + coefficients = _plane_coefficients(x, y, z, area, x0, y0) + columns = _bucket(x1 - x0 + 1) + rows = _bucket(y1 - y0 + 1) + left, top = x0.astype(np.int64), y0.astype(np.int64) + found_pixel, found_depth, found_triangle = [], [], [] + stride = 2 * (width + height) + 8 + shapes, groups = np.unique(columns * stride + rows, return_inverse=True) + order = np.argsort(groups, kind='stable') + bounds = np.concatenate([[0], np.cumsum(np.bincount(groups, minlength=len(shapes)))]) + for shape_index, shape in enumerate(shapes): + size_x, size_y = divmod(int(shape), stride) + members = order[bounds[shape_index]:bounds[shape_index + 1]] + offsets = np.arange(size_x * size_y) + dx, dy = (offsets % size_x).astype(np.float32), (offsets // size_x).astype(np.float32) + step = max(1, CANDIDATES_PER_PASS // (size_x * size_y)) + for start in range(0, len(members), step): + group = members[start:start + step] + a, b, c = coefficients[group, :, 0, None], coefficients[group, :, 1, None], coefficients[group, :, 2, None] + values = a * dx + b * dy + c + inside = (values[:, 0] >= 0) & (values[:, 1] >= 0) & (values[:, 2] >= 0) + hit_rows, hit_cols = np.nonzero(inside) + if not len(hit_rows): + continue + px = left[group[hit_rows]] + (hit_cols % size_x) + py = top[group[hit_rows]] + (hit_cols // size_x) + on_image = (px < width) & (py < height) + hit_rows, px, py = hit_rows[on_image], px[on_image], py[on_image] + found_pixel.append(py * width + px) + found_depth.append(1 / values[hit_rows, 3, hit_cols[on_image]]) + found_triangle.append(ids[group[hit_rows]]) + if found_pixel: + pixel, near, owner = np.concatenate(found_pixel), np.concatenate(found_depth), np.concatenate(found_triangle) + np.minimum.at(depth, pixel, near) + nearest = near == depth[pixel] + triangle[pixel[nearest]] = owner[nearest] + return Raster(depth.reshape(height, width), triangle.reshape(height, width)) + + +def _plane_coefficients(x, y, z, area, left, top): + result = np.empty((len(x), 4, 3)) + for weight, (first, second) in enumerate(((1, 2), (2, 0), (0, 1))): + ex, ey = x[:, second] - x[:, first], y[:, second] - y[:, first] + result[:, weight, 0] = -ey / area + result[:, weight, 1] = ex / area + result[:, weight, 2] = (ey * (x[:, first] - left) - ex * (y[:, first] - top)) / area + result[:, 3] = np.einsum('nk,nkc->nc', 1 / z, result[:, :3]) + return result.astype(np.float32) + + +def _bucket(span: np.ndarray) -> np.ndarray: + span = span.astype(np.int64) + exponent = np.floor(np.log2(np.maximum(span, 1))).astype(np.int64) + unit = np.maximum(1, (1 << exponent) // 4) + return -(-span // unit) * unit + + +def face_normals(vertices: np.ndarray, faces: np.ndarray) -> np.ndarray: + corners = np.asarray(vertices, dtype=np.float64)[faces] + normal = np.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0]) + normal /= np.maximum(np.linalg.norm(normal, axis=1, keepdims=True), 1e-12) + facing = np.einsum('ij,ij->i', normal, corners.mean(axis=1)) > 0 + normal[facing] *= -1 + return normal diff --git a/pyproject.toml b/pyproject.toml index b9f9b60e5..b617a4df3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ requires-python = ">=3.11" dependencies = [ "PyYAML>=6,<7", "filelock>=3.16,<4", "httpx[socks]>=0.27,<1", "anyio>=4,<5", "pydantic>=2.12,<3", "typer>=0.27.3,<0.28", "Pillow>=12,<14", "pillow-heif>=1.8.1,<2", - "fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1", + "fonttools==4.68.0", "fastapi>=0.115,<1", "uvicorn>=0.30,<1", "numpy>=2,<3", "starlette>=1.8,<2", "python-multipart>=0.0.33,<1", "yt-dlp>=2026.11.23", "distlib>=0.4,<1; sys_platform == 'win32'", ] diff --git a/requirements.txt b/requirements.txt index d21534ecd..5b21b4703 100644 --- a/requirements.txt +++ b/requirements.txt @@ -54,6 +54,8 @@ markdown-it-py==4.2.0 # via rich mdurl==0.1.2 # via markdown-it-py +numpy==2.5.5 + # via opendirector (pyproject.toml) opentelemetry-api==1.45.1 # via fastapi packaging==26.3 diff --git a/src/backend/rules.ts b/src/backend/rules.ts index cea000706..3d829341a 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -89,6 +89,7 @@ export interface ModelConfig { | "vllm_omni_music" | "vllm_omni_depth" | "vllm_omni_score" + | "vllm_omni_bodies" | null; authMode: "none" | "bearer" | null; proxyMode?: "system" | "direct"; @@ -116,6 +117,10 @@ export function isDepthModel(model: Pick) { return model.protocol === "vllm_omni_depth"; } +export function isBodyModel(model: Pick) { + return model.protocol === "vllm_omni_bodies"; +} + /** SheetSage2 configurations transcribe reference music into scores only. */ export function isScoreModel(model: Pick) { return model.protocol === "vllm_omni_score"; @@ -183,7 +188,10 @@ export function isGenerationModel( model: Pick, ) { return ( - !isSegmentationModel(model) && !isDepthModel(model) && !isScoreModel(model) + !isSegmentationModel(model) && + !isDepthModel(model) && + !isScoreModel(model) && + !isBodyModel(model) ); } @@ -618,6 +626,8 @@ export function backendBlocker( return tNow("errors.rules.depthModel"); if (isScoreModel(config)) return tNow("errors.rules.transcriptionModel"); + if (isBodyModel(config)) + return tNow("errors.rules.bodyModel"); if (!isGenerationModel(config)) return tNow("errors.rules.segmentationModel"); const references = backendReferences(settings, [...incoming, ...pinned], config); diff --git a/src/canvas/ModelCapabilityCard.tsx b/src/canvas/ModelCapabilityCard.tsx index b7f1f0176..c70452262 100644 --- a/src/canvas/ModelCapabilityCard.tsx +++ b/src/canvas/ModelCapabilityCard.tsx @@ -78,7 +78,7 @@ export function ModelCapabilityCard({ nativeCapabilities?.outputs.flatMap((output) => output.durations) ?? []; const video = connection.kind === "video" && - !["vllm_omni_segmentation", "vllm_omni_depth"].includes( + !["vllm_omni_segmentation", "vllm_omni_depth", "vllm_omni_bodies"].includes( connection.protocol, ); const updateDraft = (next: VideoCapabilityDraft, nextAdapter = adapter) => { diff --git a/src/canvas/ModelServiceForm.tsx b/src/canvas/ModelServiceForm.tsx index 7311da83d..9ae49e7c5 100644 --- a/src/canvas/ModelServiceForm.tsx +++ b/src/canvas/ModelServiceForm.tsx @@ -47,6 +47,7 @@ const PROTOCOLS: Record< ["volcengine", "models.protocolOption.volcengine"], ["vllm_omni_segmentation", "models.protocolOption.segmentation"], ["vllm_omni_depth", "models.protocolOption.depth"], + ["vllm_omni_bodies", "models.protocolOption.bodies"], ], audio: [ ["openai", "models.protocolOption.tts"], @@ -146,6 +147,7 @@ export function ModelServiceForm({ const segmentation = value.protocol === "vllm_omni_segmentation"; const depth = value.protocol === "vllm_omni_depth"; const score = value.protocol === "vllm_omni_score"; + const bodies = value.protocol === "vllm_omni_bodies"; const preset = PROVIDER_PRESETS.find((item) => item.id === presetId); const mediaPresetModels = kind === "agent" ? undefined : preset?.modelsByKind?.[kind]; const hasSavedKey = Boolean( @@ -585,6 +587,9 @@ export function ModelServiceForm({ {score && (

{t("models.service.scoreNote")}

)} + {bodies && ( +

{t("models.service.bodiesNote")}

+ )}