diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index c94c74953..07172bd96 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -46,6 +46,14 @@ 'higgsfield_frames': 'Each frame slot accepts one image. A last frame requires a first frame.', 'higgsfield_references': 'Reference mode requires at least one image, video, or audio clip. Check the reference roles.', 'higgsfield_prompt': 'MAGI-2 prompts allow up to 15,000 characters. Text-to-video requires a prompt.', + 'nextlabs_token': 'The NextLabs upload token is invalid.', + 'opendev_magi_model': 'Choose OpenDev MAGI-2 with the official API address.', + 'opendev_magi_key': 'Enter your OpenDev API key.', + 'opendev_magi_prompt': 'Enter a MAGI-2 prompt of up to 15,000 characters.', + 'opendev_magi_url': 'Enter a public HTTPS media URL readable without signing in.', + 'opendev_magi_reference_count': 'MAGI-2 accepts up to 10 images (local images and links combined), 5 video links, and 5 audio links.', + 'opendev_magi_local_reference': 'Configure a NextLabs upload token in the model service for local images. Use public links for video and audio references.', + 'opendev_magi_reference_model': 'This video model does not support media links.', "desktop_auth_required": "The desktop connection has expired. Reopen the application.", 'prompt_optimization_empty': 'Enter a prompt to optimize.', 'prompt_optimization_refs': 'Prompt references changed. Try again.', diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 4cf60d039..4fc87f417 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -282,6 +282,7 @@ def save_model_batch(value: ModelBatchInput): video_capabilities=video_capabilities(value), input_modalities=value.inputModalities, model_options=model_options(value), capabilities_supplied='videoCapabilities' in value.model_fields_set, capability_auto_check=value.capabilityAutoCheck, + next_labs_token=value.nextLabsToken.get_secret_value() if value.nextLabsToken is not None else None, storage=value.storage.model_dump() if value.storage is not None else None) @app.post('/api/model-configs/discover') @@ -304,7 +305,8 @@ def create_model_config(value: ModelConfigInput): return catalog.save(value.kind, value.url, value.modelId, value.apiKey.get_secret_value(), connection_type=value.connectionType, protocol=value.protocol, auth_mode=value.authMode, proxy_mode=value.proxyMode, video_adapter=value.videoAdapter, video_capabilities=video_capabilities(value), capabilities_supplied='videoCapabilities' in value.model_fields_set, input_modalities=value.inputModalities, - capability_auto_check=value.capabilityAutoCheck) + capability_auto_check=value.capabilityAutoCheck, + next_labs_token=value.nextLabsToken.get_secret_value() if value.nextLabsToken is not None else None) @app.post('/api/model-configs/capabilities') async def model_capabilities(value: ModelCapabilityRequest): @@ -319,7 +321,8 @@ def update_model_config(config_id: UUID, value: ModelConfigInput): return catalog.save(value.kind, value.url, value.modelId, value.apiKey.get_secret_value(), str(config_id), connection_type=value.connectionType, protocol=value.protocol, auth_mode=value.authMode, proxy_mode=value.proxyMode, video_adapter=value.videoAdapter, video_capabilities=video_capabilities(value), capabilities_supplied='videoCapabilities' in value.model_fields_set, input_modalities=value.inputModalities, - capability_auto_check=value.capabilityAutoCheck) + capability_auto_check=value.capabilityAutoCheck, + next_labs_token=value.nextLabsToken.get_secret_value() if value.nextLabsToken is not None else None) @app.delete("/api/model-configs/{config_id}", status_code=204) def delete_model_config(config_id: UUID): diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index 94c1446b1..19486f63c 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -29,7 +29,7 @@ class UrlSource(Model): class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' - protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] | None = None + protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'opendev_magi', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] | None = None authMode: Literal['none', 'bearer'] | None = None proxyMode: Literal['system', 'direct'] | None = None capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None) @@ -45,6 +45,7 @@ class ModelConfigInput(ModelConnection): url: str = Field(max_length=2048) modelId: str = Field(max_length=200) apiKey: SecretStr = SecretStr("") + nextLabsToken: SecretStr | None = Field(default=None, max_length=8192) inputModalities: list[AgentInputModality] | None = Field(default=None, min_length=1, max_length=4) videoAdapter: VideoAdapter | None = None videoCapabilities: VideoCapabilities | None = None diff --git a/docs/README.md b/docs/README.md index 86cc0fe69..cc65622ce 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,6 +30,7 @@ This directory is the entry point for the repository's shared documentation. The | [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 | | [Video model capabilities](guides/video-model-capabilities.md) ([中文](guides/video-model-capabilities.zh-CN.md)) | Declaring output specifications supported by a service | Configuration fields or capability integration changes | +| [OpenDev video services](guides/opendev-video.md) ([中文](guides/opendev-video.zh-CN.md)) | MAGI-2, Seedance and NextLabs local image uploads | Provider setup or reference upload changes | | [Video gateway](guides/video-gateway.md) ([中文](guides/video-gateway.zh-CN.md)) | Serving several H3 LoRA variants from one vLLM-Omni server through the gateway started with the application | Gateway configuration keys, startup, or rewrite behavior change | | [Model availability / 模型可用状态](guides/model-availability.md) | Optional runtime declarations, automatic checks, shared admission and API/CLI/Agent queries | Capability protocol, refresh, or acceptance rules change | | [OpenAI Images](guides/openai-images.md) | Wiring gpt-image as an optional image service, request shape and failures | Integration fields, capability scope, or the OpenAI interface change | diff --git a/docs/development/lessons.md b/docs/development/lessons.md index fd378c294..81caa3e2b 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -6,6 +6,12 @@ When implementing or reviewing a change, trace the affected behavior from its en When work exposes a consequential risk or a recurring problem, add a lesson or update an existing one with the trigger, failure, suggested check, and a verifiable issue, PR, or commit. Add evidence when a problem recurs. Move requirements proven durable in practice into the validation guide, and revise or remove outdated lessons. Do not count distinct defects as repetitions of the same problem, or add a lesson for every routine fix. +## Passing local tests does not register them in CI + +- **Trigger / 触发:** Adding, renaming or deleting Python test modules when CI selects files through shard rules. / CI 通过分片规则选择文件时,新增、重命名或删除 Python 测试模块。 +- **Evidence / 证据:** [PR #685 review](https://github.com/ThinkFlowLab/OpenDirector/pull/685#discussion_r4809603999) found that `test_nextlabs_upload.py` and `test_opendev_magi.py` passed locally but were absent from `scripts/ci/python_shards.json`. Focused execution and pytest collection did not prove that CI selected them. / 两个模块本地通过,但未登记进分片清单;定向测试通过或成功收集用例不能证明 CI 会执行它们。 +- **Check / 检查:** After [PR #700](https://github.com/ThinkFlowLab/OpenDirector/pull/700), unlisted modules are discovered into default core. Maintain explicit agent-cli/media assignments and renamed or deleted listed paths according to dependencies and responsibility, preserving alphabetical ordering. Run the full module inventory assertion and inspect the selected shard using the [validation commands](validation.md#python-shard-registration). Each module must occur exactly once in the resolved inventory. Compare unrelated failures against the target base and link their tracking issue; do not weaken the assertion or report a failing inventory as passed. / PR #700 后未列出的模块自动归入默认 core;按依赖和职责维护 agent-cli/media 的显式登记及已登记路径的重命名或删除,保持字母排序;运行完整模块清单断言并检查分片选择结果,确保每个模块恰好登记一次。无关失败需对照目标基线并链接跟踪记录,不能放宽断言或把失败报告为通过。 + ## Parameter IDs can encode the environment rather than the scenario - **Trigger:** Comparing collected test IDs or per-test timing evidence across platforms or dependency versions. @@ -35,6 +41,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Preview follow-up:** [PR #465](https://github.com/ThinkFlowLab/OpenDirector/pull/465) initially opened the project for a prompt rewrite, which could contend with the browser's edit lease. A rewrite reads the saved snapshot and has no durable job to recover. Verify it can finish under a separate session and that a browser disconnect closes the server-side request. - **Async projection follow-up:** PR #193's structured-editor CI failure prompted a real-browser delayed-read regression. An older background projection could finish after an acknowledged editor save and restore an obsolete CAS basis, making the next save/publication fail. Recheck the editor transaction and captured snapshot at completion before installing either changed or apparently identical content. Keep publication versions fixed, test the actual save/retry/provenance path with a deterministic interleaving, and retain the original CI failure rather than treating a longer timeout or a rerun as its explanation. - **Publication lock follow-up:** [#562](https://github.com/ThinkFlowLab/OpenDirector/pull/562) exposed task polling failing during publication. [#539](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/46222060697/job/141218914874) exposed the same contention in upload staging before a timeline save. While a same-project publication is paused after journaling, exercise task reads and upload staging through HTTP. Staging uses its own handle lock and still validates the edit lease. Asset registration and timeline saves continue to use the project write rules. / **发布锁补充:** 在同一工程写入日志后暂停发布,经 HTTP 检查工具任务读取与素材暂存。暂存使用独立的句柄锁并验证编辑租约,素材登记和时间线保存仍走工程写入规则。 +- **Generation recovery follow-up:** [PR #685](https://github.com/ThinkFlowLab/OpenDirector/pull/685) exposed a read-only directory lookup in accepted-job recovery taking the writable catalog path while another job published. Pause an actual publication after journaling and recover an already accepted job; require the directory read to use the published manifest and the resumed job to produce exactly one result. Keep write-side locking and version checks intact. / **生成恢复补充:** 已接受任务恢复时的只读目录查询曾误走可写目录路径,与其他任务发布争锁。暂停已写入日志的真实发布,再恢复已接受任务;检查其读取已发布清单并且只生成一次结果,同时保留写入锁及版本校验。 - **Media representation follow-up:** [Issue #282](https://github.com/ThinkFlowLab/OpenDirector/issues/282) exposed copy/export paths that read displayed pixels and archive imports that displayed unsupported original bytes. A browser preview and an original asset need distinct read paths while retaining the same asset identity. Verify original bytes through download, fresh publication, cross-project paste fallback and archive round trips, including the first display after import. [PR #287 review](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5857373679) also exposed missing MIME-extension mappings and a fallback that could name preview PNG bytes as HEIC. Carry the expected original type into readers, reject a missing original, and check timeline/FCPXML packages as well as canvas archives. - **Upload acknowledgement follow-up:** Investigating [PR #287's camera sample](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5868923062) reproduced a failed preview being swallowed into a successfully saved empty generation item. Require a usable preview before completing a HEIF import, and assert the failure leaves the original registered without creating an empty item. Slow uploads also crossed the first save acknowledgement: default expansion and model display labels were mistaken for user edits. Compare effective settings while retaining actual content, model, frame-selection and lock conflicts; exercise upload into a newly created node and its reference composer before the first save finishes. diff --git a/docs/development/validation.md b/docs/development/validation.md index c2c301086..428a1685d 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -171,6 +171,23 @@ Local checks verify workflow syntax, trigger/permission boundaries and rejection ## Python 分层与迁移 / Python layers and transition + + +### Python 分片登记 / Python shard registration + +新增、重命名或删除 `tests/test_*.py` 时,检查 [`scripts/ci/python_shards.json`](../../scripts/ci/python_shards.json) 解析后的分片归属。未显式列出的模块自动归入默认 `core` 分片;需要 `agent-cli` 或 `media` 的模块应按依赖和职责显式登记。更新已登记模块的重命名或删除,并保持文件路径按字母排序。在已安装测试依赖的环境中,从仓库根目录运行以下检查;`core` 应替换为实际受影响的分片。 + +When adding, renaming or deleting `tests/test_*.py`, check the resolved assignments from [`scripts/ci/python_shards.json`](../../scripts/ci/python_shards.json). Unlisted modules are discovered into the default `core` shard. Explicitly list modules requiring `agent-cli` or `media` according to dependencies and responsibility; update listed paths when renaming or deleting them and keep paths alphabetically ordered. Run these checks from the repository root with test dependencies installed; replace `core` with the affected shard. + +```sh +python -m pytest tests/test_ci_layers.py::test_repo_python_shards_manifest_covers_every_test_module_once -q --tb=short +python scripts/ci/check_test_layers.py --list-shard core +``` + +第一条检查解析后的清单是否恰好包含每个模块一次;第二条显示 CI 分片实际选择的文件,需确认目标模块出现在预期分片。继续执行受影响的测试;清单检查通过不代表测试通过,本地测试通过也不代表已登记进 CI。如果完整清单检查失败,对照目标基线区分本次遗漏与已有缺口,修复本次遗漏并为其他缺口附上跟踪记录,保留失败结论。 + +The first command checks that the resolved inventory contains every module exactly once; the second shows the files selected for a CI shard, which must include the intended modules. Also execute the affected tests: inventory success does not prove test success, and local test success does not prove CI registration. If the inventory fails, compare with the target base, fix omissions introduced by the change, link tracking records for other gaps, and retain the failed result. + ### 耗时证据 / Timing evidence Python CI 为全量套件和独立 bundled OpenCode 回归分别保存 JUnit XML、`--durations=50` 日志,以及 `--ci-profile` 生成的 JSON/Markdown;从运行的 `python-test-evidence-` artifact 下载,保存 14 天。JSON 记录 SHA、系统、Python/pytest 版本、筛选条件、逐用例 setup/call/teardown 耗时、结果、显式层级与未标记默认归属,不记录 stdout、失败正文或局部变量。 @@ -734,3 +751,11 @@ Timing JSON includes per-case hardware and aggregate hardware counts. Ark duration normalization is shared by capability admission and the submitted JSON through `normalize_ark_parameters`. Verify actual serialized POST values against admission for integral floats, integers, fractional values, booleans, strings and omitted duration in `tests/test_ark_availability.py`; do not round fractional durations or mutate saved intent. Ark 能力检查和发送 JSON 共用 `normalize_ark_parameters` 归一化时长。在 `tests/test_ark_availability.py` 中比对实际 POST 序列化参数与检查参数,覆盖整数浮点数、整数、小数、布尔值、字符串及省略时长;不对小数时长取整,不修改原始生成意图。 + +### OpenDev MAGI-2 local image uploads + +Run `python -m pytest tests/test_opendev_magi.py tests/test_nextlabs_upload.py tests/test_model_configs.py -q`. These checks use actual image bytes, persisted commands and mocked provider HTTP, not paid generation. They cover token secrecy, local and linked image limits, upload destination/header validation, completion validation, one submission, adoption and reopening. + +For both interface languages, run `python tests/browser/nextlabs_server.py --port 8507`, Vite with `OPENDIRECTOR_API_URL=http://127.0.0.1:8507 npm run dev -- --port 5507`, and `node tests/browser/nextlabs_upload.mjs`. The isolated fixture checks service configuration, file-picker import, followed image references, generation, retained input snapshots and reopening. Screenshots and receipts go to `output/playwright/nextlabs`. No real upload credential or paid model call is used. + +上述 Python 测试使用真实图片字节、持久化命令和模拟服务 HTTP,验证令牌保密、混合图片数量限制、上传地址及请求头检查、上传确认、单次提交、结果采用和重开。浏览器夹具在隔离工程中验证中英文服务配置、文件选择器导入、跟随图片参考、生成和重开后的输入快照,截图与回执保存在 `output/playwright/nextlabs`。这些检查不使用真实上传凭据,也不调用付费生成服务。 diff --git a/docs/guides/opendev-video.md b/docs/guides/opendev-video.md new file mode 100644 index 000000000..6cafffc9c --- /dev/null +++ b/docs/guides/opendev-video.md @@ -0,0 +1,22 @@ +# Generate storyboard video with OpenDev + +[中文](opendev-video.zh-CN.md) + +In **Settings → Model connections → Video → Add service**, select **OpenDev video** and choose MAGI-2 or Seedance. Enter your OpenDev Credits API key and choose the model IDs available to your account. + +| Preset | Base URL | Video protocol | Model ID | +| --- | --- | --- | --- | +| MAGI-2 | `https://api.openai-next.com` | `opendev_magi` | `magi-2` | +| Seedance | `https://api.openai-next.com/seedance/api/v3` | `volcengine` | For example, `doubao-seedance-2-0-260128`. Use **Add manually** for other IDs enabled on your account. | + +Select the saved model in a storyboard video node, enter a prompt and generate. For a Seedance text-to-video request, leave the frames empty and use automatic resolution. You can preview a completed clip on the node and adopt it from the result history. + +MAGI-2 requires a prompt of up to 15,000 characters and generates 1080p video in whole seconds from 4 to 30. Choose the aspect ratio and whether to generate audio. To guide the result, add up to 10 images, 5 videos and 5 audio files under **Reference media links**. Enter one public HTTPS URL per file, readable without a sign-in. Use links your provider can fetch and keep them available while the task is running. To use local reference images, edit the MAGI-2 service and enter a **NextLabs upload token**: a NextLabs personal access token with `works:write` permission, separate from the model API key. Connect image nodes to the video node, enter a prompt, and generate. OpenDirector uploads the images to NextLabs and submits their public HTTPS URLs automatically. Local images and image links share the 10-image limit; each local image must be a valid PNG, JPEG, WebP or GIF, at most 30,000,000 bytes. Local video and audio references still require public links. + +NextLabs uploads are publicly accessible by URL and normally expire after 24 hours; the original assets remain in your local project. Upload tokens are stored with local model credentials and are excluded from project snapshots and public model responses. Leave the token field blank to preserve a saved token, or select **Remove the saved upload token** to remove it. Upload errors stop before the video generation request. After a generation request has been accepted, recovery polls its task ID without uploading again. If an upload was interrupted before confirmation, review the failed task before starting a new attempt. + +Create a personal token in NextLabs with `works:write` permission; do not use the OpenDev model API key in this field. The [NextLabs API schema](https://labs.openai-next.com/v1/openapi.json) documents token creation (`POST /v1/me/tokens`, authenticated with your NextLabs session) and the upload ticket / PUT / completion flow. Configure the token in the application, never in a project prompt. + +OpenDirector keeps the returned MAGI-2 task ID for polling and recovery. When a result link expires, resuming the original task queries a fresh link. If submission times out before an ID is returned, check the OpenDev console for the original task before trying again, since a new submission can incur a new charge. OpenDev's documented MAGI-2 flow has no remote cancellation call. After stopping locally, check the provider console for the remote task. + +Protocol references, accessed 2026-12-02. [MAGI-2 async tasks](https://labs.openai-next.com/docs/tasks#magi-2) · [Input files](https://labs.openai-next.com/docs/files) · [Seedance async tasks](https://labs.openai-next.com/docs/tasks#seedance-ark) diff --git a/docs/guides/opendev-video.zh-CN.md b/docs/guides/opendev-video.zh-CN.md new file mode 100644 index 000000000..bdcb673f8 --- /dev/null +++ b/docs/guides/opendev-video.zh-CN.md @@ -0,0 +1,22 @@ +# 使用 OpenDev 生成分镜视频 + +[English](opendev-video.md) + +打开 **设置 → 模型接入 → 视频 → 添加服务**,在 **OpenDev 视频** 中选择 MAGI-2 或 Seedance。填写 OpenDev Credits API Key,选择账号已开通的模型。 + +| 预设 | 服务地址 | 视频协议 | 模型 ID | +| --- | --- | --- | --- | +| MAGI-2 | `https://api.openai-next.com` | `opendev_magi` | `magi-2` | +| Seedance | `https://api.openai-next.com/seedance/api/v3` | `volcengine` | 示例 `doubao-seedance-2-0-260128`。账号开通的其他 ID 可通过 **手动添加** 填入。 | + +回到分镜视频节点,选中已保存的模型,输入提示词后生成。使用 Seedance 纯文生视频时,首尾帧可以留空,分辨率选 **自动**。生成完成后,可在节点中预览,并从版本列表采用视频。 + +MAGI-2 要求填写提示词,最多 15,000 字。输出为 1080p,时长支持 4–30 秒整数,可选画幅及是否生成音频。在 **参考素材链接** 中,每个文件填写一条无需登录即可读取的公网 HTTPS 链接。最多可加 10 个图片链接、5 个视频链接和 5 个音频链接。链接需在任务运行期间保持可访问。使用本地参考图片时,在 MAGI-2 服务设置中填写 **NextLabs 上传令牌**:这是具有 `works:write` 权限的 NextLabs 个人令牌,与模型 API Key 不同。将图片节点连接至视频节点,填写提示词并生成,OpenDirector 会自动上传图片并提交返回的公网 HTTPS 链接。本地图片和图片链接合计最多 10 张;每张本地图片须为有效的 PNG、JPEG、WebP 或 GIF,大小不超过 30,000,000 字节。本地视频和音频仍需使用公网链接。 + +NextLabs 上传的图片可通过链接公开访问,通常在 24 小时后清理;原始素材保留在本地工程。上传令牌保存在本机模型凭据中,不进入项目快照或公开模型响应。编辑时留空会保留已保存令牌,勾选 **移除已保存的上传令牌** 可删除它。上传失败会阻止提交视频生成;生成请求被接受后,恢复会查询原任务 ID,不重复上传。上传未确认就中断时,请先检查失败任务,再开始新尝试。 + +在 NextLabs 创建具有 `works:write` 权限的个人令牌,不要将 OpenDev 模型 API Key 填入此字段。[NextLabs API 文档](https://labs.openai-next.com/v1/openapi.json) 描述了令牌创建接口(`POST /v1/me/tokens`,使用 NextLabs 登录会话鉴权)及申请上传地址、PUT 文件、确认上传的流程。请在应用设置中配置令牌,不要写入工程提示词。 + +OpenDirector 保存 MAGI-2 的任务 ID 以便继续查询。结果链接过期后,恢复原任务可刷新下载地址。如果提交超时且未返回 ID,请先在 OpenDev 控制台核对原任务,再决定是否重试,因为新提交可能重复计费。OpenDev 的 MAGI-2 文档没有提供远程取消接口。本地停止后,请在服务控制台核对远程任务。 + +协议查阅于 2026-12-02。[MAGI-2 异步任务](https://labs.openai-next.com/docs/tasks#magi-2) · [输入文件要求](https://labs.openai-next.com/docs/files) · [Seedance 异步任务](https://labs.openai-next.com/docs/tasks#seedance-ark) diff --git a/docs/guides/video-model-capabilities.md b/docs/guides/video-model-capabilities.md index 87dcc4aba..e541a4e48 100644 --- a/docs/guides/video-model-capabilities.md +++ b/docs/guides/video-model-capabilities.md @@ -69,6 +69,8 @@ Protocol references: [create task](https://platform.minimax.cn/docs/api-referenc Higgsfield Open supports `sand/magi-2` through one video connection: text, first/last frames and mixed image/video/audio references. Output is 1080p at 4–30 seconds with optional generated audio. See the [MAGI-2 guide](higgsfield-magi-2.md) for setup, input limits and recovery. +The OpenDev video presets offer MAGI-2 and Seedance through an OpenDev API key. MAGI-2 accepts a prompt and public HTTPS media links in the video composer. See the [OpenDev video guide](opendev-video.md) for connection settings and input limits. + Kling 4.0 uses the separate `kling_video` protocol and picks the official submit path for text, first/last frames and image references, sharing the existing task query, recovery and result-adoption flow. Its fixed capabilities are published by the backend. `kling-4.0` supports 720P / 1080P, 3–30 seconds and first/last frames; `kling-4.0-flash` supports 720P, 3–20 seconds and a first frame, without a last frame. Both models support image references and native audio, and do not accept custom pixel sizes. Setup and input limits are in the [English guide](kling-video.md) and the [Chinese guide](kling-video.zh-CN.md). MiniMax official video offers four models; adding a service selects all of them by default, and they become active after saving. Editing an existing service keeps the previous selection. Standard H3 supports 768P / 2K and 4–15 seconds; Highspeed and Lite support 480P / 768P and 4–15 seconds; Max supports 480P / 768P and 5–15 seconds. Output tiers and durations are validated per model by the backend. diff --git a/docs/guides/video-model-capabilities.zh-CN.md b/docs/guides/video-model-capabilities.zh-CN.md index ff297edbb..3f16eafab 100644 --- a/docs/guides/video-model-capabilities.zh-CN.md +++ b/docs/guides/video-model-capabilities.zh-CN.md @@ -69,6 +69,8 @@ Higgsfield Open 通过同一个视频连接支持 `sand/magi-2`:文本、首尾帧和图片、视频、音频混合参考。输出为 1080p,时长支持 4–30 秒,可以关闭生成音频。接入、输入限制与恢复说明见 [MAGI-2 指南](higgsfield-magi-2.zh-CN.md)。 +OpenDev 视频预设支持通过 OpenDev API Key 调用 MAGI-2 和 Seedance。MAGI-2 可在视频创作面板中输入提示词和公网 HTTPS 素材链接。连接方式和输入限制见 [OpenDev 视频指南](opendev-video.zh-CN.md)。 + 可灵 4.0 使用独立的 `kling_video` 协议,按文生、首尾帧和图片参考选择对应官方提交路径,共用现有任务查询、恢复和结果采用流程。固定能力由后端发布。`kling-4.0` 支持 720P / 1080P、3–30 秒及首尾帧;`kling-4.0-flash` 支持 720P、3–20 秒和首帧,不支持尾帧。两个型号均支持图片参考与原生音频,不填写自定义像素尺寸。接入与输入限制见[中文指南](kling-video.zh-CN.md)和[English guide](kling-video.md)。 MiniMax 官方视频提供四个型号,新增服务时默认全部勾选,保存后才启用;编辑已有服务时保留原有勾选。标准 H3 支持 768P / 2K、4—15 秒;Highspeed 和 Lite 支持 480P / 768P、4—15 秒;Max 支持 480P / 768P、5—15 秒。各型号的输出档位与时长由后端分别校验。 diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 459cf4ed0..f32da01e4 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -116,8 +116,7 @@ def __init__(self, projects, configs, provider=None, *, availability=None): self.availability = availability or ModelAvailability(configs) def directory(self, project_id): - with self.projects.local.transaction() as db: - return self.projects._find(db, project_id)[0] + return self.projects._published_manifest(project_id)[0] def get_job(self, project_id, job_id): return next( @@ -177,6 +176,9 @@ def _parameters(self, spec, config, node, records): 'video': {'duration': 5, 'ratio': 'adaptive', 'generate_audio': True}, 'audio': {'speaker': 'zh_female_vv_uranus_bigtts', 'audio_params': {'format': 'mp3', 'sample_rate': 24000}}}[spec.kind] intent = spec.parameters.model_dump(exclude_none=True) + if spec.kind == 'video' and config['protocol'] == 'opendev_magi': + from opendirector.domain.opendev_magi import parameters as opendev_magi_parameters + return opendev_magi_parameters(config, intent) if spec.kind == 'video' and config['protocol'] == 'higgsfield_open': from opendirector.domain.higgsfield import parameters as magi2_parameters return magi2_parameters(config, intent, node['videoMode'], diff --git a/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index 76732ce1e..c462037a2 100644 --- a/packages/core/src/opendirector/application/generation_runtime.py +++ b/packages/core/src/opendirector/application/generation_runtime.py @@ -106,7 +106,7 @@ async def _produce(self, config, task, submitted, result_ready, cache): if hasattr(self.provider, 'generate_all'): return tuple(await self.provider.generate_all(config, task, submitted, result_ready=result_ready, recovery_cache=cache)) - if task.get('protocol') == 'higgsfield_open': + if task.get('protocol') in {'higgsfield_open', 'opendev_magi'}: suffix, data = await self.provider.generate(config, task, submitted, result_ready=result_ready, recovery_cache=cache) elif hasattr(self.provider, 'resume_result'): diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 39b4ecffb..67195804c 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -384,7 +384,7 @@ def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared 'sourceAssetIds': source_ids, 'maskAssetId': mask_id, 'annotationAssetId': annotation_id, 'boxes': value.get('boxes') or [], 'parameters': parameters, 'modelConfigIds': {item: config['id'] for item, config in models.items()}, - 'modelSnapshots': {item: {key: val for key, val in config.items() if key not in {'apiKey', 'capabilityAutoCheck', 'availability'}} for item, config in models.items()}, 'requestedModelConfigIds': chosen, 'requires': list(needs), + 'modelSnapshots': {item: {key: val for key, val in config.items() if key not in {'apiKey', 'nextLabsToken', 'capabilityAutoCheck', 'availability'}} for item, config in models.items()}, 'requestedModelConfigIds': chosen, 'requires': list(needs), 'outputs': [], 'error': None, 'createdAt': _now(), 'finishedAt': None, 'revision': 1, 'workerId': self.worker_id, 'localState': 'active', 'cancelRequested': False, 'modelCalls': [], diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index d05e398fe..ea8cde5f4 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -602,6 +602,8 @@ def command_fingerprint(command: Command) -> str: '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', + 'opendev_magi_model', 'opendev_magi_key', 'opendev_magi_prompt', 'opendev_magi_url', + 'opendev_magi_reference_count', 'opendev_magi_local_reference', 'opendev_magi_reference_model', 'capability_unavailable', 'capability_paused', 'capability_connection_changed', 'capability_unsupported', 'preview_expired', 'storage_unavailable', 'submission_unknown', 'provider_error', 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 55e4a9b12..9b9e96cfa 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -8,6 +8,7 @@ from pydantic import Field, JsonValue, model_validator from opendirector.domain.minimax_models import MINIMAX_MODELS +from opendirector.domain import opendev_magi from opendirector.domain.image_presets import PRESETS from opendirector.domain.projects import ProjectError from opendirector.domain.generation import GenerationFailure, ResultCheck @@ -41,12 +42,21 @@ class ImageParameters(Contract): outputFormat: Literal['png'] = Field(default='png', description='Generated image encoding.') +class VideoReferenceUrl(Contract): + kind: Literal['image', 'video', 'audio'] = Field(description='Media type of the remote reference.') + url: str = Field(min_length=9, max_length=4096, pattern=r'^https://', + description='Public HTTPS media URL readable without signing in.') + + class VideoParameters(Contract): generateAudio: bool = Field(default=True, description='Include audio; value must be allowed by model inputRules.generateAudioOptions.') videoMode: VideoMode = Field(default='first_frame', description='Video generation input mode.') durationSeconds: Annotated[float, Field(strict=True, ge=1, le=60)] | None = Field(default=None, description='Duration in seconds; fractional values require model inputRules.fractionalDuration. Generated frames may be aligned by the model.') aspectRatio: str | None = Field(default=None, pattern=r'^[1-9]\d?:[1-9]\d?$', description='Output width-to-height ratio.') resolution: str = Field(default='auto', pattern=r'^(?:auto|[A-Z0-9][A-Z0-9_.-]{0,23})$', description='Requested output resolution.') + referenceMediaUrls: tuple[VideoReferenceUrl, ...] = Field( + default=(), max_length=sum(opendev_magi.REFERENCE_LIMITS.values()), exclude_if=lambda value: not value, + description='OpenDev MAGI-2 remote references, in the order supplied.') # Music models count audio frames at 25 per second, between 200 and 9000 frames. @@ -444,7 +454,8 @@ def execution_spec(spec, references, rules): mode = effective_video_mode({ 'mode': spec.parameters.videoMode, 'allowedModes': rules.videoModes, - 'hasNonTextMedia': any(ref.transmission != 'context_only' and ref.asset.kind != 'text' for ref in references), + 'hasNonTextMedia': bool(spec.parameters.referenceMediaUrls) or any( + ref.transmission != 'context_only' and ref.asset.kind != 'text' for ref in references), 'configured': True, }) if mode == spec.parameters.videoMode: @@ -511,6 +522,17 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if not written and not has_preset and not implicit_text_prompt(spec, references) and not optional_prompt: raise ValueError('请填写生成提示词。') rules = model.inputRules + if spec.kind == 'video': + links = spec.parameters.referenceMediaUrls + if rules.profile == opendev_magi.PROFILE: + if any(ref.asset.kind in {'video', 'audio'} or ref.asset.kind == 'image' and not rules.maxImages for ref in references): + raise ProjectError('本地图片需在模型服务中配置 NextLabs 上传令牌;视频和音频参考请使用公网链接。', 422, + code='opendev_magi_local_reference') + opendev_magi.validate_reference_urls([link.model_dump() for link in links]) + if len({ref.asset.assetId for ref in references if ref.asset.kind == 'image'}) + sum(link.kind == 'image' for link in links) > 10: + raise ProjectError('图片参考(本地图片与链接合计)最多 10 张。', 422, code='opendev_magi_reference_count') + elif links: + raise ProjectError('此视频模型不支持通过链接添加素材。', 422, code='opendev_magi_reference_model') if rules.referencesAllowed is False and references: raise ValueError('当前模型不支持参考素材,请移除参考后重试。') if rules.profile in {'moss-speech', 'minimax-speech'}: diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 9d62ba16b..299898d65 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -13,7 +13,7 @@ from .base import Contract ModelKind = Literal['agent', 'image', 'video', 'audio', 'vision'] -Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] +Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'opendev_magi', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score', 'vllm_omni_bodies'] VideoMode = Literal['first_frame', 'reference', 'continuation', 'control'] ImageQuality = Literal['auto', 'low', 'medium', 'high'] Count = Annotated[int, Field(strict=True, ge=0)] @@ -166,7 +166,7 @@ def model_name(cls, value): @model_validator(mode='after') def connection(self): allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, + 'video': {'higgsfield_open', 'opendev_magi', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} if self.protocol not in allowed[self.kind]: raise ValueError('Protocol is incompatible with model category') @@ -254,7 +254,7 @@ class ModelConfigPublic(ModelConnection): @classmethod def from_service(cls, config: dict, rules: InputRules) -> 'ModelConfigPublic': return cls.model_validate({key: value for key, value in config.items() - if key not in {'apiKey', 'storage'}} | {'inputRules': rules}) + if key not in {'apiKey', 'storage', 'nextLabsToken'}} | {'inputRules': rules}) class ModelConfigWrite(ModelConnection): @@ -263,7 +263,9 @@ class ModelConfigWrite(ModelConnection): capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None, description='Service automatic-check override; omission preserves the existing preference.') - @field_validator('apiKey') + nextLabsToken: SecretStr | None = Field(default=None, max_length=8192, description='NextLabs upload token; omission preserves it, an empty string removes it. Never included in public records.') + + @field_validator('apiKey', 'nextLabsToken') @classmethod def credential(cls, value): if value and any(ord(char) < 32 for char in value.get_secret_value()): diff --git a/packages/core/src/opendirector/domain/higgsfield.py b/packages/core/src/opendirector/domain/higgsfield.py index 28f04c420..5109da30f 100644 --- a/packages/core/src/opendirector/domain/higgsfield.py +++ b/packages/core/src/opendirector/domain/higgsfield.py @@ -43,6 +43,11 @@ def operation(mode, has_images): def parameters(config, intent, mode, has_images): validate_model(config) + output = normalize_output(config, intent) + return {'operation': operation(mode, has_images), **output} + + +def normalize_output(config, intent): capabilities = config.get('videoCapabilities') or magi2_capabilities() validate_outputs(capabilities) resolution = intent.get('resolution', 'auto') @@ -59,5 +64,4 @@ def parameters(config, intent, mode, has_images): audio = intent.get('generateAudio', True) if ratio not in RATIOS or not isinstance(audio, bool): raise ProjectError('请选择 MAGI-2 支持的画幅比例和音频选项。', 422, code='higgsfield_parameters') - return {'operation': operation(mode, has_images), 'duration': int(seconds), 'resolution': resolution, - 'ratio': ratio, 'generate_audio': audio} + return {'duration': int(seconds), 'resolution': resolution, 'ratio': ratio, 'generate_audio': audio} diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index 90d77dd56..893b85039 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -9,6 +9,7 @@ from .minimax_speech import MINIMAX_SPEECH_MODELS, MINIMAX_SPEECH_TEXT_CHARACTERS, is_minimax_speech from .projects import ProjectError from .higgsfield import AUDIO_BYTES, IMAGE_BYTES, VIDEO_BYTES, PROFILE, RATIOS, validate_model +from . import opendev_magi from .kling_models import KLING_MODELS, KLING_RATIOS, kling_capabilities from .bigmodel_image import is_bigmodel_image from .zhipu_speech import ZHIPU_DEFAULT_VOICE, ZHIPU_SPEECH_CHARACTERS, is_zhipu_speech @@ -35,6 +36,13 @@ def _adapter_rules(config): videoModes=['first_frame', 'reference'], frameRoles=['first_frame', 'last_frame'], audioReferenceStandalone=True, aspectRatios=list(RATIOS)) return rules + if config.get('protocol') == opendev_magi.PROTOCOL: + opendev_magi.validate_model(config) + rules.update(profile=opendev_magi.PROFILE, allowedKinds=['text', 'image'] if config.get('nextLabsToken') else ['text'], + maxImages=10 if config.get('nextLabsToken') else 0, imageBytes=30_000_000, requestBytes=410_000_000, maxPromptCharacters=opendev_magi.PROMPT_LIMIT, + videoModes=['first_frame', 'reference'], frameRoles=[], + aspectRatios=list(RATIOS), generateAudioOptions=[True, False]) + return rules if is_bigmodel_image(config): rules.update(profile='bigmodel-glm-image', allowedKinds=['text'], maxImages=0) return rules @@ -206,7 +214,7 @@ def input_rules(config): if library is not None: rules['voiceLibrary'] = library if config['kind'] == 'video': - rules['generateAudioOptions'] = [True, False] if config.get('protocol') in {'volcengine', 'bigmodel_video', 'higgsfield_open'} else [True] + rules.setdefault('generateAudioOptions', [True, False] if config.get('protocol') in {'volcengine', 'bigmodel_video', 'higgsfield_open'} else [True]) if config['kind'] == 'image' and rules['profile'] != 'vllm-omni-segmentation': from .image_output import image_outputs rules['imageOutputs'] = image_outputs(config, rules['profile']) diff --git a/packages/core/src/opendirector/domain/model_connection.py b/packages/core/src/opendirector/domain/model_connection.py index e94ecca57..0a5fb607a 100644 --- a/packages/core/src/opendirector/domain/model_connection.py +++ b/packages/core/src/opendirector/domain/model_connection.py @@ -10,7 +10,7 @@ def connection_fields(kind, connection_type='api', protocol=None, auth_mode=None protocol = protocol or ('openai' if kind == 'agent' or connection_type == 'self_hosted' and kind not in {'video', 'vision'} else 'vllm_omni' if connection_type == 'self_hosted' else 'volcengine') allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, + 'video': {'higgsfield_open', 'opendev_magi', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth', 'vllm_omni_bodies'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} auth_mode = auth_mode or ('none' if connection_type == 'self_hosted' else 'bearer') proxy_mode = proxy_mode if proxy_mode is not None else 'system' diff --git a/packages/core/src/opendirector/domain/opendev_magi.py b/packages/core/src/opendirector/domain/opendev_magi.py new file mode 100644 index 000000000..4d9aead0e --- /dev/null +++ b/packages/core/src/opendirector/domain/opendev_magi.py @@ -0,0 +1,59 @@ +"""Video generation through the OpenDev MAGI-2 gateway.""" +import ipaddress +from urllib.parse import urlsplit + +from .higgsfield import normalize_output +from .projects import ProjectError + + +BASE = 'https://api.openai-next.com' +MODEL = 'magi-2' +PROTOCOL = 'opendev_magi' +PROFILE = 'opendev-magi-2' +REFERENCE_LIMITS = {'image': 10, 'video': 5, 'audio': 5} +PROMPT_LIMIT = 15000 + + +def validate_model(config): + if (config['kind'] != 'video' or config['modelId'] != MODEL + or config['url'].rstrip('/') != BASE + or config.get('connectionType', 'api') != 'api' + or config.get('authMode', 'bearer') != 'bearer'): + raise ProjectError('请选择 OpenDev MAGI-2 及其官方 API 地址。', 422, code='opendev_magi_model') + + +def public_https_url(url): + """Check URL syntax without fetching files on behalf of the provider.""" + if not isinstance(url, str) or not url.startswith('https://') or len(url) > 4096: + return False + if any(char.isspace() or ord(char) < 32 or char == '\\' for char in url): + return False + try: + parts = urlsplit(url) + parts.port + host = (parts.hostname or '').rstrip('.') + except ValueError: + return False + if not host or '@' in parts.netloc or parts.fragment: + return False + try: + address = ipaddress.ip_address(host) + return address.is_global and not address.is_multicast + except ValueError: + return '.' in host and not host.endswith(('.localhost', '.local', '.internal', '.test')) + + +def validate_reference_urls(links): + if any(sum(link['kind'] == kind for link in links) > limit for kind, limit in REFERENCE_LIMITS.items()): + raise ProjectError('MAGI-2 最多支持 10 个图片链接、5 个视频链接和 5 个音频链接。', 422, + code='opendev_magi_reference_count') + if any(link['kind'] not in REFERENCE_LIMITS or not public_https_url(link['url']) for link in links): + raise ProjectError('请输入无需登录即可读取的公网 HTTPS 素材链接。', 422, code='opendev_magi_url') + + +def parameters(config, intent): + validate_model(config) + output = normalize_output(config, intent) + links = intent.get('referenceMediaUrls', ()) + validate_reference_urls(links) + return {**output, 'referenceMediaUrls': list(links)} diff --git a/packages/core/src/opendirector/domain/video_capabilities.py b/packages/core/src/opendirector/domain/video_capabilities.py index ac9ae1170..d21cdc689 100644 --- a/packages/core/src/opendirector/domain/video_capabilities.py +++ b/packages/core/src/opendirector/domain/video_capabilities.py @@ -10,6 +10,7 @@ from opendirector.domain.kling_models import kling_capabilities from opendirector.domain.bigmodel_video import cogvideo_capabilities, validate_cogvideo_outputs from opendirector.domain.higgsfield import magi2_capabilities, validate_outputs as validate_magi2_outputs +from opendirector.domain import opendev_magi VideoAdapter = Literal['auto', 'fasth3', 'fasth3_dual', 'minimax_h3', 'standard'] Second = Annotated[StrictInt, Field(ge=1, le=60)] @@ -72,7 +73,7 @@ def seedance_25_variant(model): def preset_capabilities(profile, model=''): - if profile == 'higgsfield-magi-2': + if profile in {'higgsfield-magi-2', opendev_magi.PROFILE}: return magi2_capabilities() if profile == 'bigmodel-cogvideox-3': return cogvideo_capabilities(model) @@ -113,7 +114,7 @@ def capability_fields(config, rules): validate_cogvideo_outputs(capabilities) if rules['profile'] == 'kling-official': validate_kling_outputs(capabilities, config['modelId']) - if rules['profile'] == 'higgsfield-magi-2': + if rules['profile'] in {'higgsfield-magi-2', opendev_magi.PROFILE}: validate_magi2_outputs(capabilities) if rules['profile'] in {'vllm-omni-h3', 'fasth3-omni'}: rules['fractionalDuration'] = True @@ -151,7 +152,7 @@ def check_video_config(kind, protocol, adapter, capabilities): if protocol == 'bigmodel_video': validate_cogvideo_outputs(capabilities) return capabilities - if protocol == 'higgsfield_open': + if protocol in {'higgsfield_open', opendev_magi.PROTOCOL}: validate_magi2_outputs(capabilities) return capabilities if protocol == 'kling_video': diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 00480d712..955366222 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -61,7 +61,7 @@ def _read(self) -> list[dict]: item.update(services[item['providerId']]) seen = set() for item in value["models"]: - if not {'id', 'kind', 'url', 'modelId', 'apiKey'} <= set(item) or set(item) - {'id', 'kind', 'url', 'modelId', 'apiKey', 'connectionType', 'protocol', 'authMode', 'proxyMode', 'videoAdapter', 'videoCapabilities', 'providerId', 'inputModalities', 'capabilityAutoCheck', 'storage'}: + if not {'id', 'kind', 'url', 'modelId', 'apiKey'} <= set(item) or set(item) - {'id', 'kind', 'url', 'modelId', 'apiKey', 'connectionType', 'protocol', 'authMode', 'proxyMode', 'videoAdapter', 'videoCapabilities', 'providerId', 'inputModalities', 'capabilityAutoCheck', 'storage', 'nextLabsToken'}: raise ValueError() if 'capabilityAutoCheck' in item and type(item['capabilityAutoCheck']) is not bool: raise ValueError() @@ -78,6 +78,7 @@ def _read(self) -> list[dict]: if 'videoAdapter' not in item: item['videoAdapter'] = ('minimax_h3' if item['modelId'].rsplit('/', 1)[-1].lower() == 'minimax-h3' else 'fasth3') if item['kind'] == 'video' and item['protocol'] == 'vllm_omni' else 'auto' + self._upload_token(item, None, item.get('nextLabsToken')) item['inputModalities'] = agent_input_modalities(item['kind'], item.get('inputModalities')) item['videoCapabilities'] = check_video_config(item['kind'], item['protocol'], item['videoAdapter'], item.get('videoCapabilities')) if item['authMode'] == 'bearer' and not fields['apiKey']: @@ -116,7 +117,17 @@ def resolve(self, config_id: str, kind: str) -> dict: raise ProjectError("所选模型不存在或类别不符,请在设置中配置并重新选择。", 409) return dict(item) - def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str | None = None, *, connection_type='api', protocol=None, auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, capabilities_supplied=False, input_modalities=None, capability_auto_check=None) -> dict: + @staticmethod + def _upload_token(item, existing, supplied): + if item['protocol'] != 'opendev_magi': + return + token = supplied if supplied is not None else (existing or {}).get('nextLabsToken', '') + if not isinstance(token, str) or len(token) > 8192 or any(char.isspace() or ord(char) < 32 for char in token): + raise ProjectError('NextLabs 上传令牌格式无效。', 422, code='nextlabs_token') + if token: + item['nextLabsToken'] = token + + def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str | None = None, *, connection_type='api', protocol=None, auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, capabilities_supplied=False, input_modalities=None, capability_auto_check=None, next_labs_token=None) -> dict: if capability_auto_check is not None and type(capability_auto_check) is not bool: raise ProjectError('自动能力检查设置必须为布尔值。') if kind not in MODEL_KINDS: @@ -142,6 +153,7 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str raise ProjectError('请填写 API Key,或将鉴权方式设为无需鉴权。') fields['apiKey'] = existing['apiKey'] item = {'id': config_id or str(uuid4()), 'kind': kind, **fields, **connection} + self._upload_token(item, existing, next_labs_token) auto_check = capability_auto_check if capability_auto_check is not None else (existing or {}).get('capabilityAutoCheck') if auto_check is not None: item['capabilityAutoCheck'] = auto_check @@ -216,7 +228,7 @@ def _write(self, models: list[dict]) -> None: def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, config_id: str | None = None, *, connection_type='api', protocol=None, - auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, input_modalities=None, model_options=None, capabilities_supplied=False, capability_auto_check=None, storage=None) -> list[dict]: + auth_mode=None, proxy_mode=None, video_adapter=None, video_capabilities=None, input_modalities=None, model_options=None, capabilities_supplied=False, capability_auto_check=None, storage=None, next_labs_token=None) -> list[dict]: if capability_auto_check is not None and type(capability_auto_check) is not bool: raise ProjectError('自动能力检查设置必须为布尔值。') if kind not in MODEL_KINDS or not 1 <= len(model_ids) <= 200: @@ -261,6 +273,7 @@ def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, old = existing item = {'id': old['id'] if old else str(uuid4()), 'kind': kind, **field, **connection, 'apiKey': key, 'providerId': provider_id, 'videoAdapter': video_adapter or 'auto'} + self._upload_token(item, old or existing, next_labs_token) if auto_check is not None: item['capabilityAutoCheck'] = auto_check if storage_values is not None: diff --git a/packages/core/src/opendirector/integrations/model_capabilities.py b/packages/core/src/opendirector/integrations/model_capabilities.py index c4a3ceeb2..bb279548f 100644 --- a/packages/core/src/opendirector/integrations/model_capabilities.py +++ b/packages/core/src/opendirector/integrations/model_capabilities.py @@ -9,6 +9,7 @@ from opendirector.domain.kling_models import KLING_MODELS, kling_capabilities from opendirector.domain.bigmodel_video import COGVIDEO_MODEL, cogvideo_capabilities from opendirector.domain.higgsfield import MODEL as MAGI2_MODEL, magi2_capabilities +from opendirector.domain import opendev_magi from opendirector.domain.video_capabilities import VideoCapabilities from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment from opendirector.integrations.volcengine import endpoint @@ -18,6 +19,8 @@ async def read_service_models(config, transport=None): + if config.get('protocol') == opendev_magi.PROTOCOL: + return [{'id': opendev_magi.MODEL, 'videoCapabilities': magi2_capabilities()}] if config.get('protocol') == 'higgsfield_open': return [{'id': MAGI2_MODEL, 'videoCapabilities': magi2_capabilities()}] if config.get('protocol') == 'bigmodel_video': diff --git a/packages/core/src/opendirector/integrations/nextlabs_upload.py b/packages/core/src/opendirector/integrations/nextlabs_upload.py new file mode 100644 index 000000000..b95501ada --- /dev/null +++ b/packages/core/src/opendirector/integrations/nextlabs_upload.py @@ -0,0 +1,71 @@ +"""NextLabs reference uploads; model credentials never reach the upload service.""" +import asyncio +import hashlib +import json +from uuid import UUID + +import httpx + +from opendirector.domain.opendev_magi import public_https_url +from opendirector.integrations.generation_errors import checked, protocol_failure, transport_failure +from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, public_target, trust_environment +from opendirector.integrations.volcengine import bounded + + +BASE = 'https://labs.openai-next.com' + + +async def upload_reference(config, data, mime, *, transport, cache, record, asset_id): + token = config.get('nextLabsToken') + if not token or cache is None: + raise protocol_failure('prepare') + secrets = (token, config.get('apiKey', '')) + fingerprint = hashlib.sha256(data).hexdigest() + uploads = record.setdefault('uploads', {}) + saved = uploads.get(asset_id) + if saved: + if saved.get('fingerprint') != fingerprint or saved.get('mimeType') != mime: + raise protocol_failure('prepare') + if saved.get('status') == 'ready' and public_https_url(saved.get('url')): + return saved['url'] + raise protocol_failure('prepare') + uploads[asset_id] = {'fingerprint': fingerprint, 'mimeType': mime, 'status': 'requesting'} + await asyncio.to_thread(cache.save_submission, record) + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=transport, + trust_env=trust_environment(BASE, config=config), timeout=httpx.Timeout(240, connect=15), + follow_redirects=False) as client: + async def request(path, **kwargs): + async with client.stream('POST', BASE + path, headers={'Authorization': f'Bearer {token}'}, + extensions={'model_secrets': secrets}, **kwargs) as response: + value = json.loads(await bounded(response, stage='prepare', secrets=secrets, limit=1024 * 1024)) + if not isinstance(value, dict): + raise protocol_failure('prepare') + return value + + ticket = await request('/v1/uploads', json={'purpose': 'reference', 'mimeType': mime, 'bytes': len(data)}) + upload_id = str(UUID(ticket['id'])) + upload = ticket['upload'] + if upload['method'] != 'PUT' or not public_https_url(ticket['url']): + raise protocol_failure('prepare') + headers = httpx.Headers(upload['headers']) + if (set(headers) != {'content-type', 'if-none-match'} or headers['content-type'] != mime + or headers['if-none-match'] != '*'): + raise protocol_failure('prepare') + pinned, host_headers, extensions = await public_target(upload['url'], schemes=('https',), + unsafe=lambda: protocol_failure('prepare'), unresolved=lambda: transport_failure('prepare')) + headers.update(host_headers) + extensions['model_secrets'] = secrets + uploads[asset_id].update(id=upload_id, url=ticket['url'], status='uploading') + await asyncio.to_thread(cache.save_submission, record) + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=transport, trust_env=False, + timeout=httpx.Timeout(240, connect=15), follow_redirects=False) as storage: + async with storage.stream('PUT', pinned, headers=headers, extensions=extensions, content=data) as response: + await checked(response, stage='prepare', secrets=secrets) + ready = await request('/v1/uploads/' + upload_id + '/complete') + if (ready.get('id') != upload_id or ready.get('status') != 'ready' + or ready.get('purpose') != 'reference' or ready.get('mimeType') != mime + or ready.get('bytes') != len(data) or ready.get('url') != ticket['url']): + raise protocol_failure('prepare') + uploads[asset_id]['status'] = 'ready' + await asyncio.to_thread(cache.save_submission, record) + return ready['url'] diff --git a/packages/core/src/opendirector/integrations/opendev_magi.py b/packages/core/src/opendirector/integrations/opendev_magi.py new file mode 100644 index 000000000..a7d134cc7 --- /dev/null +++ b/packages/core/src/opendirector/integrations/opendev_magi.py @@ -0,0 +1,141 @@ +"""OpenDev MAGI-2 creation, polling and credential-free result download.""" +import asyncio +import json +from io import BytesIO +from PIL import Image, UnidentifiedImageError +from urllib.parse import quote + +import httpx + +from opendirector.domain import opendev_magi +from opendirector.domain.projects import ProjectError +from opendirector.integrations.generation_errors import protocol_failure, provider_failure, transport_failure +from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment +from opendirector.integrations.reference_inputs import generation_references, references, image_type +from opendirector.integrations.nextlabs_upload import upload_reference +from opendirector.integrations.volcengine import VolcengineGeneration, bounded +from opendirector.media.probe import require_ffprobe + + +ENDPOINT = opendev_magi.BASE + '/miga/v2/generations' +PENDING = {'submitted', 'created', 'pending', 'queued', 'queueing', 'in_progress', 'processing', 'running', 'generating'} +FAILURES = {'failed': 'failed', 'canceled': 'cancelled', 'cancelled': 'cancelled', 'expired': 'expired'} + + +class OpenDevMagiGeneration(VolcengineGeneration): + def validate(self, kind, config): + opendev_magi.validate_model({**config, 'kind': kind}) + if not config.get('apiKey'): + raise ProjectError('请填写 OpenDev API Key。', 422, code='opendev_magi_key') + require_ffprobe() + + def prepare_inputs(self, project_id, task, config, *, complete=True): + prepared = generation_references(self.store, {**task, 'projectId': project_id}, config, complete=complete) + prompt = prepared['prompt'] + if complete and (not prompt.strip() or len(prompt) > opendev_magi.PROMPT_LIMIT): + raise ProjectError('请填写 MAGI-2 提示词,最多 15,000 字。', 422, code='opendev_magi_prompt') + media = [] + for data, meta, kind in references(self.store, project_id, task['referenceIds']): + if kind == 'text': + continue + if kind != 'image' or not config.get('nextLabsToken'): + raise ProjectError('本地图片需在模型服务中配置 NextLabs 上传令牌;视频和音频参考请使用公网链接。', 422, + code='opendev_magi_local_reference') + mime = image_type(data) + try: + with Image.open(BytesIO(data)) as image: + image.verify() + except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError): + mime = None + if mime is None or len(data) > 30_000_000: + raise ProjectError('图片需为有效的 JPEG、PNG、WebP 或 GIF,单张小于 30 MB。', 422, code='higgsfield_image') + media.append({'assetId': str(meta['id']), 'fingerprint': meta['fingerprint'], 'mimeType': mime}) + links = task.get('parameters', {}).get('referenceMediaUrls', []) + if len(media) + sum(link['kind'] == 'image' for link in links) > 10: + raise ProjectError('图片参考(本地图片与链接合计)最多 10 张。', 422, code='opendev_magi_reference_count') + return {'profile': opendev_magi.PROFILE, 'references': prepared['manifest'], 'prompt': prompt, 'media': media} + + async def generate(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + self.validate(task['kind'], config) + secrets = (config['apiKey'], config.get('nextLabsToken', '')) + stage = 'poll' if task.get('externalTaskId') else 'prepare' + try: + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.transport, + trust_env=trust_environment(ENDPOINT, config=config), timeout=httpx.Timeout(240, connect=15), + follow_redirects=False) as client: + async def request(method, url, **kwargs): + async with client.stream(method, url, headers=auth_headers(config), + extensions={'model_secrets': secrets}, **kwargs) as response: + result = json.loads(await bounded(response, stage=stage, secrets=secrets)) + if not isinstance(result, dict): + raise protocol_failure(stage) + return result + + external_id = task.get('externalTaskId') + if not external_id: + prepared = await asyncio.to_thread(self.prepare_inputs, task['projectId'], task, config) + record = await asyncio.to_thread(recovery_cache.submission) if recovery_cache else None + if record is None: + record = {'key': task['id'], 'uploads': {}, 'submissionStarted': False} + if record.get('key') != task['id'] or record.get('submissionStarted'): + raise protocol_failure('submit') + local_links = [] + for item in prepared['media']: + data, meta, _ = await asyncio.to_thread(next, references(self.store, task['projectId'], [item['assetId']])) + if meta['fingerprint'] != item['fingerprint']: + raise ProjectError('参考素材已变化,请重新核对后提交。', 409, code='higgsfield_reference_changed') + url = await upload_reference(config, data, item['mimeType'], transport=self.transport, + cache=recovery_cache, record=record, asset_id=item['assetId']) + local_links.append({'kind': 'image', 'url': url}) + parameters = task['parameters'] + parts = [{'type': 'text', 'text': prepared['prompt']}] + for link in [*local_links, *parameters['referenceMediaUrls']]: + kind = link['kind'] + parts.append({'type': 'reference_' + kind, kind: {'url': link['url']}}) + payload = {'model': opendev_magi.MODEL, 'parts': parts, 'duration': parameters['duration'], + 'resolution': parameters['resolution'].lower(), 'aspectRatio': parameters['ratio'], + 'generateAudio': parameters['generate_audio']} + if recovery_cache: + record.update(payload=payload, submissionStarted=True) + await asyncio.to_thread(recovery_cache.save_submission, record) + stage = 'submit' + result = await request('POST', ENDPOINT, json=payload) + external_id = result.get('id') + if not isinstance(external_id, str) or not external_id.strip() or len(external_id) > 200: + raise protocol_failure(stage) + await submitted(external_id) + stage = 'poll' + task_url = ENDPOINT + '/' + quote(external_id, safe='') + while True: + value = await self._retry_read(lambda: request('GET', task_url)) + if value.get('id', external_id) != external_id: + raise protocol_failure(stage) + status = value.get('status') + if status == 'succeeded': + stage = 'download' + url = value['output']['videoUrl'] + if not opendev_magi.public_https_url(url): + raise protocol_failure(stage) + if result_ready: + await result_ready('mp4', url) + return await self.resume_result(config, 'mp4', url) + if status in FAILURES: + raise provider_failure({**value, 'status': FAILURES[status]}, stage=stage, + http_status=200, secrets=secrets) + if status not in PENDING: + raise protocol_failure(stage) + await asyncio.sleep(self.poll_interval) + except httpx.TimeoutException: + raise transport_failure(stage, timeout=True) from None + except httpx.HTTPError: + raise transport_failure(stage) from None + except (ValueError, TypeError, KeyError, AttributeError): + raise protocol_failure(stage) from None + + async def resume_result(self, config, suffix, url): + if not opendev_magi.public_https_url(url): + raise protocol_failure('download') + return await super().resume_result(config, suffix, url, public_only=True) + + async def cancel(self, config, external_id): + raise protocol_failure('cancel') diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 415362354..9b1e43277 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -20,6 +20,7 @@ from opendirector.integrations.minimax_video import MinimaxVideoGeneration from opendirector.integrations.kling_video import KlingVideoGeneration from opendirector.integrations.higgsfield_open import HiggsfieldOpenGeneration +from opendirector.integrations.opendev_magi import OpenDevMagiGeneration from opendirector.integrations.bigmodel_video import BigModelVideoGeneration 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 @@ -57,6 +58,7 @@ def __init__(self, store, transport=None, poll_interval=3, retry_delays=(0.5, 1. self.bigmodel_video = BigModelVideoGeneration(store, transport, poll_interval, retry_delays) self.kling_video = KlingVideoGeneration(store, transport, poll_interval, retry_delays) self.higgsfield_open = HiggsfieldOpenGeneration(store, transport, poll_interval, retry_delays) + self.opendev_magi = OpenDevMagiGeneration(store, transport, 5, (5, 5)) self.vllm_omni = VllmOmniGeneration(store, transport, poll_interval, retry_delays) self.vllm_omni_image = VllmOmniImageGeneration(store, transport, poll_interval) self.minimax_image = MinimaxH3Images(transport, poll_interval) @@ -67,6 +69,8 @@ def __init__(self, store, transport=None, poll_interval=3, retry_delays=(0.5, 1. self.zhipu_speech = ZhipuSpeech(transport, poll_interval) def _profile_adapter(self, config): + if config and config.get('protocol') == 'opendev_magi': + return self.opendev_magi if config and config.get('protocol') == 'higgsfield_open': return self.higgsfield_open if config and config.get('protocol') == 'bigmodel_video': @@ -164,6 +168,8 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery extra_ready=None): if config.get('protocol') == 'higgsfield_open': return await self.higgsfield_open.generate(config, task, submitted, result_ready=result_ready, recovery_cache=recovery_cache) + if config.get('protocol') == 'opendev_magi': + return await self.opendev_magi.generate(config, task, submitted, result_ready=result_ready, recovery_cache=recovery_cache) if input_rules(config)['profile'] == 'bigmodel-glm-image': prepared = await asyncio.to_thread(generation_references, self.store, task, config) width, height = map(int, task['parameters']['size'].split('x')) @@ -336,6 +342,8 @@ async def _score(self, task, params): data, meta['name'], melody_only=params['score_mode'] == 'melody')) async def cancel(self, config, external_id, *, recovery_cache=None): + if config.get('protocol') == 'opendev_magi': + return await self.opendev_magi.cancel(config, external_id) if config.get('protocol') == 'higgsfield_open': return await self.higgsfield_open.cancel(config, external_id, recovery_cache=recovery_cache) adapter = self._profile_adapter(config) diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index d79b34007..fd641fede 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -888,6 +888,9 @@ export class CreationProjection { DEFAULT_SETTINGS.durationSeconds, aspectRatio: spec.parameters.aspectRatio ?? "auto", audioEnabled: spec.parameters.generateAudio, + ...(spec.parameters.referenceMediaUrls?.length + ? { referenceMediaUrls: spec.parameters.referenceMediaUrls } + : {}), resolution: spec.parameters.resolution === "auto" ? "auto" @@ -1180,6 +1183,9 @@ export class CreationProjection { ? null : (settings?.aspectRatio ?? null), generateAudio: settings?.audioEnabled ?? true, + ...(settings?.referenceMediaUrls?.length + ? { referenceMediaUrls: settings.referenceMediaUrls } + : {}), resolution: settings?.resolution === "auto" ? "auto" diff --git a/src/backend/models.ts b/src/backend/models.ts index f24647dc8..1f752fc8b 100644 --- a/src/backend/models.ts +++ b/src/backend/models.ts @@ -51,6 +51,7 @@ export type ModelOptions = Pick< >; export interface ModelConfigInput { + nextLabsToken?: string; capabilityAutoCheck?: boolean | null; kind: ModelKind; url: string; diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 8ebc91c90..3ae7337e3 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -85,6 +85,7 @@ export interface ModelConfig { | "openai" | "volcengine" | "higgsfield_open" + | "opendev_magi" | "minimax_video_v2" | "kling_video" | "bigmodel_video" @@ -455,7 +456,8 @@ export function backendVideoMode( return effectiveVideoMode({ mode: settings.videoMode, allowedModes: config?.inputRules.videoModes ?? [], - hasNonTextMedia: references.some((item) => item.node.data.kind !== "text"), + hasNonTextMedia: (config?.protocol === "opendev_magi" && Boolean(settings.referenceMediaUrls?.length)) || + references.some((item) => item.node.data.kind !== "text"), configured: config != null, }); } @@ -596,6 +598,8 @@ export function serviceVideoSettings( modelChanged = false, ): GenerationSettings { const next = { ...settings }; + if (config.protocol === "opendev_magi") next.videoMode = "reference"; + else if (modelChanged) next.referenceMediaUrls = undefined; const caps = config.inputRules.videoCapabilities; const durations = backendDurations(config); if (durations.length && !durationMatches(next.durationSeconds, durations, config.inputRules.fractionalDuration)) @@ -665,7 +669,13 @@ export function backendBlocker( ) return tNow("generation.issue.audioTaskTarget"); const references = backendReferences(settings, [...incoming, ...pinned], config); + if (config.protocol === "opendev_magi" && [...incoming, ...pinned].some( + (node) => ["video", "audio"].includes(node.data.kind) || node.data.kind === "image" && !config.inputRules.maxImages, + )) return tNow("generation.magiLinks.localReference"); const imageCount = references.filter((ref) => ref.node.data.kind === "image").length; + if (config.protocol === "opendev_magi" && new Set(references.filter((ref) => ref.node.data.kind === "image") + .map((ref) => ref.node.data.assetId ?? ref.node.id)).size + (settings.referenceMediaUrls ?? []).filter((link) => link.kind === "image").length > 10) + return tNow("generation.magiLinks.imageLimit"); const profile = settings.mode === "audio" ? (isMusicModel(config) ? "lyrics_to_music" : "text_to_speech") : settings.mode === "image" ? (imageCount > 1 ? "images_to_image" : imageCount === 1 ? "image_to_image" : "text_to_image") : references.some((ref) => ref.role === "continuation") ? "video_continuation" diff --git a/src/canvas/MagiReferenceLinks.tsx b/src/canvas/MagiReferenceLinks.tsx new file mode 100644 index 000000000..5880e2192 --- /dev/null +++ b/src/canvas/MagiReferenceLinks.tsx @@ -0,0 +1,82 @@ +import { useState } from "react"; +import type { VideoReferenceUrl } from "../contracts/generated.ts"; +import { useT } from "../i18n/I18nProvider.tsx"; + +const limits = { image: 10, video: 5, audio: 5 } as const; +const kinds = ["image", "video", "audio"] as const; + +export function MagiReferenceLinks({ + links, + disabled, + onChange, +}: { + links: readonly VideoReferenceUrl[]; + disabled: boolean; + onChange: (links: readonly VideoReferenceUrl[]) => void; +}) { + const t = useT(); + const [kind, setKind] = useState("image"); + const [draft, setDraft] = useState(""); + const [error, setError] = useState(""); + const add = () => { + const url = draft.trim(); + const parsed = URL.canParse(url) ? new URL(url) : undefined; + if (!url.startsWith("https://") || !parsed?.hostname || + parsed.username || parsed.password || parsed.hash || /[\s\\]/u.test(url)) { + setError(t("generation.magiLinks.invalid")); + return; + } + if (links.filter((link) => link.kind === kind).length >= limits[kind]) { + setError(t("generation.magiLinks.limit", { count: limits[kind] })); + return; + } + onChange([...links, { kind, url }]); + setDraft(""); + setError(""); + }; + return ( +
+ {t("generation.magiLinks.label")} + {links.length > 0 && ( +
    + {links.map((link, index) => ( +
  1. + {t(`generation.magiLinks.${link.kind}`)} + {link.url} + +
  2. + ))} +
+ )} +
+ + { setDraft(event.target.value); setError(""); }} + onKeyDown={(event) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + event.preventDefault(); + event.stopPropagation(); + if (draft.trim()) add(); + }} + /> + +
+ {error &&

{error}

} +
+ ); +} diff --git a/src/canvas/ModelCapabilityCard.tsx b/src/canvas/ModelCapabilityCard.tsx index c70452262..052684e29 100644 --- a/src/canvas/ModelCapabilityCard.tsx +++ b/src/canvas/ModelCapabilityCard.tsx @@ -47,7 +47,7 @@ export function ModelCapabilityCard({ saved?.videoAdapter ?? connection.videoAdapter ?? "auto"; - const official = ["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open"].includes( + const official = ["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open", "opendev_magi"].includes( connection.protocol, ); const nativeKey = `${connection.protocol}:${modelId}`; @@ -168,6 +168,8 @@ export function ModelCapabilityCard({ {t( connection.protocol === "bigmodel_video" ? "models.service.bigmodelVideoSummary" + : connection.protocol === "opendev_magi" + ? "models.service.opendevMagiSummary" : connection.protocol === "higgsfield_open" ? "models.service.higgsfieldSummary" : connection.protocol === "kling_video" @@ -198,6 +200,8 @@ export function ModelCapabilityCard({ {t( connection.protocol === "bigmodel_video" ? "models.service.bigmodelVideoReferences" + : connection.protocol === "opendev_magi" + ? "models.service.opendevMagiReferences" : connection.protocol === "higgsfield_open" ? "models.service.higgsfieldReferences" : connection.protocol === "kling_video" diff --git a/src/canvas/ModelServiceForm.tsx b/src/canvas/ModelServiceForm.tsx index 90c8d9013..e885d5152 100644 --- a/src/canvas/ModelServiceForm.tsx +++ b/src/canvas/ModelServiceForm.tsx @@ -61,6 +61,7 @@ const PROTOCOLS: Record< ["minimax_video_v2", "models.protocolOption.minimaxVideo"], ["kling_video", "models.protocolOption.klingVideo"], ["higgsfield_open", "models.protocolOption.higgsfieldOpen"], + ["opendev_magi", "models.protocolOption.opendevMagi"], ["bigmodel_video", "models.protocolOption.bigmodelVideo"], ["volcengine", "models.protocolOption.volcengine"], ["vllm_omni_segmentation", "models.protocolOption.segmentation"], @@ -227,7 +228,7 @@ export function ModelServiceForm({ setValue((current) => ({ ...current, ...patch, - ...(["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open"].includes(patch.protocol ?? "") + ...(["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open", "opendev_magi"].includes(patch.protocol ?? "") ? ({ connectionType: "api", authMode: "bearer", @@ -540,6 +541,23 @@ export function ModelServiceForm({ + {value.protocol === "opendev_magi" && ( +
+ +

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

+ {connection?.inputRules.maxImages ? ( + + ) : null} +
+ )}

)} + {opendevMagi && ( + updateSettings({ referenceMediaUrls })} + /> + )} {backend && music && (