diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index cf7a982f5..50de34034 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,6 +16,13 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + 'keyframe_unsupported': 'This model or mode does not support keyframes. Clear the keyframe times or choose another model.', + 'keyframe_mode': 'Keyframes work in Universal reference mode only, not with first/last frames, continuation or structure control.', + 'keyframe_kind': 'A keyframe must be an image.', + 'keyframe_count': 'There are more keyframes than this model accepts.', + 'keyframe_needs_reference': 'Keyframes also need at least one ordinary reference image or video.', + 'keyframe_time': 'Each keyframe needs its own time, earlier than the end of the video and at least 1/24 second from the others.', + 'keyframe_image': 'A keyframe must be a PNG, JPEG or WebP image within the size limit.', 'higgsfield_model': 'Choose MAGI-2 with the official Higgsfield Open API address.', 'higgsfield_key': 'Enter your Higgsfield Open KEY_ID:KEY_SECRET.', 'higgsfield_output': 'MAGI-2 supports 1080p and whole-second durations from 4 to 30 seconds.', diff --git a/docs/README.md b/docs/README.md index b574a4903..86cc0fe69 100644 --- a/docs/README.md +++ b/docs/README.md @@ -25,6 +25,7 @@ This directory is the entry point for the repository's shared documentation. The | [UI performance design](development/ui-performance.md) | Interaction design principles, latency budgets, and measurement | A UI performance principle, target, or measurement method changes | | [macOS installation validation](development/macos-install-validation.md) | Installation and usage scenarios verified on Apple Silicon | The corresponding acceptance checks are repeated | | [Bilingual interface](development/i18n.md) | Language selection, message organization, and checks | Language policy, message structure, or checks change | +| [H3 conditioning features](development/h3-conditioning-features.md) (中文) | Structure control, latent continuation, masked editing and keyframes for self-hosted H3 models, with measured results | The H3 request shapes or the vLLM-Omni capabilities they rely on change | | [Python installation and packaging](development/packaging.md) | Installation, platform wheel builds, and isolated verification | Packaging, resource paths, or build process changes | | [Business CLI](guides/cli.md) | Querying, editing, and generating through a terminal or Agent Shell | Commands, authorization, or receipt semantics change | | [DeepSeek Harness plugin](../plugins/deepseek-harness/README.md) | Installing the DSH bundle and editing an OpenDirector project from DSH | Plugin setup, tools, or creation workflows change | diff --git a/docs/development/h3-conditioning-features.md b/docs/development/h3-conditioning-features.md new file mode 100644 index 000000000..dc5df7641 --- /dev/null +++ b/docs/development/h3-conditioning-features.md @@ -0,0 +1,141 @@ +# H3 系列模型的条件生成能力:接入方案 + +本文说明如何让 OpenDirector 对所有自部署的 MiniMax-H3 衍生模型开放四项条件生成能力:结构控制(含姿态)、潜空间接续、局部重绘、指定时间点的关键帧。范围限于 `vllm_omni` 协议的视频模型。 + +## 1. 背景 + +vLLM-Omni 已经让每一种 H3 权重都能使用这四项能力(vllm-project/vllm-omni#11078):原版 H3、FastH3 Omni,以及 LightX2V Turbo、Pika Flex Turbo、alibaba-pai Acc 这三类蒸馏适配器。OpenDirector 仍按最初接入时的划分,把能力绑定在两个互不重叠的档案上: + +| 档案(`inputRules.profile`) | 适配器 | 视频模式 | 局部重绘工具 | +| --- | --- | --- | --- | +| `vllm-omni-h3` | `minimax_h3` | 首帧、素材参考、接续 | 可用 | +| `fasth3-omni` | `fasth3` / `fasth3_dual` | 素材参考、结构控制(`fasth3_dual` 另有首尾帧) | 不可用 | + +结果是:用 `fasth3` 请求格式的模型(FastH3 Omni、Pika H3 等 8 步蒸馏模型)用不了接续和局部重绘;用 `minimax_h3` 的原版 H3 用不了结构控制;关键帧在两边都只有「首帧 / 尾帧」两个固定位置。 + +## 2. 实测依据 + +2026-11-27 在 4×B300 上用「原版 H3 Ref2VA + Pika Flex Turbo 8 步 LoRA + Fun ControlNet Union」实测,832×480、124 帧,每项一个提示词、一个种子。 + +- 同一个服务(张量并行 4,启动时带 `--controlnet-model-path`)在不同请求里分别完成了:姿态控制、深度控制、潜空间遮罩重绘、时间线关键帧、`continue_from` 接续。 +- 结构控制与另外三项不能出现在同一个请求里,服务端返回 400:控制 + 关键帧、控制 + 遮罩重绘、控制 + `continue_from`。 +- 按 vLLM-Omni 文档,控制分支只支持张量并行,不支持 Ulysses 序列并行(后者未实测)。张量并行 4 与此前的 Ulysses 4 在这组请求上速度相同,约 3 秒一段。 +- 服务端不做预处理:`control_type=pose` 只读取上传的骨架画面,姿态、边缘、深度图都要由客户端准备。 + +## 3. 设计原则 + +**把「权重能做什么」和「请求怎么采样」分开。** 目前 `videoAdapter` 同时决定了两件事。四项能力属于 H3 这一族,与采样方式无关;采样约定才因权重而异。 + +- **能力**由 H3 族和服务的分区决定,写进输入规则,前端从 `inputRules` 读取,不再按适配器名判断。 +- **采样约定**由适配器决定:步数、引导强度、流偏移、采样器、是否需要 LoRA。 + +分区限制是真实的,需要在规则里表达: + +| 服务分区 | 文生 / 首帧 | 素材参考 | 结构控制 | 接续 | 局部重绘 | 关键帧 | +| --- | --- | --- | --- | --- | --- | --- | +| FL2VA(`--task-type fl2va`) | 是 | 否 | 是(无参考) | 是 | 是 | 是 | +| Ref2VA(`--task-type ref2va`,含 FastH3 Omni) | 否 | 是 | 是(带参考) | 是,衔接较松 | 是,需一张参考图 | 是 | +| 合并服务(两个 DiT) | 是 | 是 | 否 | 是 | 是 | 是 | + +## 4. 分项方案 + +改动量参照结构控制最初接入的那次提交(`51dedd70`,52 个文件、约 840 行,其中包含两个工具)。 + +### 4.1 潜空间接续(改动最小) + +界面上已有「接续」模式和「延长」按钮,`useWorkspaceEditor.ts` 在模型支持接续时会自动把「延长」升级为接续。缺的只是 `fasth3-omni` 档案不声明这个模式,以及它的请求路径不发 `continue_from`。 + +1. `domain/input_rules.py`:给 `fasth3-omni` 的 `videoModes` 加上 `continuation`。 +2. `integrations/fasth3.py` 的 `generation_fields`:接续时写入 `extra['continue_from']`。 +3. `integrations/providers.py`:接续模式下不上传源视频。来源解析沿用 `reference_inputs.continuation_source`。 +4. `domain/creation/generation.py`、`model_availability.py`、`rule_facts.py` 的用例向量:把 `fasth3-omni` 纳入接续的校验与可用性判断。 + +来源必须是同一服务生成且缓存还在的任务,上传的视频不能接续。对上传的视频,「延长」继续走素材参考模式,把该视频作为参考视频(长度仍受参考视频时长上限限制)。Ref2VA 权重对潜变量尾部跟得较松,接缝可能可见,应在模式说明里写明。 + +### 4.2 局部重绘 + +界面(`VideoActionEditor`)、三个工具和后端流程都已存在,只是 `adapter_for` 只在 `vllm-omni-h3` 档案下返回提供 `video.edit` 的适配器。 + +1. `integrations/model_adapters.py`:`adapter_for` 对 `fasth3-omni` 也返回一个编辑适配器。 +2. 该适配器按 Ref2VA 的约定发请求:`task=ref2va`、固定步数与引导强度,并附一张参考图(取源片段的第一帧)。现有的 `VllmOmniVideo.edit_video` 发的是 `task=t2va`,在只有 Ref2VA 的服务上不可用。 +3. `domain/capability_contract.py`:`video_to_video` 档案的必需输入增加参考图的情况。 + +**参考图决定片段的开头。** Ref2VA 模型会让片段开头贴近参考图:重绘区域在开头显示的是参考图在该处的内容,提示词描述的画面要过一段时间才出现。以源片段首帧作参考图时,成片第 0 帧的重绘区域与原片相同(固定种子 9 次中 9 次),修改最早在第 32 帧前后出现,慢的要到片尾。把参考图里的重绘区域涂灰、裁掉,或改写提示词,都不能消除这一点:结果随种子而变,涂灰时开头可能出现灰块,裁剪时可能把参考图里的人物再画一遍。服务端不接受不带参考图的请求。 + +因此框选重绘跑两遍:第一遍以源片段首帧为参考图,到片尾时已是修改后的画面;第二遍以第一遍结果中修改覆盖的最后一帧为参考图,让修改尽量从片头就在。两遍的请求除参考图外完全相同,耗时约为一遍的两倍。这样做提高了修改出现在片头的概率,但并不可靠:早期固定种子实测,同一提示词下 6 次中 5 次从第 0 帧起就是修改后的画面,另 1 次在前约半秒内淡入;2026-12-01 在画布上用另一组素材提交的框选重绘里,也有到第 46 帧(约 1.9 秒)修改才出现的一次(见第 8 节)。整帧的时间段重绘(局部重拍)仍只跑一遍:片段开头是保留的画面,首帧正是要延续的样子;时间段从片头开始时,改取时间段结束后的第一帧。后一种情况固定种子各测 3 次:以首帧为参考图时,要求的修改 2 次完全没有出现、1 次只短暂出现;改取时间段之后的第一帧,3 次都在整个时间段内出现。 + +### 4.3 结构控制的类型 + +现在 `fasth3.control_parameters` 把类型写死为 `depth`,界面没有选择。 + +1. `VideoParameters` 增加 `controlType`(`depth`、`pose`、`canny`、`hed`、`mlsd`)和 `controlScale`,重新生成契约。 +2. `NodeComposer.tsx` 在结构控制模式下增加类型下拉和强度输入,补中英文文案。 +3. 给原版 H3(`vllm-omni-h3`)也开放 `control` 模式:FL2VA 服务上是无参考的 T2VA 请求。合并服务不提供。 +4. 预处理工具:已有「深度动捕」;新增「姿态提取」和「边缘提取」,产出可直接连接为控制视频的素材。边缘可用本地 FFmpeg 完成;姿态需要一个检测模型,可以做成本地工具进程,也可以接一个新的模型协议。 + +### 4.4 指定时间点的关键帧(改动最大) + +现有的首尾帧只存两个节点 ID,引用上没有时间字段,`frame_indices` 只会是 0 或 -1。 + +1. 契约:在引用上增加可选的 `frameTimeMs`(或在 `VideoParameters` 上增加关键帧列表),角色增加 `keyframe`,重新生成契约。 +2. 画布:`NodeComposer.tsx` 的帧槽位从固定两格扩展为列表,每一项选一张已连接的图片并填写时间点;`creationProjection.ts` 负责双向映射。 +3. 后端:`creation_generation.task()` 把时间随 `referenceRoles` 传下去;`reference_inputs.py` 换算成帧号;请求发送 `timeline_guides` 清单、`guide_files` 上传和 `quality=lossless`。 +4. 校验:最多 8 项;时间点落在输出时长内;与结构控制、接续、局部重绘互斥。 + +首帧和尾帧可以统一成时间为 0 和结尾的关键帧,这样 Ref2VA 权重也能有首尾帧,不必依赖 `fasth3_dual` 的第二个 DiT。 + +### 4.5 采样约定与 LoRA + +Pika、LightX2V Turbo、PAI Acc 都要求每个请求带 `lora` 字段,并使用各自固定的步数和流偏移。OpenDirector 现在不发 `lora`,部署时只能在中间加一层转发来补。 + +- 在模型配置上增加可选的采样约定:`steps`、`guidanceScale`、`flowShift`、`lora`(名称、服务端路径、强度)。`fasth3` 这条请求路径读取它们,而不是写死 8 步。 +- 更好的来源是服务自己声明。OpenDirector 已经会查询 `/v1/omni/capabilities`,当前 vLLM-Omni 对它返回 404。等服务端提供该接口后,能力、分区和采样约定都应从那里读取,手工配置只作兜底。 + +## 5. 互斥规则 + +前端在 `rules.ts` 的 `backendBlocker`、后端在 `validate_generation` 中各校验一次: + +- 结构控制不与关键帧、接续、局部重绘同时使用。 +- 关键帧不与接续、局部重绘同时使用。 +- 结构控制模式下输出时长跟随控制视频,现有规则不变。 + +## 6. 实现情况 + +已实现: + +- **潜空间接续(4.1)**:`fasth3-omni` 档案声明 `continuation`;请求发送 `continue_from` 并沿用来源画幅,不上传源视频;服务端已无缓存时给出专门的说明。 +- **局部重绘(4.2)**:`FastH3VideoEdit` 适配器为 `fasth3-omni` 提供 `video.edit`,按 Ref2VA 发请求。框选重绘跑两遍,第二遍以第一遍结果的最后一帧作参考图,让修改尽量从片头就出现(多数情况有效,并不可靠,见 4.2)。请求附带的参考图已计入三个编辑工具的准入检查。 +- **指定帧(4.4)**:引用新增角色 `keyframe` 和字段 `frameTimeMs`,输入规则新增 `maxKeyframes`(两个 H3 档案均为 8);画布设置为 `pinnedFrames`;两条 H3 请求路径都发送 `timeline_guides`。目前只在素材参考模式下提供;规格没有时长时拒绝关键帧,因为时间点无从比较。 + +未实现: + +- **采样约定与 LoRA(4.5)**:OpenDirector 的请求仍固定 8 步、不带 `lora`;现在由随应用启动的视频转发层按模型名补上步数、流偏移和 `lora`(见[视频转发层指南](../guides/video-gateway.zh-CN.md))。模型配置里直接填写采样约定仍未实现。 +- **结构控制的类型(4.3)**:仍固定为深度。用现有的「视频抠像」「深度动捕」「蒙版合成」可以做出只有人物的深度视频,实测比姿态骨架更贴合动作,所以姿态的优先级可以降低。 +- **原版 H3 的结构控制**、**首帧模式下的指定帧**、**用关键帧统一首尾帧**。 +- 复制节点时 `pinnedFrames` 会改指向副本里的图片,图片不在副本里的时间被丢弃;删除或断开图片时同样丢弃。导入画布归档时是否保留未验证;重新从工程加载时按后端引用恢复。 +- 局部重绘工具只支持框选区域和时间段,不支持任意形状的遮罩。 + + +## 7. 界面 + +- **指定帧**:素材参考模式下,每张已连接的图片对应一个时间框;填了时间后,时间框下方提示这次生成按无损质量进行。 +- **潜空间接续**:对同一模型配置生成的视频选择「视频延长」,草稿的模式自动为「接续」;上传的、编辑过的或其他模型生成的视频保持「全能参考」。 +- **局部重绘**:「局部重拍」「视频编辑」「字幕擦除」在 FastH3-Omni 请求格式的模型上可用。 + +截图和操作录屏随合并请求 #541 提供,不放在仓库里。 + +## 8. 实测 + +2026-12-01,在 OpenDirector 里对自部署的「原版 MiniMax-H3 Ref2VA + Pika Flex Turbo 8 步 HD LoRA」服务(FastH3-Omni 请求格式)走完各项能力。素材是用 MiniMax-H3-Image 生成的一张造型图和两张姿势图。每项只跑了一两个种子,没有挑选:能说明功能通不通,不能说明质量高低。 + +| 能力 | 入口 | 结果 | +| --- | --- | --- | +| 指定帧 | 画布上的时间框;命令行 `video create --keyframe` | 钉在 1.25 秒和 4 秒的两帧与指定图片的 SSIM 约为 0.78 和 0.85–0.88,与另一张图片交叉比较约为 0.55 | +| 潜空间接续 | 「视频延长」,草稿为「接续」模式 | 服务端日志记录了 `continue_from` 和上一段的任务 ID,成片带音轨 | +| 视频编辑 | 框选画面上方 30%,重画成夜空 | 与源片段相比,框内 PSNR 约 10–13 dB,框外约 36 dB | +| 局部重拍 | 重拍第 2–4 秒 | 区间内 PSNR 约 17 dB,区间前后约 38 dB | +| 字幕擦除 | 烧入一行字幕的片段,默认的底部区域 | 两次里一次擦除干净,一次在原位置画出了新的乱码文字 | + +- 框选重绘跑两遍后,修改出现的时间仍随种子变化:逐帧看过的几次里,有从第 0 帧起就在的,有从第 2 帧起的,也有到约第 46 帧才出现的。 +- 字幕擦除在这组权重上还不可靠;它与另外两个工具共用同一个适配器,所以一并开放。 +- 结构控制的入口原本就有,这次没有重测。它的输出长度取不超过控制视频的最大 `17n+5` 帧,可能比控制视频短不到 0.7 秒。 diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 87de24eb1..b91586561 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -23,9 +23,10 @@ opendirector model show MiniMax-H3-Lite opendirector --project PROJECT_UUID asset import ./after.png --kind image opendirector --project PROJECT_UUID canvas add-material --asset ASSET_UUID --x 0 --y 0 opendirector --project PROJECT_UUID video create --model MODEL_CONFIG_UUID --prompt "人物缓缓转头" --duration 5 --first-frame SOURCE_CANVAS_ITEM_UUID +opendirector --project PROJECT_UUID video create --model MODEL_CONFIG_UUID --prompt "人物起舞" --duration 5 --reference-item COSTUME_ITEM_UUID --keyframe POSE_ITEM_UUID@1.25 ``` -`canvas add-material` 和 `video create` 通过必填的 `--x`、`--y` 明确创建位置。Agent 先读取画布对象的位置、尺寸及分组,再安排新元素布局。`video create` 创建可编辑的生成节点与参考关系,返回 `specId` 和 `itemId`。所有画布修改命令以及批量事务通过共用返回层提供 `canvasItems`,包含元素身份、版本、位置、尺寸、父级、坐标系及可见性。位置未变化的操作也返回目标元素的几何信息,供后续布局判断。几何信息读取失败时,回执保留已提交状态并返回 `geometryReadError`。模型可通过配置 UUID 或唯一匹配的完整模型名指定。重名配置返回候选 UUID 和端点,由调用者明确选择。模型的输入模式必须支持所选参数。`--reference-item` 支持重复指定参考节点。提交生成时使用创建回执中的对象版本,后台任务由服务端继续执行。 +`canvas add-material` 和 `video create` 通过必填的 `--x`、`--y` 明确创建位置。Agent 先读取画布对象的位置、尺寸及分组,再安排新元素布局。`video create` 创建可编辑的生成节点与参考关系,返回 `specId` 和 `itemId`。所有画布修改命令以及批量事务通过共用返回层提供 `canvasItems`,包含元素身份、版本、位置、尺寸、父级、坐标系及可见性。位置未变化的操作也返回目标元素的几何信息,供后续布局判断。几何信息读取失败时,回执保留已提交状态并返回 `geometryReadError`。模型可通过配置 UUID 或唯一匹配的完整模型名指定。重名配置返回候选 UUID 和端点,由调用者明确选择。模型的输入模式必须支持所选参数。`--reference-item` 支持重复指定参考节点。`--keyframe ITEM_UUID@秒数` 把一张图片节点固定到成片的该时间点,可重复指定;它只用于参考模式,需要模型的 `inputRules.maxKeyframes` 不为空,并且至少同时有一个 `--reference-item`。提交生成时使用创建回执中的对象版本,后台任务由服务端继续执行。 ### 画布坐标与分组 / Canvas coordinates and groups diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 9e406fdef..9fe1d001c 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -61,6 +61,15 @@ example vLLM's 4096 default) rejects every request with HTTP 400. For vLLM-Omni video connections, enter fractional seconds directly, for example `6.583333`. The CLI accepts `opendirector video create --duration 6.583333` together with the other required options. Read `opendirector video create --help` and `opendirector model list` first; `inputRules.fractionalDuration` identifies support, and each output's duration list defines the allowed range. H3 can align output to its supported frame count, so inspect the actual result duration before assembling segments. +Self-hosted H3 models add four ways to condition a video. Continue and keyframes work on native MiniMax-H3 and on models using the FastH3-Omni request shape; the other two are as noted: + +- **Continue**: generate a video with the model, choose **Extend** on it, and the next clip continues from where it ended, picture and sound. This only continues clips this same service generated and still holds; for an uploaded video, **Extend** opens in Universal reference mode with the video as a reference, on models that accept reference videos (the FastH3-Omni request shape does; native MiniMax-H3 does not). +- **Keyframes**: in Universal reference mode, each connected image shows a time box above the prompt. Give an image a time and the video shows that picture at that moment; leave it empty and the image stays an ordinary reference. Up to eight keyframes, each earlier than the end of the video and at least 1/24 second from the others (a keyframe is pinned to one frame), and at least one image or video must stay unpinned. Copying the node together with its pictures keeps the times. The CLI takes `opendirector video create --keyframe ITEM_UUID@SECONDS`. +- **Redraw part of a video**: **Partial reshoot**, **Video edit** and **Subtitle erasure** redraw a time span or a boxed region and keep the rest of the clip. On a model that uses the FastH3-Omni request format, a boxed redraw is generated twice to bring the change to the start of the clip, which takes about twice as long. The change can still arrive up to a couple of seconds into the clip; run the edit again if it does. +- **Structure control**: connect a depth video and choose structure control, as before. This needs a service started with the ControlNet weights and is available on the FastH3-Omni request shape. + +Structure control, continuation and keyframes cannot be combined in one generation. + To use few-step H3 adapters such as Pika Flex Turbo, which need a LoRA and their own step count on every request, or to offer several such variants from one vLLM-Omni server, see the [video gateway](video-gateway.md) that starts with OpenDirector. For detailed video settings, see [Video model capability configuration](video-model-capabilities.md). When no explicit output specification is provided, use **Auto** or **Service default duration**. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 6eec424b3..2d279e8d4 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -73,6 +73,15 @@ HTTP 400。 vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可使用 `opendirector video create --duration 6.583333` 并填写其余必需参数。先运行 `opendirector video create --help` 和 `opendirector model list`;`inputRules.fractionalDuration` 表示支持小数秒,各输出规格的时长列表定义允许范围。H3 可能按模型支持的帧数对齐,拼接分段前应核对结果的实际时长。 +自部署的 H3 模型提供四种条件生成方式。接续和关键帧在原版 MiniMax-H3 和使用 FastH3-Omni 请求格式的模型上都可用,另外两种见各条说明: + +- **接续**:用模型生成一段视频后,对它使用「延长」,下一段会从它结束的地方接着生成,画面和声音都连续。只能接续同一个服务生成、且服务仍保留着的片段;对上传的视频,「延长」以全能参考模式打开,把它当作参考视频;这需要模型接受参考视频(FastH3-Omni 请求格式接受,原版 MiniMax-H3 不接受)。 +- **指定帧**:在全能参考模式下,每张已连接的图片在提示词上方都有一个时间框。给图片填一个时间,生成的视频会在那一刻出现这个画面;留空则仍是普通参考。最多 8 个指定帧,时间须早于视频结束、彼此至少相隔 1/24 秒(每个指定帧钉在一帧上),并且至少留一张图片或一段视频不指定时间。连同图片一起复制节点时会保留这些时间。命令行使用 `opendirector video create --keyframe ITEM_UUID@SECONDS`。 +- **重画视频的一部分**:「局部重拍」「视频编辑」「字幕擦除」会重画某个时间段或框选区域,其余部分保持原样。使用 FastH3-Omni 请求格式的模型上,框选重绘会生成两遍,让修改尽量从片头就出现,耗时约为一遍的两倍。修改仍可能在开头一两秒之后才出现,遇到时可再执行一次。 +- **结构控制**:与此前相同,连接一段深度视频并选择结构控制。需要服务启动时加载 ControlNet 权重,适用于 FastH3-Omni 请求格式。 + +结构控制、接续和指定帧不能在同一次生成中同时使用。 + 使用 Pika Flex Turbo 等少步数 H3 适配器(每个请求都需要 LoRA 和对应的步数),或想用一个 vLLM-Omni 服务提供多个这样的变体时,参见随 OpenDirector 一起启动的[视频转发层](video-gateway.zh-CN.md)。 ## 制作第一支短片 diff --git a/docs/guides/video-model-capabilities.md b/docs/guides/video-model-capabilities.md index 72f436852..87dcc4aba 100644 --- a/docs/guides/video-model-capabilities.md +++ b/docs/guides/video-model-capabilities.md @@ -7,7 +7,7 @@ Generation history shows the requested video duration and the measured result du ## Interface 1. Open "Model connections", add or edit a video model, and fill in the base URL, Model ID and authentication. -2. Expand the collapsed "Video adapter" section for advanced settings. Choose the adapter for the `/videos` API. FastH3 uses eight steps and multi-asset references; each generation draws a new seed, keeps it with the job and reuses it when the job is recovered. FastH3 first/last frames (`fasth3_dual`) offers two generation modes on one model: its reference mode matches FastH3, while first/last-frame mode takes at most one first-frame and one last-frame anchor image, submits `fl2va` with `res_multistep` at 20 steps, and lands on the native 17n+5 frame grid, keeping the tail anchor at the grid's last frame instead of trimming to the requested duration. First/last-frame mode requires both anchors, rejects video and audio references, and is not combined with multi-asset references. Native H3 supports a first frame, asset references and continuation. The generic adapter sends only text and a single first frame, without H3 sampling parameters. When a model uses a custom name, choose the adapter explicitly. +2. Expand the collapsed "Video adapter" section for advanced settings. Choose the adapter for the `/videos` API. FastH3 uses eight steps and multi-asset references; each generation draws a new seed, keeps it with the job and reuses it when the job is recovered. It also continues a clip the same configuration generated, pins up to eight images at chosen times of the output as keyframes in reference mode, and provides the video-edit tools (Partial reshoot, Video edit, Subtitle erasure). FastH3 first/last frames (`fasth3_dual`) offers two generation modes on one model: its reference mode matches FastH3, while first/last-frame mode takes at most one first-frame and one last-frame anchor image, submits `fl2va` with `res_multistep` at 20 steps, and lands on the native 17n+5 frame grid, keeping the tail anchor at the grid's last frame instead of trimming to the requested duration. First/last-frame mode requires both anchors, rejects video and audio references, and is not combined with multi-asset references. Native H3 supports a first frame, asset references with keyframes, and continuation. The generic adapter sends only text and a single first frame, without H3 sampling parameters. When a model uses a custom name, choose the adapter explicitly. 3. Known models offer "Load adapter preset". Models without a declared capability show only "Auto" and "Service default duration". 4. Enable "Custom output specs" and fill in the resolution, supported durations and optional landscape pixel width and height for each tier. Durations accept `4-10,15`, meaning 4 to 10 seconds plus 15 seconds; tiers may declare different duration sets. 5. Set the default resolution, default duration and pixel alignment step, then save. Whether pixel sizes are required depends on the submitted parameters: adapters that send an explicit width and height need sizes, while adapters that send a resolution tier and let the service decide may leave them empty. Known H3 tiers may also use the adapter's built-in sizes. H3 aligns to 32 pixels and existing adapters stay within 4–15 seconds. diff --git a/docs/guides/video-model-capabilities.zh-CN.md b/docs/guides/video-model-capabilities.zh-CN.md index cbaafe47f..ff297edbb 100644 --- a/docs/guides/video-model-capabilities.zh-CN.md +++ b/docs/guides/video-model-capabilities.zh-CN.md @@ -7,7 +7,7 @@ ## 界面操作 1. 打开“模型接入”,添加或编辑视频模型,填写地址、Model ID 和鉴权信息。 -2. 点击默认折叠的“视频适配方式”展开高级配置。对 `/videos` 接口选择适配方式。FastH3 使用八步和多素材参考,每次生成使用新的随机种子并随任务保存,恢复任务时沿用;FastH3 首尾帧(`fasth3_dual`)在同一模型上提供两种生成方式:参考模式与 FastH3 相同,首尾帧模式最多使用首帧、尾帧两张锚点图片,按 `fl2va`、`res_multistep` 采样、20 步提交,帧数落在 17n+5 网格上,尾帧锚点保留原生网格最后一帧、不按所选时长裁剪;首尾帧模式必须同时提供首帧和尾帧,不接受视频或音频参考,也不与多素材参考同时使用。原生 H3 支持首帧、素材参考及接续;通用适配仅发送文本和单张首帧,不携带 H3 专属的采样参数。模型使用自定义名称时,应明确选择适配方式。 +2. 点击默认折叠的“视频适配方式”展开高级配置。对 `/videos` 接口选择适配方式。FastH3 使用八步和多素材参考,每次生成使用新的随机种子并随任务保存,恢复任务时沿用;它还支持接续同一配置生成的片段,在参考模式下把最多八张图片作为关键帧固定到成片的指定时间点,并提供视频编辑工具(局部重拍、视频编辑、字幕擦除);FastH3 首尾帧(`fasth3_dual`)在同一模型上提供两种生成方式:参考模式与 FastH3 相同,首尾帧模式最多使用首帧、尾帧两张锚点图片,按 `fl2va`、`res_multistep` 采样、20 步提交,帧数落在 17n+5 网格上,尾帧锚点保留原生网格最后一帧、不按所选时长裁剪;首尾帧模式必须同时提供首帧和尾帧,不接受视频或音频参考,也不与多素材参考同时使用。原生 H3 支持首帧、素材参考(含关键帧)及接续;通用适配仅发送文本和单张首帧,不携带 H3 专属的采样参数。模型使用自定义名称时,应明确选择适配方式。 3. 已知模型可点击“载入适配预设”。未声明能力的模型只显示“自动”和“服务默认时长”。 4. 开启“自定义输出规格”,每档填写分辨率、支持时长和可选横屏像素宽高。时长支持 `4-10,15`,即 4 至 10 秒以及 15 秒。不同档位可填写不同的时长集合。 5. 设置默认分辨率、默认时长和像素对齐步长,保存。是否需要填写像素尺寸取决于提交参数:发送明确宽高的适配需要配置尺寸;发送分辨率档位、由服务端确定宽高的适配可以留空。已知 H3 档位也可使用适配器内置的尺寸。H3 使用 32 像素对齐,现有适配仍限定 4–15 秒。 diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 00d698c47..98f2bdb40 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -125,7 +125,7 @@ def resolve_reference(snapshot, reference): asset = assets.get(ref.assetId) if asset is None or asset.fingerprint != ref.fingerprint: raise ContractError('reference_invalid', '参考素材不存在或内容已变化。', reference.id) - resolved.append(ResolvedReference(referenceId=reference.id, role=reference.role, asset=asset_ref(asset), + resolved.append(ResolvedReference(referenceId=reference.id, role=reference.role, frameTimeMs=reference.frameTimeMs, asset=asset_ref(asset), metadata=asset.metadata, sourceVersion=source_version, documentVersion=document_version, subjectRole=subject_role, name=asset.name, sourceTitle=source_title)) return resolved @@ -713,6 +713,8 @@ def _mutate(self, data, kind, payload): if any(other['id'] != old['id'] and other['active'] and (other['targetSpecId'], other['binding'], other['source']) == (ref['targetSpecId'], ref['binding'], ref['source']) for other in data['references']): raise ContractError('reference_invalid', '该参考来源已连接到目标配置。', payload.reference.id) old.update(ref) + if 'frameTimeMs' not in ref: + old.pop('frameTimeMs', None) if ref['binding'] == 'follow_current': source = self._get(data, 'canvas_item', ref['source']['id']) source_kind = source['kind'] diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 4a9f82c95..e5185e05a 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -162,7 +162,8 @@ def task(self, job): kind=spec.kind, status=job.status, phase=job.phase, recovery=job.recovery, resumeAllowed=job.resumeAllowed, modelConfigId=str(model.modelConfigId), model=model.modelId, baseURL=model.url, protocol=model.protocol, title=spec.prompt[:80] or spec.kind, prompt=prompt, promptContent=content, referenceIds=reference_ids, - referenceRoles=[{'assetId': str(r.asset.assetId), 'role': r.role} for r in job.inputSnapshot.references if r.transmission != 'context_only'], + referenceRoles=[{'assetId': str(r.asset.assetId), 'role': r.role} | ({'frameTimeMs': r.frameTimeMs} if r.frameTimeMs is not None else {}) + for r in job.inputSnapshot.references if r.transmission != 'context_only'], referenceInputs={'profile': profile}, videoMode=spec.parameters.videoMode if spec.kind == 'video' else 'first_frame', parameters=job.adapterParameters, externalTaskId=job.externalTaskId, assetId=str(job.asset.assetId) if job.asset else None, diff --git a/packages/core/src/opendirector/application/model_availability.py b/packages/core/src/opendirector/application/model_availability.py index 2fc4f352d..5675a4764 100644 --- a/packages/core/src/opendirector/application/model_availability.py +++ b/packages/core/src/opendirector/application/model_availability.py @@ -14,6 +14,7 @@ from opendirector.domain import capability_contract from opendirector.domain.image_inputs import image_input_policy from opendirector.domain.input_rules import input_rules +from opendirector.domain.rule_facts import keyframe_frame from opendirector.domain.request_constraints import INPUT_ROLES, constraint_failure, input_details, role_evidence from opendirector.domain.capability_messages import constraint_rejection from opendirector.domain.voices import effective_speech_voice @@ -74,7 +75,7 @@ def generation_request(config, spec, references, *, parameters=None): candidates = requests_for(config) if not candidates: return None - transmitted = [item for item in references if item.transmission == 'content'] + transmitted = [item for item in references if item.transmission == 'content' and getattr(item, 'role', None) != 'keyframe'] kinds = {item.asset.kind for item in transmitted} if spec.kind == 'image': profile = 'image_to_image' if 'image' in kinds else 'text_to_image' @@ -130,7 +131,10 @@ def generation_request(config, spec, references, *, parameters=None): actual = generation_capability_parameters(config, spec.kind, parameters, has_images='image' in kinds, video_mode=mode if spec.kind == 'video' else 'first_frame', has_audio='audio' in kinds, continue_size=(metadata.width, metadata.height) if metadata is not None else None, - frame_indices=frame_indices) if parameters is not None else {} + frame_indices=frame_indices, + guide_frames=[keyframe_frame(item.frameTimeMs) for item in references + if item.transmission == 'content' and getattr(item, 'role', None) == 'keyframe'], + ) if parameters is not None else {} if profile == 'text_to_speech': voice = effective_speech_voice(config, getattr(getattr(spec, 'parameters', None), 'voice', None)) counts['voice'] = 1 @@ -151,6 +155,8 @@ def tool_request(config, capability, *, actual=False): return request profile = request.profile roles = frozenset(capability_contract.required_roles_for(upstream_capability)) + if upstream_capability == 'video.edit' and input_rules(config)['profile'] == 'fasth3-omni': + roles |= {'reference_image'} request = replace(request, required_roles=roles) # These video tools always transmit the same input roles and counts, so # their directory entries can check those facts before a task is selected. @@ -163,6 +169,8 @@ def tool_request(config, capability, *, actual=False): inputs.add('image') elif profile == 'video_to_video': inputs.add('video') + if 'reference_image' in roles: + inputs.add('image') elif profile == 'lyrics_to_music': inputs.add('instructions') inputs.update(roles) diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 42b2b3ef8..40d6b1e9b 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -494,8 +494,8 @@ async def cutout_model(request): async def edit_model(request, submitted): config, adapter = frozen_model('video.edit') - return await self._model_call(task, 'video.edit', - lambda remember: adapter.edit_video(config, request, submitted=remember)) + return await adapter.edit_video(config, request, + remote_job=lambda run: self._model_call(task, 'video.edit', run)) async def segment_model(request): config, adapter = frozen_model('image.segment') diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index a59c2fdf0..a3a497ef6 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -756,16 +756,28 @@ def video_create(ctx: typer.Context, x: Annotated[float, typer.Option(help="Canvas X coordinate. Choose using the current item positions and sizes.")], y: Annotated[float, typer.Option(help="Canvas Y coordinate. Choose using the current item positions and sizes.")], first_frame: Annotated[UUID | None, typer.Option(help="Source image canvas item for first-frame mode.")] = None, - reference_item: Annotated[list[UUID] | None, typer.Option(help="Source canvas items for reference mode. Repeat for multiple inputs.")] = None): + reference_item: Annotated[list[UUID] | None, typer.Option(help="Source canvas items for reference mode. Repeat for multiple inputs.")] = None, + keyframe: Annotated[list[str] | None, typer.Option(help="Pin an image canvas item at a moment of the output, as ITEM_UUID@SECONDS (e.g. 3f2a...@1.25). Repeat for several keyframes. Needs reference mode, at least one --reference-item, and a model whose inputRules.maxKeyframes is set.")] = None): client = ctx.obj client.command = ctx.command_path config = select_model([value for value in client.models() if value["kind"] == "video"], model) - if first_frame and reference_item: - raise ProjectError("Choose --first-frame or --reference-item for the selected video mode.") + if first_frame and (reference_item or keyframe): + raise ProjectError("Choose --first-frame, or --reference-item with optional --keyframe, for the selected video mode.") + pinned = [] + for value in keyframe or []: + item, _, seconds = value.partition("@") + try: + pinned.append((UUID(item), round(float(seconds) * 1000))) + except (ValueError, OverflowError): + raise ProjectError(f"--keyframe expects ITEM_UUID@SECONDS, got {value!r}.") from None + if pinned[-1][1] < 0: + raise ProjectError("--keyframe time must not be negative.") + if pinned and not config["inputRules"].get("maxKeyframes"): + raise ProjectError("Selected model does not support keyframes (inputRules.maxKeyframes is not set).") allowed = config["inputRules"]["videoModes"] if first_frame: mode = "first_frame" - elif reference_item: + elif reference_item or pinned: mode = "reference" else: mode = allowed[0] @@ -783,6 +795,13 @@ def video_create(ctx: typer.Context, references.append({"id": str(uuid5(operation, f"reference-{index}")), "projectId": project_id, "targetSpecId": spec_id, "role": "first_frame" if first_frame else "reference", "order": index, "binding": "follow_current", "source": {"id": str(source_id)}}) + for source_id, milliseconds in pinned: + if not any(item["id"] == str(source_id) and item["kind"] == "image" for item in snapshot["canvasItems"]): + raise ProjectError(f"Keyframe canvas item {source_id} is not an image in this project.") + index = len(references) + references.append({"id": str(uuid5(operation, f"reference-{index}")), "projectId": project_id, + "targetSpecId": spec_id, "role": "keyframe", "frameTimeMs": milliseconds, + "order": index, "binding": "follow_current", "source": {"id": str(source_id)}}) receipt = client.execute("canvas.createGeneration", { "spec": {"id": spec_id, "projectId": project_id, "kind": "video", "purpose": "generation", "modelConfigId": config["id"], "prompt": prompt, diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 72dc22cef..b1ccad39a 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -506,6 +506,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'canvas_run_layout_group', 'canvas_run_layout_conflict', 'canvas_run_layout_extent', 'canvas_run_layout_shared_object', 'missing_object', 'reference_invalid', 'image_quality_unsupported', + 'keyframe_unsupported', 'keyframe_mode', 'keyframe_kind', 'keyframe_count', 'keyframe_needs_reference', 'keyframe_time', 'keyframe_image', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', 'kling_model', 'kling_mode', 'kling_image', 'kling_frames', 'kling_prompt', 'kling_aspect', 'kling_output', 'kling_cancel', diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 513c705e7..b0877872f 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -13,7 +13,7 @@ from opendirector.domain.generation import GenerationFailure, ResultCheck from opendirector.domain.projects import ProjectError from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, LYRICS_MAX_LENGTH, MAX_REFERENCES, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, KEYFRAME_FPS, keyframe_frame, LYRICS_MAX_LENGTH, MAX_REFERENCES, MUSIC_SECONDS_INITIAL, MUSIC_SECONDS_MAX, MUSIC_SECONDS_MIN, PROMPT_MAX_LENGTH, REFERENCE_MEDIA_SECONDS, STORED_VOICE_PATTERN, TEXT_DEFAULT_MAX_TOKENS, TEXT_MAX_TOKENS, duration_matches, effective_video_mode, generate_audio_options, prompt_optional_with_media, @@ -158,7 +158,9 @@ class FollowingSource(Contract): class ReferenceBase(ProjectEntity): targetSpecId: UUID = Field(description='Target generation configuration ID.') - role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(default='reference', description='Business role of this binding or reference.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control', 'keyframe'] = Field(default='reference', description='Business role of this binding or reference.') + frameTimeMs: int | None = Field(default=None, ge=0, strict=True, exclude_if=lambda value: value is None, + description='For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.') order: int = Field(default=0, ge=0, strict=True, description='Reference ordering within the target configuration.') active: bool = Field(default=True, description='Whether this reference participates in generation.') # Retained tombstone prevents revision ABA on undo. @@ -186,7 +188,9 @@ class FollowingReference(ReferenceBase): class ResolvedReference(Contract): referenceId: UUID = Field(description='Generation reference ID.') - role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control'] = Field(description='Business role of this binding or reference.') + role: Literal['reference', 'first_frame', 'last_frame', 'continuation', 'control', 'keyframe'] = Field(description='Business role of this binding or reference.') + frameTimeMs: int | None = Field(default=None, ge=0, exclude_if=lambda value: value is None, + description='For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.') asset: AssetRef = Field(description='Immutable asset version.') metadata: MediaMetadata = Field(description='Verified media properties.') sourceVersion: ObjectVersion | None = Field(default=None, description='Captured source object version.') @@ -382,6 +386,30 @@ def implicit_text_prompt(spec: GenerationSpec, references: tuple[ResolvedReferen ref.asset.kind == 'text' and ref.transmission == 'content' for ref in references) +def validate_keyframes(spec, rules, keyframes, *, has_reference): + if not rules.maxKeyframes: + raise ProjectError('当前模型不支持指定帧生成,请移除关键帧或更换模型。', 422, code='keyframe_unsupported') + if spec.parameters.videoMode != 'reference': + raise ProjectError('关键帧只能用于素材参考模式,不能与首尾帧、接续或结构控制同时使用。', 422, code='keyframe_mode') + if any(ref.asset.kind != 'image' for ref in keyframes): + raise ProjectError('关键帧必须是图片。', 422, code='keyframe_kind') + if len(keyframes) > rules.maxKeyframes: + raise ProjectError(f'最多指定 {rules.maxKeyframes} 个关键帧,当前为 {len(keyframes)} 个。', 422, code='keyframe_count') + if not has_reference: + raise ProjectError('指定帧生成还需要至少一张普通参考图片或一段参考视频。', 422, code='keyframe_needs_reference') + seconds = spec.parameters.durationSeconds + times = [ref.frameTimeMs for ref in keyframes] + if any(value is None for value in times): + raise ProjectError('每个关键帧都需要指定时间点。', 422, code='keyframe_time') + if seconds is None: + raise ProjectError('指定关键帧时需要先设置视频时长。', 422, code='keyframe_time') + frames = [keyframe_frame(value) for value in times] + if any(frame >= round(seconds * KEYFRAME_FPS) for frame in frames): + raise ProjectError(f'关键帧的时间点必须早于视频结束({seconds:g} 秒)。', 422, code='keyframe_time') + if len(set(frames)) != len(frames): + raise ProjectError('两个关键帧不能落在同一帧上,请把时间点至少错开 1/24 秒。', 422, code='keyframe_time') + + def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, references: tuple[ResolvedReference, ...] = (), *, submitting: bool = False): """Pure shared validation; it never submits, uploads or changes a project.""" @@ -422,8 +450,10 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc unique([(ref.referenceId, ref.asset.assetId) for ref in references], 'resolved reference assets') if spec.promptContent and any(isinstance(part, PromptReference) and part.referenceId not in {ref.referenceId for ref in references} for part in spec.promptContent): raise ValueError('提示词引用了未解析的参考素材。') + keyframes = [ref for ref in references if ref.role == 'keyframe'] + references = tuple(ref for ref in references if ref not in keyframes) transmitted = [ref for ref in references if ref.role != 'continuation' and ref.transmission != 'context_only'] - if sum(ref.metadata.size for ref in transmitted) > rules.requestBytes: + if sum(ref.metadata.size for ref in (*transmitted, *keyframes)) > rules.requestBytes: raise ValueError('参考素材总大小超过模型请求上限。') for ref in transmitted: limit = (rules.imageBytes if ref.asset.kind == 'image' else rules.videoBytes if ref.asset.kind == 'video' @@ -464,9 +494,11 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if spec.kind == 'audio' and spec.promptContent is not None and not any(part.type == 'text' and part.text.strip() for part in spec.promptContent): raise ValueError('语音生成需要实际文本,不能只使用参考标签。') if spec.kind != 'video': - if any(ref.role != 'reference' for ref in references): + if keyframes or any(ref.role != 'reference' for ref in references): raise ValueError('首尾帧和续写参考只能用于视频生成。') return + if keyframes: + validate_keyframes(spec, rules, keyframes, has_reference=any(ref.asset.kind in {'image', 'video'} for ref in transmitted)) params = spec.parameters if rules.profile == 'minimax-h3-official': if model.modelId not in MINIMAX_MODELS: diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 6897ff9f5..cd72c26af 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -63,6 +63,8 @@ class InputRules(Contract): maxImages: Count = Field(description='Maximum reference image count.') maxVideos: Count = Field(description='Maximum reference video count.') maxAudios: Count = Field(description='Maximum reference audio count.') + maxKeyframes: Count = Field(default=0, exclude_if=lambda value: not value, + description='Maximum pictures that can be pinned at chosen moments of a generated video; omitted when unsupported.') imageBytes: Count = Field(description='Maximum bytes per reference image.') videoBytes: Count = Field(description='Maximum bytes per reference video.') audioBytes: Count | None = Field(default=None, exclude_if=lambda value: value is None, diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index eaa230f88..3d5e4e0a8 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -139,11 +139,13 @@ def project_relations(self): source = items.get(reference.source.id) if source is None or source.kind not in {'text', 'image', 'video', 'audio', 'subject'}: raise ValueError('Following reference needs a stable logical media source') - if reference.role == 'first_frame' and source.kind != 'image' or reference.role in {'continuation', 'control'} and source.kind != 'video': + if reference.role in {'first_frame', 'keyframe'} and source.kind != 'image' or reference.role in {'continuation', 'control'} and source.kind != 'video': raise ValueError('Reference source kind does not match its role') - elif ((reference.role == 'first_frame' and reference.source.kind != 'image') + elif ((reference.role in {'first_frame', 'keyframe'} and reference.source.kind != 'image') or (reference.role in {'continuation', 'control'} and reference.source.kind != 'video')): raise ValueError('Reference source kind does not match its role') + if (reference.frameTimeMs is not None) != (reference.role == 'keyframe') and reference.active: + raise ValueError('frameTimeMs is set exactly on keyframe references') for spec in self.generationSpecs: if spec.promptContent: for part in spec.promptContent: diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index ac5ada2e7..b5889807a 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -13,6 +13,7 @@ from .zhipu_speech import ZHIPU_DEFAULT_VOICE, ZHIPU_SPEECH_CHARACTERS, is_zhipu_speech VideoMode = Literal['first_frame', 'reference', 'continuation'] +H3_KEYFRAMES = 8 def _adapter_rules(config): @@ -112,14 +113,15 @@ def _adapter_rules(config): # references) stays zero. rules.update(profile='vllm-omni-h3', allowedKinds=['text', 'image', 'video', 'audio'], maxImages=9, maxAudios=3, imageBytes=30 * 1024 * 1024, requestBytes=64 * 1024 * 1024, videoModes=['first_frame', 'reference', 'continuation'], - outputResolutions=['480P', '768P']) + outputResolutions=['480P', '768P'], maxKeyframes=H3_KEYFRAMES) return rules if kind == 'video' and config.get('protocol') == 'vllm_omni' and adapter in {'fasth3', 'fasth3_dual'}: rules.update(profile='fasth3-omni', allowedKinds=['text', 'image', 'video', 'audio'], maxImages=9, maxVideos=3, maxAudios=3, imageBytes=30 * 1024 * 1024, - requestBytes=160 * 1024 * 1024, videoModes=['reference', 'control'], outputResolutions=['480P', '768P']) + requestBytes=160 * 1024 * 1024, videoModes=['reference', 'control', 'continuation'], + outputResolutions=['480P', '768P'], maxKeyframes=H3_KEYFRAMES) if adapter == 'fasth3_dual': - rules.update(videoModes=['reference', 'first_frame', 'control'], frameRoles=['first_frame', 'last_frame']) + rules.update(videoModes=['reference', 'first_frame', 'control', 'continuation'], frameRoles=['first_frame', 'last_frame']) return rules if kind == 'video' and config.get('protocol') == 'vllm_omni': rules.update(profile='standard-video', maxImages=1, videoModes=['first_frame']) diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 4ee1fd661..01ad9ee2f 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -42,6 +42,7 @@ MUSIC_SECONDS_INITIAL = 30 REFERENCE_MEDIA_SECONDS = 15 FASTH3_MEDIA_REFERENCE_LIMIT = 12 +KEYFRAME_FPS = 24 # FastH3 structure control: the control video sets the output length (long_video_mode=full up to 30 s). CONTROL_VIDEO_SECONDS = (4, 30) # Identifiers sent to a speech adapter. Stored specs may also keep a Unicode @@ -77,6 +78,7 @@ def facts_payload(): 'musicSecondsInitial': MUSIC_SECONDS_INITIAL, 'referenceMediaSeconds': REFERENCE_MEDIA_SECONDS, 'fasth3MediaReferenceLimit': FASTH3_MEDIA_REFERENCE_LIMIT, + 'keyframeFps': KEYFRAME_FPS, 'controlVideoSeconds': list(CONTROL_VIDEO_SECONDS), 'serviceVoicePattern': SERVICE_VOICE_PATTERN, 'storedVoicePattern': STORED_VOICE_PATTERN, @@ -477,3 +479,7 @@ def typescript_module(): facts = json.dumps(facts_payload(), ensure_ascii=False, indent=2) vectors = json.dumps(derivation_vectors(), ensure_ascii=False, indent=2) return _TYPESCRIPT.replace('__FACTS__', facts).replace('__VECTORS__', vectors) + + +def keyframe_frame(milliseconds: int) -> int: + return round(milliseconds * KEYFRAME_FPS / 1000) diff --git a/packages/core/src/opendirector/integrations/fasth3.py b/packages/core/src/opendirector/integrations/fasth3.py index 8e8fb58c6..4a46d8bc4 100644 --- a/packages/core/src/opendirector/integrations/fasth3.py +++ b/packages/core/src/opendirector/integrations/fasth3.py @@ -6,7 +6,7 @@ from opendirector.domain.references import project_content -def generation_fields(parameters, *, frame_indices=None): +def generation_fields(parameters, *, frame_indices=None, continue_from=None, continue_size=None): """Prepare the same FastH3 fields for capability checks and HTTP submission.""" from opendirector.integrations.vllm_omni import FPS, video_frame_parameters fields = {} @@ -26,6 +26,11 @@ def generation_fields(parameters, *, frame_indices=None): steps = parameters.get('num_inference_steps', 20) fields.update(size=parameters.get('size', '832x480'), num_inference_steps=steps, guidance_scale=1, fps=24, seed=parameters.get('seed', 1234)) + if continue_from is not None: + extra['continue_from'] = continue_from + width, height = continue_size or (None, None) + if width and height: + fields['size'] = f'{width}x{height}' return fields, extra diff --git a/packages/core/src/opendirector/integrations/generation_capability_parameters.py b/packages/core/src/opendirector/integrations/generation_capability_parameters.py index f8de030ba..3e32f085a 100644 --- a/packages/core/src/opendirector/integrations/generation_capability_parameters.py +++ b/packages/core/src/opendirector/integrations/generation_capability_parameters.py @@ -9,7 +9,8 @@ def generation_capability_parameters(config, kind, parameters, *, has_images=False, - video_mode='first_frame', has_audio=False, continue_size=None, frame_indices=None): + video_mode='first_frame', has_audio=False, continue_size=None, frame_indices=None, + guide_frames=()): profile = input_rules(config)['profile'] if kind == 'image': size = parameters.get('size', '') @@ -48,13 +49,15 @@ def generation_capability_parameters(config, kind, parameters, *, has_images=Fal result['voice'] = effective_speech_voice(config, parameters.get('voice')) elif kind == 'video': if profile == 'vllm-omni-h3': - from opendirector.integrations.vllm_omni import capability_parameters, generation_fields + from opendirector.integrations.vllm_omni import capability_parameters, generation_fields, timeline_guide_fields result = capability_parameters(*generation_fields(parameters, video_mode, has_images=has_images, has_audio=has_audio, continue_size=continue_size)) + result.update(timeline_guide_fields(guide_frames)) elif profile == 'fasth3-omni': from opendirector.integrations.fasth3 import generation_fields - fields, extra = generation_fields(parameters, frame_indices=frame_indices) - result = {**fields, **extra} + from opendirector.integrations.vllm_omni import timeline_guide_fields + fields, extra = generation_fields(parameters, frame_indices=frame_indices, continue_size=continue_size) + result = {**fields, **extra, **timeline_guide_fields(guide_frames)} else: result = {key: parameters[key] for key in ('size',) if key in parameters} if 'duration' in parameters: diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index 560269231..ecfa09437 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -129,7 +129,7 @@ async def cutout(self, config, request: CutoutRequest) -> MediaResult: async def video(self, config, request: VideoRequest, *, submitted=None) -> MediaResult: raise ProjectError('所选模型不支持视频生成。', 409) - async def edit_video(self, config, request: VideoEditRequest, *, submitted=None) -> MediaResult: + async def edit_video(self, config, request: VideoEditRequest, *, remote_job=None) -> MediaResult: raise ProjectError('所选模型不支持视频局部重绘。', 409) async def cancel_video(self, config, external_id): @@ -649,6 +649,11 @@ def sound_mask(cls, mask: EditMask | None, frames: int): start, end = mask.start or 0, mask.end if mask.end is not None else seconds return [mask.level if start <= index * seconds / steps < end else 0.0 for index in range(steps)] + async def _remote_job(self, remote_job, config, fields, files): + async def run(submitted=None): + return await self._job(config, fields, files, submitted) + return await (remote_job(run) if remote_job else run()) + async def _job(self, config, fields, files, submitted): headers, secrets = auth_headers(config), (config.get('apiKey', ''),) base = endpoint(config['url'], '/videos') @@ -723,7 +728,7 @@ def _conformed(cls, data, width, height): with media.Workspace() as work: return media.conform(work.write('in.mp4', data), work.path / 'out.mp4', width=width, height=height, fps=cls.FPS).read_bytes() - async def edit_video(self, config, request: VideoEditRequest, *, submitted=None) -> MediaResult: + async def edit_video(self, config, request: VideoEditRequest, *, remote_job=None) -> MediaResult: values, extra = self.edit_parameters(request.seconds, request.width, request.height) frames = values['num_frames'] width, height = map(int, values['size'].split('x')) @@ -732,7 +737,7 @@ async def edit_video(self, config, request: VideoEditRequest, *, submitted=None) files = [('source_video', ('source.mp4', source, 'video/mp4')), ('video_noise_mask', ('video-mask.json', json.dumps(self.picture_mask(request.picture, frames)).encode(), 'application/json')), ('audio_noise_mask', ('audio-mask.json', json.dumps(self.sound_mask(request.sound, frames)).encode(), 'application/json'))] - return await self._job(config, fields, files, submitted) + return await self._remote_job(remote_job, config, fields, files) async def cancel_video(self, config, external_id): async def work(): @@ -762,6 +767,56 @@ async def work(): return await _call('poll', work) +class FastH3VideoEdit(VllmOmniVideo): + + capabilities = frozenset({'video.edit'}) + + @classmethod + def edit_parameters(cls, seconds, width, height): + values, _ = super().edit_parameters(seconds, width, height) + return {**values, 'num_inference_steps': 8, 'guidance_scale': 1}, {'task': 'ref2va', 'audio_flow_shift': 3} + + @classmethod + def _last_edited_frame(cls, data, end: float | None): + with media.Workspace() as work: + path = work.write('in.mp4', data) + moment = media.last_frame_time(path) + if end is not None: + moment = min(end - 1 / cls.FPS, moment) + return media.frame_at(path, max(moment - 0.5 / cls.FPS, 0.0), work.path / 'frame.png') + + @classmethod + def _source_still(cls, data, mask: EditMask | None): + with media.Workspace() as work: + path = work.write('in.mp4', data) + moment = 0.0 + if mask is not None and mask.region is None and not mask.start and mask.end is not None: + kept = math.ceil(mask.end * cls.FPS - 1e-6) + if kept <= round(media.last_frame_time(path) * cls.FPS): + moment = max(kept - 0.5, 0.0) / cls.FPS + return media.frame_at(path, moment, work.path / 'frame.png') + + async def edit_video(self, config, request: VideoEditRequest, *, remote_job=None) -> MediaResult: + values, extra = self.edit_parameters(request.seconds, request.width, request.height) + frames = values['num_frames'] + width, height = map(int, values['size'].split('x')) + source = await blocking(self._conformed, request.source, width, height) + fields = self._fields(config, ' ' + request.prompt, values, extra) + masks = [('video_noise_mask', ('video-mask.json', json.dumps(self.picture_mask(request.picture, frames)).encode(), 'application/json')), + ('audio_noise_mask', ('audio-mask.json', json.dumps(self.sound_mask(request.sound, frames)).encode(), 'application/json'))] + + async def redraw(still): + files = [('input_references', ('reference.png', still, 'image/png')), ('source_video', ('source.mp4', source, 'video/mp4')), *masks] + return await self._remote_job(remote_job, config, fields, files) + + still = await blocking(self._source_still, source, request.picture) + mask = request.picture + if mask is not None and mask.region is not None: + draft = await redraw(still) + still = await blocking(self._last_edited_frame, draft.data, mask.end) + return await redraw(still) + + class OpenAISpeech(ModelAdapter): """OpenAI-compatible /audio/speech (also served by vLLM-Omni TTS).""" @@ -983,6 +1038,8 @@ def adapter_for(config, transport=None, poll_interval=3, *, image_policy=None, l return OpenAIImages(transport, poll_interval, **image_options) if kind == 'video' and profile == 'vllm-omni-h3': return VllmOmniVideo(transport, poll_interval) + if kind == 'video' and profile == 'fasth3-omni': + return FastH3VideoEdit(transport, poll_interval) if kind == 'audio' and profile == 'vllm-omni-music': return VllmOmniMusic(transport, poll_interval) if kind == 'audio' and protocol in {'openai', 'vllm_omni'}: diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index da687d58f..4c9eacbe4 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -20,7 +20,7 @@ from opendirector.integrations.kling_video import KlingVideoGeneration from opendirector.integrations.higgsfield_open import HiggsfieldOpenGeneration from opendirector.integrations.bigmodel_video import BigModelVideoGeneration -from opendirector.integrations.vllm_omni import VllmOmniGeneration, _upload +from opendirector.integrations.vllm_omni import VllmOmniGeneration, _continuation_failure, _missing_latents, _upload, continuation_rejection, timeline_guide_parts from opendirector.integrations.fasth3 import generation_fields as fasth3_generation_fields from opendirector.integrations.vllm_omni_image import VllmOmniImageGeneration from opendirector.integrations.model_adapters import (BigModelImages, MinimaxH3Images, MinimaxSpeech, MossImages, MossSpeech, OpenAISpeech, @@ -83,10 +83,12 @@ def validate(self, kind, config): if kind == 'video' and config.get('protocol') != 'vllm_omni': raise ProjectError('视频模型请选择 vLLM-Omni 视频接口。') - async def _json(self, client, method, url, config, **kwargs): + async def _json(self, client, method, url, config, *, continuation=False, **kwargs): if kwargs.get('files'): kwargs['extensions'] = {'model_parameters': {'fields': kwargs.get('data'), 'file_count': len(kwargs['files'])}} async with client.stream(method, url, headers=auth_headers(config), **kwargs) as response: + if continuation and response.status_code == 400: + await continuation_rejection(response, 'submit', (config.get('apiKey', ''),)) await checked(response, stage='poll' if method == 'GET' else 'submit', secrets=(config.get('apiKey', ''),)) data = bytearray() async for chunk in response.aiter_bytes(): @@ -186,7 +188,15 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery files = [('input_references', _upload(image, 'first_frame' if index == 0 else 'last_frame')) for index, image in zip(frame_indices, prepared['images'], strict=True)] else: + continuing = task.get('videoMode') == 'continuation' + roles = {} + for value in task.get('referenceRoles') or []: + roles.setdefault(str(value['assetId']), set()).add(value['role']) for data, meta, source_kind in references(self.store, task['projectId'], task['referenceIds']): + if continuing and source_kind == 'video': + continue + if roles.get(str(meta['id'])) == {'keyframe'}: + continue if fast and str(meta['id']) == str(prepared.get('control')): # FastH3 + ControlNet: the structure video conditions every frame, not as a reference clip. files.append(('control_reference', (meta['name'], data, meta['type']))) @@ -201,11 +211,16 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery form['seconds'] = str(int(seconds)) if float(seconds).is_integer() else str(seconds) if 'size' in parameters: form['size'] = parameters['size'] if fast: - values, extra = fasth3_generation_fields(parameters, frame_indices=frame_indices) + values, extra = fasth3_generation_fields(parameters, frame_indices=frame_indices, + continue_from=prepared.get('continueFrom'), continue_size=prepared.get('continueSize')) form.update({key: str(value) for key, value in values.items()}) form['extra_params'] = json.dumps(extra) + guide_fields, guide_files = timeline_guide_parts(prepared) + form.update(guide_fields) + files.extend(guide_files) # Force multipart even for an empty reference list. - value = await self._json(client, 'POST', url, config, data=form, files=files or {'_multipart': (None, '1')}) + value = await self._json(client, 'POST', url, config, data=form, files=files or {'_multipart': (None, '1')}, + continuation=bool(prepared.get('continueFrom'))) external_id = value['id'] if not isinstance(external_id, str) or not external_id or len(external_id) > 200: raise protocol_failure(stage) @@ -221,6 +236,8 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery await result_ready('mp4', content_url) return await self.resume_result(config, 'mp4', content_url) if value.get('status') in {'failed', 'cancelled', 'expired'}: + if value.get('status') == 'failed' and task.get('videoMode') == 'continuation' and _missing_latents(value): + raise _continuation_failure('poll') raise provider_failure(value, stage='poll', http_status=200, secrets=secrets) if value.get('status') not in {'queued', 'in_progress', 'running'}: raise protocol_failure('poll') diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 08fef8e84..1bb9c3af1 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,7 +5,7 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, keyframe_frame, ) from opendirector.domain.projects import ProjectError from opendirector.domain.minimax_image import validate_minimax_image_reference @@ -102,7 +102,7 @@ def generation_references(store, task, config, *, complete=True, overrides=None) rules = input_rules({**config, 'kind': 'agent' if kind == 'text' else kind}) mode = task.get('videoMode', 'first_frame') prompt = project_content(task['promptContent'], speech=kind == 'audio')[0] if task.get('promptContent') is not None else task['prompt'] - result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None} + result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': []} if kind == 'text': result['content'] = reference_content(store, task['projectId'], {'text': task['prompt'], 'content': task.get('promptContent'), 'assets': [{'id': asset_id} for asset_id in task['referenceIds']]}, manifest=result['manifest'], overrides=overrides) request_size(result['content'], rules['requestBytes']) @@ -119,7 +119,7 @@ def generation_references(store, task, config, *, complete=True, overrides=None) for _, meta, source_kind in references(store, task['projectId'], task['referenceIds'], overrides)] return result if kind == 'video' and mode not in rules['videoModes']: - raise ProjectError('当前模型不支持接续生成,请选择 vLLM-Omni MiniMax-H3。' if mode == 'continuation' + raise ProjectError('当前模型不支持接续生成,请选择支持接续的 MiniMax-H3 模型。' if mode == 'continuation' else '当前模型接口尚未接通素材参考模式,请选择该模型支持的生成方式。') dual_frames = kind == 'video' and mode == 'first_frame' and config.get('videoAdapter') == 'fasth3_dual' total_audio_ms, total_video_ms, media_bytes = 0, 0, 0 @@ -174,6 +174,23 @@ def generation_references(store, task, config, *, complete=True, overrides=None) text_context.append(context) entry['role'] = 'text' elif source_kind == 'image': + asset_roles = [value for value in task.get('referenceRoles') or [] if str(value['assetId']) == str(meta['id'])] + pinned = [value['frameTimeMs'] for value in asset_roles if value['role'] == 'keyframe'] + if pinned: + if not (kind == 'video' and mode == 'reference' and rules.get('maxKeyframes')): + raise ProjectError('当前模型或生成模式不支持指定帧生成,请移除关键帧。', 422, code='keyframe_unsupported') + guide_mime = image_type(data) + if guide_mime not in {'image/png', 'image/jpeg', 'image/webp'} or len(data) > rules['imageBytes']: + raise ProjectError(f'“{meta["name"]}”不能作为关键帧:需为不超过大小限制的 PNG、JPEG 或 WEBP 图片。', 422, code='keyframe_image') + for milliseconds in pinned: + result['guides'].append({'assetId': str(meta['id']), 'name': meta['name'], 'data': data, 'mime': guide_mime, + 'frame': keyframe_frame(milliseconds)}) + result['manifest'].append({**entry, 'role': 'keyframe', 'frameTimeMs': milliseconds}) + if all(value['role'] == 'keyframe' for value in asset_roles): + media_bytes += len(data) * (len(pinned) - 1) + source_metadata.pop() + continue + media_bytes += len(data) * len(pinned) mime = image_type(data) if rules['profile'] == 'minimax-h3-image': mime = mime or heif_type(data) @@ -260,6 +277,9 @@ def generation_references(store, task, config, *, complete=True, overrides=None) raise ProjectError('结构控制需要连接一个控制视频(例如人物深度视频)。') if complete and mode == 'continuation' and not result['continueFrom']: raise ProjectError('接续生成需要引用上一段由 vLLM-Omni H3 生成的视频。') + result['guides'].sort(key=lambda guide: guide['frame']) + if len(result['guides']) > rules.get('maxKeyframes', 0): + raise ProjectError(f'最多指定 {rules.get("maxKeyframes", 0)} 个关键帧。', 422, code='keyframe_count') if len(result['videos']) > rules.get('maxVideos', 0) or total_video_ms > REFERENCE_MEDIA_SECONDS * 1000: raise ProjectError(f'视频参考最多 3 段,总时长不超过 {REFERENCE_MEDIA_SECONDS} 秒。') if rules['profile'] == 'fasth3-omni' and len(result['images']) + len(result['videos']) + len(result['audios']) > FASTH3_MEDIA_REFERENCE_LIMIT: @@ -279,5 +299,6 @@ def generation_references(store, task, config, *, complete=True, overrides=None) validate_moss_image_prompt(result['prompt']) if len(result['prompt']) > 20000: raise ProjectError('正文及文本参考超过当前生成长度限制,请缩短后重试。') - request_size({key: result[key] for key in ('prompt', 'images', 'audios', 'videos')}, rules['requestBytes'] - 4096) + guide_bytes = sum(4 * ((len(guide['data']) + 2) // 3) for guide in result['guides']) + request_size({key: result[key] for key in ('prompt', 'images', 'audios', 'videos')}, rules['requestBytes'] - 4096 - guide_bytes) return result diff --git a/packages/core/src/opendirector/integrations/vllm_omni.py b/packages/core/src/opendirector/integrations/vllm_omni.py index 1b974a105..cd8ce528c 100644 --- a/packages/core/src/opendirector/integrations/vllm_omni.py +++ b/packages/core/src/opendirector/integrations/vllm_omni.py @@ -62,6 +62,19 @@ def capability_parameters(fields, extra): return result +def timeline_guide_fields(frames): + if not frames: + return {} + manifest = [{'frame_index': frame, 'image': {'upload_index': index}} for index, frame in enumerate(frames)] + return {'timeline_guides': json.dumps(manifest), 'quality': 'lossless'} + + +def timeline_guide_parts(prepared): + guides = prepared.get('guides') or [] + files = [('guide_files', (guide['name'], guide['data'], guide['mime'])) for guide in guides] + return timeline_guide_fields([guide['frame'] for guide in guides]), files + + def _upload(data_uri, name): header, payload = data_uri.split(',', 1) mime = header.removeprefix('data:').split(';', 1)[0] @@ -80,6 +93,20 @@ def _continuation_failure(stage): suggestion='请重新生成上一段视频后再接续,或改用首帧/素材参考模式;当前输入已保留。'), 409) +async def continuation_rejection(response, stage, secrets): + body = bytearray() + async for chunk in response.aiter_bytes(): + body.extend(chunk[:max(0, 65536 - len(body))]) + if len(body) >= 65536: + break + try: + value = json.loads(body) + except (ValueError, UnicodeError): + value = None + raise _continuation_failure(stage) if _missing_latents(value) else provider_failure( + value, stage=stage, headers=response.headers, http_status=400, secrets=secrets) + + class VllmOmniGeneration: def __init__(self, store, transport=None, poll_interval=3): self.store, self.transport, self.poll_interval = store, transport, poll_interval @@ -107,6 +134,9 @@ def form(self, config, task, prepared): prepared = {**prepared, 'images': []} files.extend(('input_references', _upload(image, f'image_{index}')) for index, image in enumerate(prepared['images'], 1)) files.extend(('input_references', _upload(audio, f'audio_{index}')) for index, audio in enumerate(prepared['audios'], 1)) + guide_fields, guide_files = timeline_guide_parts(prepared) + fields.update(guide_fields) + files.extend(guide_files) fields['extra_params'] = json.dumps(extra) return fields, files @@ -126,9 +156,7 @@ async def generate(self, config, task, submitted, *, result_ready=None): parts = [(name, (None, value)) for name, value in fields.items()] + files async with client.stream('POST', base, headers=headers, files=parts, extensions={'model_parameters': {'fields': fields, 'file_count': len(files)}}) as response: if response.status_code == 400 and task.get('videoMode') == 'continuation': - value = json.loads(await response.aread()) - raise _continuation_failure(stage) if _missing_latents(value) else provider_failure( - value, stage=stage, headers=response.headers, http_status=400, secrets=secrets) + await continuation_rejection(response, stage, secrets) external_id = json.loads(await bounded(response, stage=stage, secrets=secrets))['id'] if not isinstance(external_id, str) or not external_id or len(external_id) > 200: raise protocol_failure(stage) diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index f901d942b..6cd9be5b7 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -152,6 +152,15 @@ def frame_at(path: Path, seconds: float, out: Path) -> bytes: return out.read_bytes() +def last_frame_time(path: Path) -> float: + value = json.loads(_run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-count_packets', + '-show_entries', 'stream=nb_read_packets,r_frame_rate', '-of', 'json', str(path)], timeout=60)) + picture = (value.get('streams') or [{}])[0] + numerator, _, denominator = (picture.get('r_frame_rate') or '24/1').partition('/') + fps = float(numerator) / float(denominator or 1) if float(denominator or 1) else 24.0 + return max(int(picture.get('nb_read_packets') or 1) - 1, 0) / (fps or 24.0) + + def _normalized(source: Path, out: Path, info: dict, *, start=None, end=None): """One segment re-encoded to the reference size, rate and stereo AAC (silence when missing).""" width, height, fps = info['width'] - info['width'] % 2, info['height'] - info['height'] % 2, info['fps'] diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index 373db6884..fdf3602f8 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -36,7 +36,7 @@ import { mediaBlobDataUrl } from "../canvas/localMediaRuntime.ts"; import { generationContentPatch } from "../canvas/generationReferenceContent.ts"; import { assemblyResource, staleAssembly } from "../canvas/editorAssembly.ts"; import { RULE_FACTS } from "../contracts/ruleFacts.generated.ts"; -import { canvasReferenceRole, MUSIC_SECONDS } from "./rules.ts"; +import { canvasReferenceFrameTime, canvasReferenceRole, MUSIC_SECONDS } from "./rules.ts"; import { assetReference, CreationClient, @@ -879,6 +879,15 @@ export class CreationProjection { ? "lastFrameNodeId" : "firstFrameNodeId" ] = frame.source.id; + const pinned = currentReferences.flatMap((ref) => + ref.targetSpecId === spec.id && + ref.role === "keyframe" && + ref.binding === "follow_current" && + typeof ref.frameTimeMs === "number" + ? [{ nodeId: ref.source.id, seconds: ref.frameTimeMs / 1000 }] + : [], + ); + if (pinned.length) node.data.settings.pinnedFrames = pinned; } const selected = snapshot.results.find( (r) => r.id === spec.currentResultId, @@ -1892,11 +1901,15 @@ export class CreationProjection { ? items.get(ref.source.id)?.kind : ref.source.kind; const role = canvasReferenceRole(settings, sourceKind, ref); - if (role !== ref.role) { + const frameTimeMs = canvasReferenceFrameTime(settings, sourceKind, ref); + if (role !== ref.role || (frameTimeMs ?? null) !== (ref.frameTimeMs ?? null)) { expect("reference", ref); + const { frameTimeMs: _previous, ...rest } = ref; operations.push({ type: "reference.update", - payload: { reference: { ...ref, role } }, + payload: { + reference: { ...rest, role, ...(frameTimeMs !== undefined ? { frameTimeMs } : {}) }, + }, }); } } @@ -1913,9 +1926,13 @@ export class CreationProjection { ?.type ?? items.get(ref.source.id)?.kind) : ref.source.kind; const role = canvasReferenceRole(settings, sourceKind, ref); + const frameTimeMs = canvasReferenceFrameTime(settings, sourceKind, ref); + const { frameTimeMs: _previous, ...rest } = ref; operations[index] = { type: op.type, - payload: { reference: { ...ref, role } }, + payload: { + reference: { ...rest, role, ...(frameTimeMs !== undefined ? { frameTimeMs } : {}) }, + }, }; } } diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 5da816653..cea000706 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -47,6 +47,7 @@ export interface InputRules { audioBytes?: number | null; referenceMediaMinSeconds?: number | null; referenceMediaSeconds?: number | null; + maxKeyframes?: number; requestBytes?: number; maxPromptCharacters?: number | null; voiceRequired?: boolean | null; @@ -99,7 +100,8 @@ export interface ModelConfig { export interface BackendReference { node: CanvasNode; - role: "reference" | "firstFrame" | "lastFrame" | "continuation" | "control"; + role: "reference" | "firstFrame" | "lastFrame" | "continuation" | "control" | "keyframe"; + seconds?: number; } /** SAM configurations serve editing tools, including legacy vision entries. */ @@ -315,15 +317,52 @@ export function backendReferences( .map((node) => ({ node, role: "reference" as const })), ]; } - return usable.map((node) => ({ - node, - role: - settings.videoMode === "continuation" && node.data.kind === "video" - ? "continuation" - : settings.videoMode === "control" && node.data.kind === "video" - ? "control" - : "reference", - })); + return usable.map((node) => { + const pinned = settings.mode === "video" ? pinnedFrameSeconds(settings, node.data.kind, node.id) : undefined; + if (pinned !== undefined) return { node, role: "keyframe" as const, seconds: pinned }; + return { + node, + role: + settings.videoMode === "continuation" && node.data.kind === "video" + ? ("continuation" as const) + : settings.videoMode === "control" && node.data.kind === "video" + ? ("control" as const) + : ("reference" as const), + }; + }); +} + +export function pinnedFrameSeconds( + settings: Pick | undefined, + sourceKind: string | undefined, + sourceId: string | undefined, +): number | undefined { + if (!settings || sourceKind !== "image" || !sourceId) return undefined; + if ((settings.videoMode ?? "reference") !== "reference") return undefined; + return settings.pinnedFrames?.find((frame) => frame.nodeId === sourceId)?.seconds; +} + +export function canvasReferenceFrameTime( + settings: Pick | undefined, + sourceKind: string | undefined, + ref: { + binding: string; + role?: string | null; + frameTimeMs?: number | null; + source: { id?: string } | { assetId: string }; + }, +): number | undefined { + if (ref.binding === "pinned") + return settings && + sourceKind === "image" && + (settings.videoMode ?? "reference") === "reference" && + ref.role === "keyframe" && + typeof ref.frameTimeMs === "number" + ? ref.frameTimeMs + : undefined; + const sourceId = ref.binding === "follow_current" && "id" in ref.source ? ref.source.id : undefined; + const seconds = pinnedFrameSeconds(settings, sourceKind, sourceId); + return seconds === undefined ? undefined : Math.round(seconds * 1000); } /** Canvas slot assignment for a saved reference. The backend stores this role. */ @@ -331,7 +370,7 @@ export function canvasReferenceRole( settings: | Pick< GenerationSettings, - "videoMode" | "firstFrameNodeId" | "lastFrameNodeId" + "videoMode" | "firstFrameNodeId" | "lastFrameNodeId" | "pinnedFrames" > | undefined, sourceKind: string | undefined, @@ -340,8 +379,9 @@ export function canvasReferenceRole( role?: string | null; source: { id?: string } | { assetId: string }; }, -): "reference" | "first_frame" | "last_frame" | "continuation" | "control" { +): "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe" { const sourceId = "id" in ref.source ? ref.source.id : undefined; + if (canvasReferenceFrameTime(settings, sourceKind, ref) !== undefined) return "keyframe"; if (settings?.videoMode === "continuation" && sourceKind === "video") { return "continuation"; } @@ -734,9 +774,22 @@ export function backendBlocker( return tNow("errors.rules.controlDuration", { low, high }); } } + const keyframes = references.filter((item) => item.role === "keyframe"); + if (keyframes.length) { + const limit = rules.maxKeyframes ?? 0; + if (!limit) return tNow("errors.rules.keyframeUnsupported"); + if (keyframes.length > limit) return tNow("errors.rules.keyframeCount", { limit }); + const frames = keyframes.map((item) => keyframeFrame(item.seconds ?? 0)); + if (frames.some((frame) => frame >= Math.round(settings.durationSeconds * RULE_FACTS.keyframeFps))) + return tNow("errors.rules.keyframeTime", { seconds: settings.durationSeconds }); + if (new Set(frames).size !== frames.length) return tNow("errors.rules.keyframeDuplicate"); + if (!references.some((item) => item.role === "reference" && ["image", "video"].includes(String(item.node.data.kind)))) + return tNow("errors.rules.keyframeReference"); + } const count = (kind: string) => references.filter( - (item) => item.role !== "continuation" && item.role !== "control" && item.node.data.kind === kind, + (item) => + item.role !== "continuation" && item.role !== "control" && item.role !== "keyframe" && item.node.data.kind === kind, ).length; for (const kind of ["image", "video", "audio"] as const) { const limit = availabilityInputLimit(config, profile, kind); @@ -759,22 +812,26 @@ export function backendBlocker( return null; } +export const keyframeFrame = (seconds: number) => + Math.round((Math.round(seconds * 1000) * RULE_FACTS.keyframeFps) / 1000); + /** The same budget applies to following nodes, pinned assets and expanded subjects. */ export function referenceBudgetIssue( sources: readonly CanvasNode[], config: ModelConfig, settings?: GenerationSettings, ) { - const usable = settings - ? backendReferences(settings, sources, config) - .filter((ref) => ref.role !== "continuation") - .map((ref) => ref.node) + const sent = settings + ? backendReferences(settings, sources, config).filter((ref) => ref.role !== "continuation") + : undefined; + const usable = sent + ? sent.filter((ref) => ref.role !== "keyframe").map((ref) => ref.node) : sources.flatMap((node) => node.type === "subject" ? subjectReferenceNodes(node) : [node], ); let total = 0; const seen = new Set(); - for (const source of usable) { + for (const source of sent ? sent.map((ref) => ref.node) : usable) { const key = `${source.id}:${source.type}:${source.data.src ?? source.data.text ?? ""}`; if (seen.has(key)) continue; seen.add(key); diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 0910201d6..3dd1f9aef 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -429,6 +429,15 @@ export function NodeComposer({ const frameCandidates = incomingNodes.filter( (node) => node.data.kind === "image", ); + const pinnableFrames = + mode === "video" && + backend && + frameCandidates.length > 0 && + (settings.videoMode ?? "reference") === "reference" && + ((config?.inputRules.maxKeyframes ?? 0) > 0 || + frameCandidates.some((node) => + settings.pinnedFrames?.some((frame) => frame.nodeId === node.id), + )); const serviceSeconds = backendDurations(config); const duration = backend && mode === "video" @@ -694,6 +703,56 @@ export function NodeComposer({ )} + {pinnableFrames && ( +
+ {t("generation.keyframes.title")} + {frameCandidates.map((node) => { + const pinned = settings.pinnedFrames?.find((frame) => frame.nodeId === node.id); + const usable = node.data.src && node.data.assetState !== "missing"; + const name = node.data.title || t("generation.keyframes.untitled"); + return ( + + ); + })} + {frameCandidates.some((node) => settings.pinnedFrames?.some((frame) => frame.nodeId === node.id)) && ( + {t("generation.keyframes.lossless")} + )} +
+ )} {referenceVisibility.showStrip && (
+ record(frame) && + nonempty(frame.nodeId) && + finite(frame.seconds) && + Number(frame.seconds) >= 0, + ))) && (value.audioCreationType === undefined || value.audioCreationType === "audio" || value.audioCreationType === "music") && diff --git a/src/canvas/model.ts b/src/canvas/model.ts index 82068db8e..3682c0950 100644 --- a/src/canvas/model.ts +++ b/src/canvas/model.ts @@ -64,6 +64,7 @@ export interface GenerationSettings { firstFrameNodeId?: string; lastFrameNodeId?: string; frameSlotsInitialized?: boolean; + pinnedFrames?: { nodeId: string; seconds: number }[]; audioCreationType?: "audio" | "music"; audioMode?: "unified" | "tts"; voiceName?: string; @@ -1215,5 +1216,19 @@ export function mapSettingsNodeReferences( if (after === undefined) delete next[key]; else next[key] = after; } + if (settings.pinnedFrames?.length) { + const pinned = settings.pinnedFrames.flatMap((frame) => { + const nodeId = resolve(frame.nodeId); + return nodeId === undefined ? [] : [{ ...frame, nodeId }]; + }); + const unchanged = + pinned.length === settings.pinnedFrames.length && + pinned.every((frame, index) => frame.nodeId === settings.pinnedFrames![index]!.nodeId); + if (!unchanged) { + if (next === settings) next = { ...settings }; + if (pinned.length) next.pinnedFrames = pinned; + else delete next.pinnedFrames; + } + } return next; } diff --git a/src/canvas/nodeActionWorkflow.ts b/src/canvas/nodeActionWorkflow.ts index 9b53f01b0..21c116cd2 100644 --- a/src/canvas/nodeActionWorkflow.ts +++ b/src/canvas/nodeActionWorkflow.ts @@ -9,7 +9,20 @@ import { type ResultSource, } from "./linkedResults.ts"; import { tNow } from "../i18n/messages.ts"; -import { createNode, type CanvasDocument } from "./model.ts"; +import { createNode, type CanvasDocument, type CanvasNode } from "./model.ts"; + +export function continuesOwnClip( + source: Pick, + jobs: readonly { id: string; inputSnapshot: { model: { modelConfigId: string } } }[], + modelConfigId: string | undefined, +): boolean { + const provenance = source.data.generationProvenance; + return ( + Boolean(modelConfigId) && + provenance?.source === "generated" && + jobs.find((job) => job.id === provenance.jobId)?.inputSnapshot.model.modelConfigId === modelConfigId + ); +} /** Source toolbar action creates a new connected draft; generation later fills that draft. */ export function createVideoExtensionDraft( diff --git a/src/canvas/nodes.css b/src/canvas/nodes.css index 37a241348..5fb515553 100644 --- a/src/canvas/nodes.css +++ b/src/canvas/nodes.css @@ -647,6 +647,54 @@ .cw-frame-last { order: 2; } +.cw-keyframes { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding-bottom: 6px; +} +.cw-keyframes-title, +.cw-keyframes-note { + flex: 0 0 100%; + font-size: 12px; + opacity: 0.7; +} +.cw-keyframe { + display: flex; + align-items: center; + gap: 6px; + padding: 2px 8px 2px 2px; + border: 1px solid #ffffff0a; + border-radius: 9px; + background: #ffffff05; + color: #bfc0c9; + font-size: 12px; +} +.cw-keyframe.is-pinned { + border-color: #9b93f4; +} +.cw-keyframe:focus-within { + outline: 2px solid #9b93f4; + outline-offset: 2px; +} +.cw-keyframe .cw-frame-thumbnail { + flex: 0 0 36px; + width: 36px; + height: 36px; + border-radius: 7px; + overflow: hidden; +} +.cw-workspace .cw-composer .cw-keyframe input { + width: 7em; + min-width: 0; + padding: 2px 4px; + border: 0; + background: transparent; + color: inherit; + font: inherit; + font-variant-numeric: tabular-nums; +} .cw-frame-unavailable { border-color: #967052; } diff --git a/src/canvas/workspace/useWorkspaceEditor.ts b/src/canvas/workspace/useWorkspaceEditor.ts index e91f2aadb..599736474 100644 --- a/src/canvas/workspace/useWorkspaceEditor.ts +++ b/src/canvas/workspace/useWorkspaceEditor.ts @@ -15,7 +15,7 @@ import type { CanvasItem, ProjectSnapshot } from "../../contracts/generated.ts"; import { lockedNodeIds } from "../hierarchy"; import { captureEditorSource, validateNodeActionSource, type LinkedMediaResult, type ResultSource } from "../linkedResults"; import { type CanvasDocument, type CanvasNode, type CanvasNodeData } from "../model"; -import { createVideoExtensionDraft } from "../nodeActionWorkflow"; +import { continuesOwnClip, createVideoExtensionDraft } from "../nodeActionWorkflow"; import { getNodeGenerationSettings } from "../NodeComposer"; import { resourceFromNode } from "../operations"; @@ -340,6 +340,11 @@ export function useWorkspaceEditor(rt: WorkspaceRuntime, readOnly: boolean) { if ( draft && settings && + continuesOwnClip( + source, + creationClient(historyRef.current.present.id).snapshot?.jobs ?? [], + settings.modelConfigId, + ) && backendModel( settings, backendCatalog.models, diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 886819cef..9e28e4748 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4361,6 +4361,13 @@ "missing_object", "reference_invalid", "image_quality_unsupported", + "keyframe_unsupported", + "keyframe_mode", + "keyframe_kind", + "keyframe_count", + "keyframe_needs_reference", + "keyframe_time", + "keyframe_image", "bigmodel_video_model", "bigmodel_video_output", "bigmodel_video_image", @@ -6049,11 +6056,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -8173,6 +8195,13 @@ "title": "Maxaudios", "type": "integer" }, + "maxKeyframes": { + "default": 0, + "description": "Maximum pictures that can be pinned at chosen moments of a generated video; omitted when unsupported.", + "minimum": 0, + "title": "Maxkeyframes", + "type": "integer" + }, "imageBytes": { "description": "Maximum bytes per reference image.", "minimum": 0, @@ -10988,11 +11017,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -12748,11 +12792,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -13079,11 +13138,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "asset": { "$ref": "#/$defs/AssetRef", "description": "Immutable asset version." @@ -22758,6 +22832,13 @@ "missing_object", "reference_invalid", "image_quality_unsupported", + "keyframe_unsupported", + "keyframe_mode", + "keyframe_kind", + "keyframe_count", + "keyframe_needs_reference", + "keyframe_time", + "keyframe_image", "bigmodel_video_model", "bigmodel_video_output", "bigmodel_video_image", @@ -24497,11 +24578,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -26717,6 +26813,13 @@ "title": "Maxaudios", "type": "integer" }, + "maxKeyframes": { + "default": 0, + "description": "Maximum pictures that can be pinned at chosen moments of a generated video; omitted when unsupported.", + "minimum": 0, + "title": "Maxkeyframes", + "type": "integer" + }, "imageBytes": { "description": "Maximum bytes per reference image.", "minimum": 0, @@ -29611,11 +29714,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -31426,11 +31544,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "order": { "default": 0, "description": "Reference ordering within the target configuration.", @@ -31767,11 +31900,26 @@ "first_frame", "last_frame", "continuation", - "control" + "control", + "keyframe" ], "title": "Role", "type": "string" }, + "frameTimeMs": { + "anyOf": [ + { + "minimum": 0, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "For role keyframe: where in the generated video this picture is pinned, in milliseconds from its start.", + "title": "Frametimems" + }, "asset": { "$ref": "#/$defs/AssetRef", "description": "Immutable asset version." diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 61f7ddf52..d9b149d0c 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -483,7 +483,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -820,6 +820,7 @@ export interface InputRulesInput extends ContractInput { readonly maxImages: number; readonly maxVideos: number; readonly maxAudios: number; + readonly maxKeyframes?: number; readonly imageBytes: number; readonly videoBytes: number; readonly audioBytes?: number | null; @@ -1294,7 +1295,8 @@ export interface ReferenceAddCommandOperationInput { export interface ReferenceBaseInput extends ProjectEntityInput { readonly targetSpecId: string; - readonly role?: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role?: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly order?: number; readonly active?: boolean; } @@ -1339,7 +1341,8 @@ export interface ReferenceWriteInput extends ContractInput { export interface ResolvedReferenceInput extends ContractInput { readonly referenceId: string; - readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly asset: AssetRefInput; readonly metadata: MediaMetadataInput; readonly sourceVersion?: ObjectVersionInput | null; @@ -2376,7 +2379,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -2713,6 +2716,7 @@ export interface InputRules extends Contract { readonly maxImages: number; readonly maxVideos: number; readonly maxAudios: number; + readonly maxKeyframes?: number; readonly imageBytes: number; readonly videoBytes: number; readonly audioBytes?: number | null; @@ -3186,7 +3190,8 @@ export interface ReferenceAddCommandOperation { export interface ReferenceBase extends ProjectEntity { readonly targetSpecId: string; - readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly order: number; readonly active: boolean; } @@ -3231,7 +3236,8 @@ export interface ReferenceWrite extends Contract { export interface ResolvedReference extends Contract { readonly referenceId: string; - readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control"; + readonly role: "reference" | "first_frame" | "last_frame" | "continuation" | "control" | "keyframe"; + readonly frameTimeMs?: number | null; readonly asset: AssetRef; readonly metadata: MediaMetadata; readonly sourceVersion: ObjectVersion | null; diff --git a/src/contracts/ruleFacts.generated.ts b/src/contracts/ruleFacts.generated.ts index 7b4ca8cce..565adf436 100644 --- a/src/contracts/ruleFacts.generated.ts +++ b/src/contracts/ruleFacts.generated.ts @@ -26,6 +26,7 @@ export const RULE_FACTS = { "musicSecondsInitial": 30, "referenceMediaSeconds": 15, "fasth3MediaReferenceLimit": 12, + "keyframeFps": 24, "controlVideoSeconds": [ 4, 30 diff --git a/src/i18n/messages/en-US/errors.ts b/src/i18n/messages/en-US/errors.ts index 7c68ae9f2..105f4cc5e 100644 --- a/src/i18n/messages/en-US/errors.ts +++ b/src/i18n/messages/en-US/errors.ts @@ -162,6 +162,13 @@ export const errors = { "errors.rules.controlDuration": "The control video must be {low}–{high} seconds", "errors.rules.continuationSource": "Continuation needs a video generated by the current H3 service as the previous segment.", + "errors.rules.keyframeUnsupported": + "This model does not support keyframes. Clear the times on the images or choose another model.", + "errors.rules.keyframeCount": "Up to {limit} keyframes.", + "errors.rules.keyframeTime": "A keyframe must be earlier than the end of the video ({seconds} s).", + "errors.rules.keyframeDuplicate": "Two keyframes cannot land on the same frame. Keep their times at least 1/24 second apart.", + "errors.rules.keyframeReference": + "Keyframes also need at least one unpinned reference image or a reference video.", "errors.rules.serviceInputLimit": "Up to {limit} {kind} inputs; currently {current}.", "errors.rules.referenceLimit": "Too many {kind} references for this model (limit: {limit}).", diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index 948dc8969..fc50e39e5 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -179,6 +179,13 @@ export const generation = { "generation.lyricsReferencePlaceholder": "Lyrics (optional; leave blank for instrumental music). Follow the sections and phrases of the reference, with each section tag on its own line, for example:\n[verse]\nRain falls by the window\n[chorus]\nLet the melody answer what I cannot say", + "generation.keyframes.title": + "Keyframes: give an image a time and the video shows that picture at that moment", + "generation.keyframes.placeholder": "Unpinned", + "generation.keyframes.unit": "s", + "generation.keyframes.untitled": "Untitled image", + "generation.keyframes.time": "Second at which to pin “{title}”", + "generation.keyframes.lossless": "With keyframes the video is generated at lossless quality.", "generation.frame.title": "First and last frame references", "generation.frame.first": "First frame", "generation.frame.last": "Last frame", diff --git a/src/i18n/messages/zh-CN/errors.ts b/src/i18n/messages/zh-CN/errors.ts index 652cb0cff..2941324cf 100644 --- a/src/i18n/messages/zh-CN/errors.ts +++ b/src/i18n/messages/zh-CN/errors.ts @@ -115,6 +115,11 @@ export const errors = { "errors.rules.controlDuration": "控制视频需要 {low}–{high} 秒", "errors.rules.continuationSource": "接续需要连接一段由当前 H3 服务生成的视频作为上一段。", + "errors.rules.keyframeUnsupported": "当前模型不支持指定帧,请清除图片上的时间或更换模型。", + "errors.rules.keyframeCount": "最多指定 {limit} 个关键帧。", + "errors.rules.keyframeTime": "关键帧的时间必须早于视频结束({seconds} 秒)。", + "errors.rules.keyframeDuplicate": "两个关键帧不能落在同一帧上,请把时间至少错开 1/24 秒。", + "errors.rules.keyframeReference": "指定帧生成还需要至少一张不指定时间的参考图片或一段参考视频。", "errors.rules.referenceLimit": "参考{kind}超过当前模型上限({limit} 个)。", "errors.rules.serviceInputLimit": "最多支持 {limit} 个{kind},当前为 {current} 个。", "errors.rules.referenceFileSize": "参考文件超过当前模型的大小限制", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index d7a1bc86a..cdd5a1462 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -164,6 +164,12 @@ export const generation = { "generation.lyricsReferencePlaceholder": "歌词(可选,留空生成纯音乐)。按参照音乐的段落和乐句填写,段落标签单独成一行,例如:\n[verse]\n雨落在窗前\n[chorus]\n说不出的话,让旋律回答", + "generation.keyframes.title": "指定帧:给图片填一个时间,生成的视频会在那一刻出现这个画面", + "generation.keyframes.placeholder": "不指定", + "generation.keyframes.unit": "秒", + "generation.keyframes.untitled": "未命名图片", + "generation.keyframes.time": "把“{title}”钉在第几秒", + "generation.keyframes.lossless": "指定关键帧后会以无损质量生成。", "generation.frame.title": "首尾帧参考", "generation.frame.first": "首帧", "generation.frame.last": "尾帧", diff --git a/tests/backendRules.test.ts b/tests/backendRules.test.ts index e53df21c2..731dda70d 100644 --- a/tests/backendRules.test.ts +++ b/tests/backendRules.test.ts @@ -124,6 +124,28 @@ test("MAGI-2 keeps ordinary image references, optional media prompts and native assert.ok(referenceBudgetIssue([sound], magi, settings)); }); +test("keyframe pictures share the request byte budget but not the reference counts", () => { + const megabyte = 1024 * 1024; + const guided = config("video", { + maxImages: 1, maxKeyframes: 8, imageBytes: 30 * megabyte, requestBytes: 64 * megabyte, + videoModes: ["first_frame", "reference", "continuation"], + }); + const sized = (bytes: number) => { + const node = media("image"); + node.data.byteSize = bytes; + return node; + }; + const costume = sized(20 * megabyte), left = sized(25 * megabyte), right = sized(25 * megabyte); + const pin = (...nodes: CanvasNode[]) => ({ + ...video({ videoMode: "reference" }), + modelConfigId: guided.id, + pinnedFrames: nodes.map((node, index) => ({ nodeId: node.id, seconds: index + 1 })), + }); + assert.equal(referenceBudgetIssue([costume, left], guided, pin(left)), null); + setActiveLocale("zh-CN"); + assert.ok(referenceBudgetIssue([costume, left, right], guided, pin(left, right))); +}); + test("SAM stays tool-only in both media categories and legacy vision configurations", () => { for (const kind of ["image", "video"] as const) { const sam = { diff --git a/tests/keyframeReferences.test.ts b/tests/keyframeReferences.test.ts new file mode 100644 index 000000000..5fbe8844e --- /dev/null +++ b/tests/keyframeReferences.test.ts @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { CreationClient, type CreationOperation } from "../src/backend/creationClient.ts"; +import { CreationProjection } from "../src/backend/creationProjection.ts"; +import { + canvasReferenceFrameTime, + canvasReferenceRole, + keyframeFrame, + pinnedFrameSeconds, +} from "../src/backend/rules.ts"; +import { mapSettingsNodeReferences } from "../src/canvas/model.ts"; +import { continuesOwnClip } from "../src/canvas/nodeActionWorkflow.ts"; +import type { CanvasItem, GenerationSpec, ProjectSnapshot } from "../src/contracts/generated.ts"; + +const follow = (id: string) => ({ binding: "follow_current", role: "reference", source: { id } }); + +test("a pinned image becomes a keyframe at its time in milliseconds", () => { + const settings = { videoMode: "reference" as const, pinnedFrames: [{ nodeId: "pose", seconds: 1.25 }] }; + assert.equal(canvasReferenceRole(settings, "image", follow("pose")), "keyframe"); + assert.equal(canvasReferenceFrameTime(settings, "image", follow("pose")), 1250); + assert.equal(canvasReferenceRole(settings, "image", follow("costume")), "reference"); + assert.equal(canvasReferenceFrameTime(settings, "image", follow("costume")), undefined); +}); + +test("pins apply to images in reference mode only", () => { + const pinnedFrames = [{ nodeId: "clip", seconds: 2 }]; + assert.equal(pinnedFrameSeconds({ videoMode: "reference", pinnedFrames }, "video", "clip"), undefined); + for (const videoMode of ["first-last", "continuation", "control"] as const) + assert.equal(pinnedFrameSeconds({ videoMode, pinnedFrames }, "image", "clip"), undefined); + assert.equal(pinnedFrameSeconds({ pinnedFrames }, "image", "clip"), 2); + assert.equal(canvasReferenceRole({ videoMode: "control", pinnedFrames }, "video", follow("clip")), "control"); +}); + +test("a pinned asset version is not tied to a canvas node, so it keeps its stored role", () => { + const settings = { videoMode: "reference" as const, pinnedFrames: [{ nodeId: "pose", seconds: 1 }] }; + const pinnedAsset = { binding: "pinned", role: "reference", source: { assetId: "pose" } }; + assert.equal(canvasReferenceFrameTime(settings, "image", pinnedAsset), undefined); + assert.equal(canvasReferenceRole(settings, "image", pinnedAsset), "reference"); +}); + +test("a keyframe on a pinned asset version keeps its role and time through a canvas save", () => { + const stored = { binding: "pinned", role: "keyframe", frameTimeMs: 1250, source: { assetId: "pose" } }; + for (const settings of [{ videoMode: "reference" as const }, {}]) { + assert.equal(canvasReferenceRole(settings, "image", stored), "keyframe"); + assert.equal(canvasReferenceFrameTime(settings, "image", stored), 1250); + } + for (const videoMode of ["first-last", "continuation", "control"] as const) { + assert.equal(canvasReferenceRole({ videoMode }, "image", stored), "reference"); + assert.equal(canvasReferenceFrameTime({ videoMode }, "image", stored), undefined); + } +}); + +test("times are compared as the output frames they land on", () => { + assert.equal(keyframeFrame(1), 24); + assert.equal(keyframeFrame(1.02), 24); + assert.equal(keyframeFrame(1.05), 25); + assert.equal(keyframeFrame(4.4583), Math.round((4458 * 24) / 1000)); +}); + +test("a copied node keeps its keyframe times on the copied pictures", () => { + const settings = { + videoMode: "reference" as const, + firstFrameNodeId: "first", + pinnedFrames: [{ nodeId: "pose", seconds: 1.25 }, { nodeId: "left-behind", seconds: 3 }], + }; + const copies: Record = { first: "first-copy", pose: "pose-copy" }; + const mapped = mapSettingsNodeReferences(settings as never, (id) => copies[id]); + assert.deepEqual(mapped.pinnedFrames, [{ nodeId: "pose-copy", seconds: 1.25 }]); + assert.equal(mapped.firstFrameNodeId, "first-copy"); + assert.deepEqual(settings.pinnedFrames.map((frame) => frame.nodeId), ["pose", "left-behind"]); + const same = { videoMode: "reference" as const, pinnedFrames: [{ nodeId: "pose", seconds: 1 }] }; + assert.equal(mapSettingsNodeReferences(same as never, (id) => id), same); + const none = mapSettingsNodeReferences(same as never, () => undefined); + assert.equal(none.pinnedFrames, undefined); +}); + +test("extend continues only a clip the same model configuration generated", () => { + const jobs = [ + { id: "by-pika", inputSnapshot: { model: { modelConfigId: "pika" } } }, + { id: "by-other", inputSnapshot: { model: { modelConfigId: "other" } } }, + ]; + const clip = (source: string, jobId?: string, modelConfigId = "pika") => + ({ data: { generationProvenance: { source, jobId }, settings: { modelConfigId } } }) as never; + assert.equal(continuesOwnClip(clip("generated", "by-pika"), jobs, "pika"), true); + assert.equal(continuesOwnClip(clip("upload"), jobs, "pika"), false); + assert.equal(continuesOwnClip(clip("edited", "by-pika"), jobs, "pika"), false); + assert.equal(continuesOwnClip(clip("generated", "by-other"), jobs, "pika"), false); + assert.equal(continuesOwnClip(clip("generated", "by-pika"), jobs, undefined), false); + assert.equal(continuesOwnClip(clip("generated", "unknown-job"), jobs, "pika"), false); + assert.equal(continuesOwnClip({ data: {} } as never, jobs, "pika"), false); +}); + +test("a node switched to another model after generating does not continue the old model's clip", () => { + const jobs = [{ id: "by-pika", inputSnapshot: { model: { modelConfigId: "pika" } } }]; + const switched = { + data: { generationProvenance: { source: "generated", jobId: "by-pika" }, settings: { modelConfigId: "native-h3" } }, + } as never; + assert.equal(continuesOwnClip(switched, jobs, "native-h3"), false); +}); + +test("a canvas save rewrites a changed keyframe time and leaves a pinned-asset keyframe alone", async () => { + const base = JSON.parse( + readFileSync(new URL("./fixtures/creation-project.json", import.meta.url), "utf8"), + ) as ProjectSnapshot; + const picture = { + ...base.canvasItems.find((item) => item.kind === "image" && item.binding.role === "material")!, + editors: [], + } as CanvasItem; + const asset = base.assets.find((entry) => entry.kind === "image")!; + const spec = { + ...base.generationSpecs.find((entry) => entry.kind === "image")!, + kind: "video", + currentResultId: null, + parameters: { videoMode: "reference", durationSeconds: 5, aspectRatio: "9:16", generateAudio: true }, + } as GenerationSpec; + const video = { + ...base.canvasItems.find((item) => item.kind === "image" && item.binding.role === "generation")!, + kind: "video", + binding: { role: "generation", materialOverride: null, objectRef: { objectType: "generation_spec", id: spec.id } }, + editors: [], + } as CanvasItem; + const shared = { projectId: base.project.id, revision: 1, targetSpecId: spec.id, role: "keyframe", active: true }; + const following = { + ...shared, id: crypto.randomUUID(), order: 0, frameTimeMs: 1250, + binding: "follow_current", source: { objectType: "canvas_item", id: picture.id }, + }; + const pinned = { + ...shared, id: crypto.randomUUID(), order: 1, frameTimeMs: 4000, + binding: "pinned", source: { assetId: asset.id, revision: asset.revision, fingerprint: asset.fingerprint, kind: "image" }, + }; + const snapshot = { + ...base, canvasItems: [picture, video], generationSpecs: [spec], references: [following, pinned], + editorDocuments: [], jobs: [], results: [], + } as unknown as ProjectSnapshot; + const client = new CreationClient(base.project.id); + client.install(snapshot); + client.view = async () => ({ + projectId: client.id, clientId: crypto.randomUUID(), viewport: { x: 0, y: 0, zoom: 1 }, + selectedItemIds: [], activeEditorId: null, playheads: [], generationCounts: {}, + }); + const batches: CreationOperation[][] = []; + client.batch = async (operations) => { + batches.push(operations); + return undefined; + }; + const projection = new CreationProjection(client); + const restored = await projection.read(); + const settings = restored.nodes.find((node) => node.id === video.id)!.data.settings!; + assert.deepEqual(settings.pinnedFrames, [{ nodeId: picture.id, seconds: 1.25 }]); + projection.baseline = restored; + projection.basis = snapshot; + const next = structuredClone(restored); + next.nodes.find((node) => node.id === video.id)!.data.settings!.pinnedFrames = [{ nodeId: picture.id, seconds: 2 }]; + await projection.save(next); + const rewritten = batches.flat().flatMap((operation) => + operation.type === "reference.update" + ? [[operation.payload.reference.id, operation.payload.reference.role, operation.payload.reference.frameTimeMs]] + : [], + ); + assert.deepEqual(rewritten, [[following.id, "keyframe", 2000]]); +}); diff --git a/tests/test_agent_metadata.py b/tests/test_agent_metadata.py index db301a44a..f4b9416f4 100644 --- a/tests/test_agent_metadata.py +++ b/tests/test_agent_metadata.py @@ -95,7 +95,7 @@ async def parameters(**options): spec = await parameters(path='payload.spec', modelConfigId=config['id']) assert 'parameters' in spec['required'] compact = await parameters(path='payload.spec.parameters', modelConfigId=config['id']) - assert compact['fields']['videoMode']['enum'] == ['reference', 'control'] + assert compact['fields']['videoMode']['enum'] == ['reference', 'control', 'continuation'] assert 'default' not in compact['fields']['videoMode'] assert 'videoMode' in compact['required'] assert compact['fields']['generateAudio']['enum'] == [True] diff --git a/tests/test_capability_input_projection.py b/tests/test_capability_input_projection.py index fe9e99652..29f46439f 100644 --- a/tests/test_capability_input_projection.py +++ b/tests/test_capability_input_projection.py @@ -1,5 +1,6 @@ """Admission follows provider comparison rules and actual media transmission.""" from copy import deepcopy +import json from types import SimpleNamespace import pytest @@ -131,6 +132,36 @@ def test_continuation_does_not_claim_video_upload_but_honors_route_pause(service assert availability.decision(config, request)['status'] == 'unknown' +def test_a_keyframe_is_not_counted_as_a_reference_image(service): + configs, saved, state, availability = service + config = {**private(configs, saved), 'kind': 'video', 'protocol': 'vllm_omni'} + spec = SimpleNamespace(kind='video', parameters=SimpleNamespace(videoMode='reference')) + guide = SimpleNamespace(asset=SimpleNamespace(kind='image'), transmission='content', role='keyframe') + ordinary = SimpleNamespace(asset=SimpleNamespace(kind='image'), transmission='content', role='reference') + request = generation_request(config, spec, [ordinary, guide, guide]) + assert dict(request.input_counts) == {'text': 1, 'image': 1, 'reference_image': 1} + + +@pytest.mark.parametrize('adapter', ['minimax_h3', 'fasth3']) +def test_a_guided_request_is_checked_with_the_guide_fields_it_sends(service, adapter): + configs, saved, state, availability = service + config = {**private(configs, saved), 'kind': 'video', 'protocol': 'vllm_omni', 'videoAdapter': adapter} + spec = SimpleNamespace(kind='video', parameters=SimpleNamespace(videoMode='reference')) + ordinary = SimpleNamespace(asset=SimpleNamespace(kind='image'), transmission='content', role='reference') + guides = [SimpleNamespace(asset=SimpleNamespace(kind='image'), transmission='content', role='keyframe', frameTimeMs=time) + for time in (1250, 4000)] + parameters = {'duration': 5, 'size': '1280x720'} + plain = dict(generation_request(config, spec, [ordinary], parameters=parameters).parameters) + assert 'quality' not in plain and 'timeline_guides' not in plain + guided = dict(generation_request(config, spec, [ordinary, *guides], parameters=parameters).parameters) + assert guided['quality'] == 'lossless' + assert json.loads(guided['timeline_guides']) == [{'frame_index': 30, 'image': {'upload_index': 0}}, + {'frame_index': 96, 'image': {'upload_index': 1}}] + refused = RequestConstraints.model_validate({'parameters': {'timeline_guides': {'support': 'unsupported'}}}) + assert constraint_failure(refused, None, guided) == ('parameter_unsupported', {'parameter': 'timeline_guides'}) + assert constraint_failure(refused, None, plain) is None + + @pytest.mark.parametrize('route,unavailable', [ ({'method': 'POST', 'path': '/v1/videos', 'transport': 'http', 'exposure': 'disabled'}, True), ({'method': 'GET', 'path': '/v1/videos', 'transport': 'http', 'exposure': 'disabled'}, False), diff --git a/tests/test_fasth3_continuation.py b/tests/test_fasth3_continuation.py new file mode 100644 index 000000000..972af1228 --- /dev/null +++ b/tests/test_fasth3_continuation.py @@ -0,0 +1,111 @@ +import asyncio +import json +from email.parser import BytesParser +from email.policy import default +from types import SimpleNamespace +from uuid import uuid4 + +import httpx +import pytest + +from opendirector.domain.generation import GenerationError +from opendirector.domain.input_rules import input_rules +from opendirector.domain.projects import ProjectError +from opendirector.integrations.fasth3 import generation_fields, video_parameters +from opendirector.integrations.providers import GenerationProviders + + +pytestmark = pytest.mark.cpu + +CONFIG = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', + 'videoAdapter': 'fasth3', 'apiKey': '', 'authMode': 'none'} + + +@pytest.mark.parametrize('adapter', ['fasth3', 'fasth3_dual']) +def test_every_fasth3_shaped_model_offers_continuation(adapter): + assert 'continuation' in input_rules({**CONFIG, 'videoAdapter': adapter})['videoModes'] + + +def test_fields_name_the_source_job_and_keep_its_canvas(): + fields, extra = generation_fields({'duration': 5, 'size': '832x480'}, continue_from='video_gen_1', continue_size=(768, 1344)) + assert extra['continue_from'] == 'video_gen_1' and extra['task'] == 'ref2va' + assert fields['size'] == '768x1344' and fields['num_inference_steps'] == 8 + assert 'continue_from' not in generation_fields({'duration': 5})[1] + + +def test_the_capability_check_sees_the_size_the_continuation_sends(): + from opendirector.integrations.generation_capability_parameters import generation_capability_parameters + config = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', 'videoAdapter': 'fasth3'} + parameters = {'duration': 5, 'size': '832x480'} + checked = generation_capability_parameters(config, 'video', parameters, video_mode='continuation', continue_size=(768, 1344)) + sent, _ = generation_fields(parameters, continue_from='video_gen_1', continue_size=(768, 1344)) + assert checked['size'] == sent['size'] == '768x1344' + + +def fixture(source_job, **source_meta): + video = {'id': str(uuid4()), 'name': 'part1.mp4', 'kind': 'video', 'type': 'video/mp4', 'fingerprint': 'fixture', + 'durationMs': 5167, 'width': 768, 'height': 1344, 'generationTaskId': 'task-1', **source_meta} + picture = {'id': str(uuid4()), 'name': 'costume.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + assets = {video['id']: (b'source-video-bytes', video), picture['id']: (b'\x89PNG\r\n\x1a\nfixture', picture)} + store = SimpleNamespace(asset=lambda owner, key: assets[key], generation_task=lambda owner, key: source_job) + task = {'kind': 'video', 'projectId': 'owner', 'prompt': '她缓缓落地', 'referenceIds': list(assets), 'videoMode': 'continuation'} + task['parameters'] = video_parameters(task, {key: pair[1] for key, pair in assets.items()}, duration_seconds=5) + return store, task + + +def run(store, task, handle): + async def submitted(value): + assert value == 'video_gen_2' + provider = GenerationProviders(store, httpx.MockTransport(handle), poll_interval=0) + return asyncio.run(provider.generate(CONFIG, task, submitted)) + + +SOURCE_JOB = {'kind': 'video', 'status': 'succeeded', 'externalTaskId': 'video_gen_1', 'baseURL': CONFIG['url'], 'model': CONFIG['modelId']} + + +def test_the_wire_carries_the_job_id_and_not_the_source_video(): + store, task = fixture(SOURCE_JOB) + seen = {} + + def handle(request): + if request.method == 'POST': + prefix = 'Content-Type: ' + request.headers['content-type'] + '\r\n\r\n' + message = BytesParser(policy=default).parsebytes(prefix.encode() + request.content) + for part in message.iter_parts(): + seen.setdefault(part.get_param('name', header='content-disposition'), []).append(part.get_payload(decode=True)) + return httpx.Response(200, json={'id': 'video_gen_2'}) + if request.url.path.endswith('/content'): + return httpx.Response(200, content=b'generated') + return httpx.Response(200, json={'status': 'completed'}) + + assert run(store, task, handle) == ('mp4', b'generated') + extra = json.loads(seen['extra_params'][0]) + assert extra['continue_from'] == 'video_gen_1' and extra['task'] == 'ref2va' + assert seen['size'] == [b'768x1344'] and seen['num_inference_steps'] == [b'8'] + assert len(seen['input_references']) == 1 and b'source-video-bytes' not in b''.join(seen['input_references']) + + +def test_an_uploaded_or_foreign_clip_cannot_be_continued(): + for job in ({**SOURCE_JOB, 'model': 'another-model'}, {**SOURCE_JOB, 'status': 'failed'}): + store, task = fixture(job) + with pytest.raises(ProjectError, match='不能接续'): + run(store, task, lambda request: pytest.fail('nothing may be sent')) + store, task = fixture(SOURCE_JOB, generationTaskId=None) + with pytest.raises(ProjectError, match='不能接续'): + run(store, task, lambda request: pytest.fail('nothing may be sent')) + + +@pytest.mark.parametrize('answer', [ + httpx.Response(400, json={'error': {'message': 'continue_from job video_gen_1 has no cached latents'}}), + None, +]) +def test_a_clip_the_service_no_longer_holds_is_explained(answer): + store, task = fixture(SOURCE_JOB) + + def handle(request): + if request.method == 'POST': + return answer or httpx.Response(200, json={'id': 'video_gen_2'}) + return httpx.Response(200, json={'status': 'failed', 'error': {'message': 'continue_from: cached latents were evicted'}}) + + with pytest.raises(GenerationError, match='接续缓存'): + run(store, task, handle) diff --git a/tests/test_fasth3_video_edit.py b/tests/test_fasth3_video_edit.py new file mode 100644 index 000000000..6f0f46562 --- /dev/null +++ b/tests/test_fasth3_video_edit.py @@ -0,0 +1,165 @@ +import asyncio +import json + +import pytest + +from opendirector.domain.capabilities import EditMask, MediaResult, VideoEditRequest +from opendirector.integrations.model_adapters import FastH3VideoEdit, VllmOmniVideo, adapter_for, capabilities_of +from opendirector.integrations.vllm_omni import capability_parameters + + +pytestmark = pytest.mark.cpu + +CONFIG = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', + 'videoAdapter': 'fasth3', 'apiKey': '', 'authMode': 'none'} + + +@pytest.mark.parametrize('adapter', ['fasth3', 'fasth3_dual']) +def test_fasth3_shaped_models_provide_local_redraw_only(adapter): + config = {**CONFIG, 'videoAdapter': adapter} + assert isinstance(adapter_for(config), FastH3VideoEdit) + assert capabilities_of(config) == {'video.edit'} + assert capabilities_of({**CONFIG, 'videoAdapter': 'minimax_h3'}) == VllmOmniVideo.capabilities + + +def test_edit_admission_declares_the_reference_picture_the_request_uploads(): + from opendirector.application.model_availability import tool_request + from opendirector.domain.omni_capabilities import RequestConstraints + from opendirector.domain.request_constraints import constraint_failure + edit = tool_request(CONFIG, 'video.edit', actual=True) + assert {'image', 'reference_image', 'source_video', 'video_noise_mask', 'audio_noise_mask'} <= edit.inputs + assert 'reference_image' in edit.required_roles and dict(edit.input_counts)['reference_image'] == 1 + native = tool_request({**CONFIG, 'videoAdapter': 'minimax_h3'}, 'video.edit', actual=True) + assert 'image' not in native.inputs and 'reference_image' not in native.required_roles + refusing = RequestConstraints.model_validate({'inputs': {'reference_image': {'support': 'unsupported'}}}) + assert constraint_failure(refusing, dict(edit.input_counts), {}) == ('input_unsupported', {'input': 'reference_image'}) + assert constraint_failure(refusing, dict(native.input_counts), {}) is None + + +def recorded(monkeypatch, adapter): + calls, reported = [], [] + + async def job(config, fields, files, submitted): + calls.append((fields, files)) + if submitted: + await submitted(f'job-{len(calls)}') + return MediaResult(f'draft-{len(calls)}'.encode(), 'mp4') + + async def remote_job(run): + ids = [] + reported.append(ids) + + async def submitted(external_id): + ids.append(external_id) + return await run(submitted) + + monkeypatch.setattr(adapter, '_job', job) + monkeypatch.setattr(adapter, '_conformed', lambda source, *_: source) + monkeypatch.setattr(adapter, '_source_still', lambda source, mask: b'source-still-of-' + source) + monkeypatch.setattr(adapter, '_last_edited_frame', lambda clip, end: b'last-frame-before-%r-of-' % end + clip) + return calls, reported, remote_job + + +def test_edit_request_is_ref2va_on_the_fixed_schedule_with_a_source_frame_as_reference(monkeypatch): + adapter = FastH3VideoEdit() + calls, _, remote_job = recorded(monkeypatch, adapter) + checked = capability_parameters(*adapter.edit_parameters(5, 768, 1344)) + asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='把背景换成月夜', source=b'video', seconds=5, width=768, height=1344, + picture=EditMask(1.0, region=((0.0, 1.0),)), avoid='凳子'), remote_job=remote_job)) + fields, files = calls[0] + extra = json.loads(fields['extra_params']) + assert extra == {'task': 'ref2va', 'audio_flow_shift': 3} + assert (fields['num_inference_steps'], fields['guidance_scale'], fields['num_frames'], fields['size']) == ('8', '1', '124', '768x1344') + sent = {key: value for key, value in fields.items() if key not in {'model', 'prompt', 'extra_params'}} | extra + assert {key: str(value) for key, value in checked.items() if key not in {'width', 'height'}} == {key: str(value) for key, value in sent.items()} + assert fields['prompt'] == ' 把背景换成月夜' and 'negative_prompt' not in fields + assert [name for name, _ in files] == ['input_references', 'source_video', 'video_noise_mask', 'audio_noise_mask'] + assert files[0][1][1] == b'source-still-of-video' + assert json.loads(files[2][1][1]) == [[0.0, 1.0]] and json.loads(files[3][1][1]) == 0.0 + + +def test_a_boxed_redraw_runs_again_with_its_own_last_edited_frame_as_reference(monkeypatch): + adapter = FastH3VideoEdit() + calls, reported, remote_job = recorded(monkeypatch, adapter) + result = asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='moon', source=b'video', seconds=5, width=768, height=1344, + picture=EditMask(1.0, region=((1.0, 0.0),))), remote_job=remote_job)) + assert [files[0][1][1] for _, files in calls] == [b'source-still-of-video', b'last-frame-before-None-of-draft-1'] + assert calls[0][0] == calls[1][0] and calls[0][1][1:] == calls[1][1][1:] + assert result.data == b'draft-2' + assert reported == [['job-1'], ['job-2']] + + +def test_a_boxed_redraw_that_stops_early_takes_the_last_frame_it_covers(monkeypatch): + adapter = FastH3VideoEdit() + calls, _, remote_job = recorded(monkeypatch, adapter) + asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='moon', source=b'video', seconds=5, width=768, height=1344, + picture=EditMask(1.0, region=((1.0, 0.0),), start=1.0, end=3.0)), remote_job=remote_job)) + assert calls[1][1][0][1][1] == b'last-frame-before-3.0-of-draft-1' + + +@pytest.mark.parametrize('mask', [EditMask(1.0, None, 1.0, 3.0), EditMask(1.0, None, 0.0, 2.5), EditMask(1.0, None), None], + ids=['span-inside', 'span-opens-clip', 'whole-clip', 'sound-only']) +def test_a_whole_frame_redraw_runs_once(monkeypatch, mask): + adapter = FastH3VideoEdit() + calls, _, remote_job = recorded(monkeypatch, adapter) + result = asyncio.run(adapter.edit_video(CONFIG, VideoEditRequest(prompt='green dress', source=b'video', seconds=5, width=768, height=1344, + picture=mask, sound=EditMask(1.0)), remote_job=remote_job)) + assert len(calls) == 1 and result.data == b'draft-1' + assert calls[0][1][0][1][1] == b'source-still-of-video' + + +@pytest.fixture(scope='module') +def two_tone(tmp_path_factory): + import shutil + import subprocess + if not shutil.which('ffmpeg'): + pytest.skip('FFmpeg is required to build the clip') + clip = tmp_path_factory.mktemp('edit') / 'clip.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=red:s=64x48:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=blue:s=64x48:r=24:d=1', + '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-filter_complex', '[0:v][1:v]concat=n=2:v=1:a=0[v]', + '-map', '[v]', '-map', '2:a', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', str(clip)], check=True) + return clip.read_bytes() + + +def colour(still): + from io import BytesIO + + from PIL import Image + red, _, blue = Image.open(BytesIO(still)).convert('RGB').getpixel((32, 24)) + return 'red' if red > 200 and blue < 60 else 'blue' if blue > 200 and red < 60 else (red, blue) + + +@pytest.mark.parametrize('mask, expected', [ + (None, 'red'), + (EditMask(1.0, ((1.0, 0.0),)), 'red'), + (EditMask(1.0, None, 1.0, 1.5), 'red'), + (EditMask(1.0, None, 0.0, 1.0), 'blue'), + (EditMask(1.0, None, None, 0.5), 'red'), + (EditMask(1.0, None, 0.0, 2.0), 'red'), + (EditMask(1.0, None, 0.0, 2.9), 'red'), + (EditMask(1.0, None, 0.0, 47 / 24), 'blue'), +], ids=['no-picture-mask', 'boxed', 'span-inside', 'span-opens-clip', 'short-opening-span', 'span-to-the-end', 'span-past-the-picture', 'last-frame-kept']) +def test_the_source_still_is_a_frame_the_edit_keeps(two_tone, mask, expected): + assert colour(FastH3VideoEdit._source_still(two_tone, mask)) == expected + + +def test_the_final_picture_is_found_when_the_sound_runs_longer(tmp_path): + import shutil + import subprocess + + from opendirector.media import processing as media + if not shutil.which('ffmpeg'): + pytest.skip('FFmpeg is required to build the clip') + clip = tmp_path / 'clip.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=c=red:s=64x48:r=24:d=1', '-f', 'lavfi', '-i', 'color=c=blue:s=64x48:r=24', + '-f', 'lavfi', '-i', 'sine=frequency=440:duration=3', '-filter_complex', '[1:v]trim=end_frame=23[b];[0:v][b]concat=n=2:v=1:a=0[v]', + '-map', '[v]', '-map', '2:a', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', str(clip)], check=True) + assert media.video_info(clip)['duration'] == pytest.approx(3, abs=0.1) + assert media.last_frame_time(clip) == pytest.approx(46 / 24) + from io import BytesIO + + from PIL import Image + red, green, blue = Image.open(BytesIO(FastH3VideoEdit._last_edited_frame(clip.read_bytes(), None))).convert('RGB').getpixel((32, 24)) + assert blue > 200 and red < 60 + red, green, blue = Image.open(BytesIO(FastH3VideoEdit._last_edited_frame(clip.read_bytes(), 0.5))).convert('RGB').getpixel((32, 24)) + assert red > 200 and blue < 60 diff --git a/tests/test_h3_keyframes.py b/tests/test_h3_keyframes.py new file mode 100644 index 000000000..c4c7244bd --- /dev/null +++ b/tests/test_h3_keyframes.py @@ -0,0 +1,325 @@ +import asyncio +import json +from email.parser import BytesParser +from email.policy import default +from types import SimpleNamespace +from uuid import uuid4 + +import httpx +import pytest + +from opendirector.domain.creation.assets import AssetRef, MediaMetadata +from opendirector.domain.creation.generation import (ResolvedReference, VideoGenerationSpec, VideoParameters, + validate_generation) +from opendirector.domain.creation.models import ModelConfigPublic +from opendirector.domain.input_rules import input_rules +from opendirector.domain.projects import ProjectError +from opendirector.integrations.fasth3 import video_parameters +from opendirector.integrations.providers import GenerationProviders +from opendirector.integrations.reference_inputs import generation_references +from opendirector.integrations.vllm_omni import VllmOmniGeneration + + +pytestmark = pytest.mark.cpu + +PNG = b'\x89PNG\r\n\x1a\n' +OMNI = {'kind': 'video', 'protocol': 'vllm_omni', 'url': 'http://localhost:18091/v1', 'modelId': 'Pika-H3', + 'videoAdapter': 'fasth3', 'apiKey': '', 'authMode': 'none'} + + +@pytest.mark.parametrize('adapter, expected', [('fasth3', 8), ('fasth3_dual', 8), ('minimax_h3', 8), ('standard', None)]) +def test_every_h3_adapter_declares_keyframes(adapter, expected): + assert input_rules({**OMNI, 'videoAdapter': adapter}).get('maxKeyframes') == expected + + +def model(**extra): + config = {'kind': 'video', 'url': 'http://model.test/v1', 'modelId': 'Pika-H3', 'connectionType': 'self_hosted', + 'protocol': 'vllm_omni', 'authMode': 'none', 'videoAdapter': 'fasth3', **extra} + return ModelConfigPublic(id=uuid4(), inputRules=input_rules(config), **config) + + +def picture(role='reference', time=None, kind='image', transmission='content'): + return ResolvedReference(referenceId=uuid4(), role=role, frameTimeMs=time, transmission=transmission, + asset=AssetRef(assetId=uuid4(), revision=1, fingerprint='sha256:' + '0' * 64, kind=kind), + metadata=MediaMetadata(mimeType='image/png' if kind == 'image' else 'video/mp4', size=10, width=32, height=24, + durationSeconds=None if kind == 'image' else 5)) + + +def spec(target, mode='reference', seconds=5): + return VideoGenerationSpec(id=uuid4(), projectId=uuid4(), kind='video', purpose='generation', modelConfigId=target.id, + prompt='A dancer', parameters=VideoParameters(videoMode=mode, durationSeconds=seconds)) + + +def test_submission_accepts_keyframes_beside_a_reference(): + omni = model() + validate_generation(spec(omni), omni, (picture(), picture('keyframe', 1250), picture('keyframe', 4583)), submitting=True) + validate_generation(spec(omni), omni, (*[picture() for _ in range(9)], *[picture('keyframe', 100 * n) for n in range(8)]), submitting=True) + + +@pytest.mark.parametrize('references, message', [ + (lambda: (picture('keyframe', 1000),), '普通参考'), + (lambda: (picture(), picture('keyframe', None)), '时间点'), + (lambda: (picture(), picture('keyframe', 5000)), '早于视频结束'), + (lambda: (picture(), picture('keyframe', 1000), picture('keyframe', 1000)), '同一帧'), + (lambda: (picture(), picture('keyframe', 1000), picture('keyframe', 1020)), '同一帧'), + (lambda: (picture(), picture('keyframe', 4990)), '早于视频结束'), + (lambda: (picture(), *[picture('keyframe', 100 * n) for n in range(9)]), '最多指定 8 个'), +]) +def test_submission_rejects_invalid_keyframes(references, message): + omni = model() + with pytest.raises(ProjectError, match=message): + validate_generation(spec(omni), omni, references(), submitting=True) + + +def test_a_keyframe_needs_a_duration_to_be_checked_against(): + omni = model() + with pytest.raises(ProjectError) as error: + validate_generation(spec(omni, seconds=None), omni, (picture(), picture('keyframe', 14000)), submitting=True) + assert error.value.code == 'keyframe_time' + + +def test_keyframe_bytes_count_toward_the_request(): + omni = model() + def sized(role, size, time=None): + return picture(role, time).model_copy(update={'metadata': MediaMetadata(mimeType='image/png', size=size, width=32, height=24)}) + megabyte = 1024 * 1024 + validate_generation(spec(omni), omni, (sized('reference', megabyte), *[sized('keyframe', 20 * megabyte, 100 * n) for n in range(7)]), + submitting=True) + with pytest.raises(ValueError, match='总大小超过'): + validate_generation(spec(omni), omni, (sized('reference', megabyte), *[sized('keyframe', 25 * megabyte, 100 * n) for n in range(7)]), + submitting=True) + + +def test_native_h3_request_size_includes_its_guides(): + native = {**OMNI, 'videoAdapter': 'minimax_h3'} + megabyte = 1024 * 1024 + costume = {'id': str(uuid4()), 'name': 'costume.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + poses = [{'id': str(uuid4()), 'name': f'pose-{index}.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + for index in range(2)] + def task_with(pose_bytes): + assets = {costume['id']: (PNG + b'c' * (20 * megabyte), costume), + **{pose['id']: (PNG + b'p' * pose_bytes, pose) for pose in poses}} + task = {'kind': 'video', 'projectId': 'owner', 'prompt': '飞天起舞', 'referenceIds': list(assets), 'videoMode': 'reference', + 'parameters': {'seconds': 5}, + 'referenceRoles': [{'assetId': costume['id'], 'role': 'reference'}, + *[{'assetId': pose['id'], 'role': 'keyframe', 'frameTimeMs': 1000 * (n + 1)} for n, pose in enumerate(poses)]]} + return SimpleNamespace(asset=lambda owner, key: assets[key]), task + store, task = task_with(megabyte) + assert len(generation_references(store, task, native)['guides']) == 2 + store, task = task_with(15 * megabyte) + with pytest.raises(ProjectError, match='请求过大'): + generation_references(store, task, native) + + +def test_keyframes_need_reference_mode_and_a_supporting_model(): + omni = model() + control = picture('control', kind='video') + with pytest.raises(ProjectError, match='素材参考模式'): + validate_generation(spec(omni, 'control'), omni, (control, picture(), picture('keyframe', 1000)), submitting=True) + plain = model(videoAdapter='standard') + with pytest.raises(ProjectError, match='不支持指定帧'): + validate_generation(spec(plain, 'first_frame'), plain, (picture('keyframe', 1000),), submitting=True) + + +def test_a_keyframe_a_mode_leaves_out_is_refused_and_not_dropped(): + omni = model(videoAdapter='fasth3_dual') + first = picture('first_frame') + with pytest.raises(ProjectError, match='素材参考模式') as error: + validate_generation(spec(omni, 'first_frame'), omni, (first, picture('keyframe', 2000, transmission='context_only')), submitting=True) + assert error.value.code == 'keyframe_mode' + + +def test_keyframe_codes_reach_clients_and_read_in_english(): + from typing import get_args + + from opendirector.domain.creation.commands import IssueCode + from opendirector_api.localization import localized_error_for_language + + def flat(annotation): + return {name for item in get_args(annotation) for name in (flat(item) if get_args(item) else {item})} + + codes = {'keyframe_unsupported', 'keyframe_mode', 'keyframe_kind', 'keyframe_count', 'keyframe_needs_reference', 'keyframe_time', + 'keyframe_image'} + assert codes <= flat(IssueCode) + for code in codes: + english = localized_error_for_language('en-US', chinese='关键帧必须是图片。', status=422, code=code) + assert english.isascii() and 'keyframe' in english.lower() + assert localized_error_for_language('zh-CN', chinese='关键帧必须是图片。', status=422, code=code) == '关键帧必须是图片。' + + +def test_the_cli_refuses_a_time_that_is_not_a_finite_number(): + from typer.testing import CliRunner + + from opendirector.cli import app + for moment in ('inf', 'nan', '1e400', 'soon'): + result = CliRunner().invoke(app, ['--project', str(uuid4()), 'video', 'create', '--model', str(uuid4()), '--prompt', 'x', '--duration', '5', + '--x', '0', '--y', '0', '--reference-item', str(uuid4()), '--keyframe', f'{uuid4()}@{moment}']) + assert not isinstance(result.exception, OverflowError), moment + + +def test_the_cli_creates_a_video_with_a_keyframe_at_its_time(tmp_path, monkeypatch): + from fastapi.testclient import TestClient + from PIL import Image + from typer.testing import CliRunner + + from opendirector import cli + from opendirector.infrastructure.local_projects import LocalProjects + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector_api.main import create_app + + api = TestClient(create_app(LocalProjects(tmp_path)), headers={'X-OpenDirector-Request': '1'}) + client = httpx.Client + + def forward(request): + response = api.request(request.method, request.url.path, headers=dict(request.headers), content=request.read()) + return httpx.Response(response.status_code, headers=response.headers, content=response.content) + + monkeypatch.setattr(cli.httpx, 'Client', lambda **kwargs: client(**kwargs, transport=httpx.MockTransport(forward))) + project = str(uuid4()) + + def invoke(*arguments): + result = CliRunner().invoke(cli.app, ['--project', project, *arguments]) + assert result.exit_code == 0, result.output + return json.loads(result.output) + + invoke('project', 'create', '--name', 'Keyframes') + items = [] + for name in ('costume.png', 'pose.png'): + file = tmp_path / name + Image.new('RGB', (64, 48), 'blue').save(file) + invoke('asset', 'import', str(file), '--kind', 'image') + asset = next(value for value in invoke('project', 'show')['assets'] if value['name'] == name) + items.append(invoke('canvas', 'add-material', '--asset', asset['id'], '--x', str(400 * len(items)), '--y', '0')['canvasItems'][0]['id']) + costume, pose = items + model = ModelConfigs(tmp_path).save('video', 'http://127.0.0.1:9999/v1', 'FastVideo/FastVideo-FastH3-Omni-8-Step-V1', '', + connection_type='self_hosted', protocol='vllm_omni', auth_mode='none', video_adapter='fasth3') + created = invoke('video', 'create', '--model', model['id'], '--prompt', 'A dance', '--duration', '5', '--x', '900', '--y', '0', + '--reference-item', costume, '--keyframe', f'{pose}@1.25') + snapshot = invoke('project', 'show') + spec = next(value for value in snapshot['generationSpecs'] if value['id'] == created['specId']) + assert spec['parameters']['videoMode'] == 'reference' + stored = sorted((value for value in snapshot['references'] if value['targetSpecId'] == spec['id']), key=lambda value: value['order']) + assert [(value['source']['id'], value['role'], value.get('frameTimeMs')) for value in stored] == [ + (costume, 'reference', None), (pose, 'keyframe', 1250)] + + +def fixture(times=(1250, 4583)): + costume = {'id': str(uuid4()), 'name': 'costume.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + poses = [{'id': str(uuid4()), 'name': f'pose-{index}.png', 'kind': 'image', 'type': 'image/png', 'fingerprint': 'fixture'} + for index in range(len(times))] + assets = {costume['id']: (PNG + b'costume', costume), **{pose['id']: (PNG + pose['name'].encode(), pose) for pose in poses}} + store = SimpleNamespace(asset=lambda owner, key: assets[key]) + task = {'kind': 'video', 'projectId': 'owner', 'prompt': '飞天起舞', 'referenceIds': list(assets), 'videoMode': 'reference', + 'referenceRoles': [{'assetId': costume['id'], 'role': 'reference'}, + *[{'assetId': pose['id'], 'role': 'keyframe', 'frameTimeMs': time} for pose, time in zip(poses, times)]]} + task['parameters'] = video_parameters(task, {key: pair[1] for key, pair in assets.items()}, duration_seconds=5) + return store, task, costume, poses + + +def test_a_keyframe_is_a_guide_and_not_a_reference_picture(): + store, task, costume, poses = fixture() + prepared = generation_references(store, task, OMNI) + assert len(prepared['images']) == 1 + assert [(guide['name'], guide['frame']) for guide in prepared['guides']] == [('pose-0.png', 30), ('pose-1.png', 110)] + assert prepared['prompt'].count('