diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index d0d786766..183412a69 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,6 +16,20 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + '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.', + 'higgsfield_parameters': 'Choose an aspect ratio and audio option supported by MAGI-2.', + 'higgsfield_mode': 'MAGI-2 supports first/last frames and reference media.', + 'higgsfield_image': 'Use valid JPEG, PNG, WebP, or GIF images, each smaller than 30 MB.', + 'higgsfield_format': 'Use MP4 video and WAV audio references. Convert MOV to MP4 and MP3 to WAV before uploading.', + 'higgsfield_media_size': 'Each reference video must be at most 200 MB; each audio file at most 15 MB.', + 'higgsfield_duration': 'Each reference video or audio clip must be 2–30 seconds. The total for each media type cannot exceed 30 seconds.', + 'higgsfield_reference_count': 'MAGI-2 accepts up to 10 images, 5 videos, and 5 audio references.', + 'higgsfield_reference_changed': 'A reference asset changed. Review the inputs before submitting again.', + '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.', "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/models.py b/apps/api/src/opendirector_api/models.py index 36fd15239..75e65dfe7 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -25,7 +25,7 @@ class AssetSource(Model): class ModelConnection(Model): connectionType: Literal['api', 'self_hosted'] = 'api' - protocol: Literal['openai', 'volcengine', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] | None = None + protocol: Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] | None = None authMode: Literal['none', 'bearer'] | None = None proxyMode: Literal['system', 'direct'] | None = None capabilityAutoCheck: bool | None = Field(default=None, strict=True, exclude_if=lambda value: value is None) diff --git a/docs/development/validation.md b/docs/development/validation.md index b037e9bad..860d14728 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -512,6 +512,10 @@ Local visible-Chrome test: upload `IMG_8066.HEIC` through the system file picker `browser-image` also supplies the pixel dimensions for cropping, masks and image editing, so this patch does not impose a 2048-pixel limit on that shared route. A bounded display rendition must be separate from editing inputs. The first full-resolution PNG transfer remains about 14 MB. Other platforms, HDR accuracy and the full Python suite were not revalidated. +MAGI-2 protocol checks use `python -m pytest tests/test_higgsfield_open.py -q`. For its bilingual browser workflow, start `python tests/browser/higgsfield_server.py --port 8504`, run Vite with `OPENDIRECTOR_API_URL=http://127.0.0.1:8504 npm run dev -- --port 5504`, and run `node tests/browser/higgsfield_open.mjs`. The fixture creates an isolated temporary project directory and uses the actual upload/generation adapter with mocked HTTP. It checks all three routes, mixed media, output adoption, reload and MP3 rejection. Screenshots and a JSON receipt are written to `output/playwright/higgsfield` or `CREATION_SCREENSHOTS`. + +MAGI-2 协议测试命令为 `python -m pytest tests/test_higgsfield_open.py -q`。双语浏览器检查使用上述独立服务和命令,验证真实适配器发送的请求与工程保存结果,供应商 HTTP 由模拟服务代替。检查不调用真实模型,不证明账户权限、计费或生成质量。真实验收需另行记录实际提交、查询、下载、采用和远端任务编号,不保存密钥。 + Kling 4.0 protocol and bilingual workflow checks: ```sh diff --git a/docs/guides/higgsfield-magi-2.md b/docs/guides/higgsfield-magi-2.md new file mode 100644 index 000000000..410b0b7ce --- /dev/null +++ b/docs/guides/higgsfield-magi-2.md @@ -0,0 +1,50 @@ +# MAGI-2 through Higgsfield Open + +[中文](higgsfield-magi-2.zh-CN.md) + +## Account connection + +Open **Settings → Model connections → Video → Add service**, choose **Higgsfield Open**, and keep `https://api.higgsfield.ai`. Enter your Higgsfield Open credentials as `KEY_ID:KEY_SECRET`, enable `sand/magi-2`, and save. Select this model in the generation picker. + +The model list and output specifications are built-in declarations. Loading or saving them does not test account access or submit a generation. Generating requires model access and sufficient API credits. + +## Inputs and output + +One connection supports three inputs in both the canvas and Agent: + +| Input | Selection | +| --- | --- | +| Text | Enter a prompt with no media references. | +| First/last frames | Choose first/last-frame mode and select a first image, optionally a last image. | +| References | Choose reference mode and attach images, video, audio, or a mixture. A single ordinary image remains a reference. Audio may be used on its own. | + +Text-to-video requires a prompt. A prompt is optional with media. The final prompt, including connected text, allows up to 15,000 characters; excessive input is rejected without truncation. + +| Reference | Formats | Maximum count | Size per file | Duration | +| --- | --- | --- | --- | --- | +| Image | JPEG, PNG, WebP, GIF | 10 | Smaller than 30 MB | — | +| Video | MP4 | 5 | 200 MB | 2–30 seconds each; 30 seconds total | +| Audio | WAV | 5 | 15 MB | 2–30 seconds each; 30 seconds total | + +Convert MOV to MP4 and MP3 to WAV before attaching them. OpenDirector uploads the original accepted bytes through Higgsfield's upload service. Credentials are only sent to the official API. + +Output is 1080p, with an integer duration of 4–30 seconds. New nodes default to 5 seconds, 16:9 and generated audio enabled. The available ratios are 21:9, 16:9, 4:3, 1:1, 3:4 and 9:16, including for first/last frames. Generated audio can be disabled. Saved supported choices are preserved. + +## Tasks and results + +Accepted jobs retain their inputs and parameters. Completed files are downloaded, checked and registered as project assets and result candidates. Adoption follows existing version and lock checks, preserving newer edits. Generated files have the existing 50 MB download and recovery-cache limit. + +Recover an interrupted original task to continue submission, querying, downloading or saving. The private recovery cache preserves the exact submitted body, uploaded URLs and a fixed `Idempotency-Key`, which identifies one intended generation. Replaying that request uses the same remote generation. A damaged cache stops recovery before another submission. + +An unknown submission can only be replayed with the original API Key ID. If you change it, restore the original connection before recovering that task; a different account has a separate idempotency history. + +Remote cancellation is available while the request is queued. A cancellation request and confirmed remote cancellation are tracked separately. If generation has started, Higgsfield rejects cancellation; stopping local work does not stop remote processing or confirm a refund. + +## API references + +- [Text-to-video](https://open.higgsfield.ai/models/sand/magi-2/text-to-video/api-reference) +- [Image-to-video](https://open.higgsfield.ai/models/sand/magi-2/image-to-video/api-reference) +- [Reference-to-video](https://open.higgsfield.ai/models/sand/magi-2/reference-to-video/api-reference) +- [File uploads](https://docs.higgsfield.ai/docs/concepts/file-uploads) +- [Request lifecycle](https://docs.higgsfield.ai/docs/concepts/requests) +- [Idempotent requests](https://docs.higgsfield.ai/docs/concepts/idempotency) diff --git a/docs/guides/higgsfield-magi-2.zh-CN.md b/docs/guides/higgsfield-magi-2.zh-CN.md new file mode 100644 index 000000000..faa3c3ca4 --- /dev/null +++ b/docs/guides/higgsfield-magi-2.zh-CN.md @@ -0,0 +1,50 @@ +# Higgsfield Open MAGI-2 视频生成 + +[English](higgsfield-magi-2.md) + +## 账户连接 + +打开**设置 → 模型接入 → 视频 → 添加服务**,选择 **Higgsfield Open**,保留地址 `https://api.higgsfield.ai`。按照 `KEY_ID:KEY_SECRET` 格式填写 Higgsfield Open 凭据,勾选 `sand/magi-2` 并保存,然后在生成面板中选择该模型。 + +模型列表与输出规格来自内置声明。加载和保存配置不会验证账户权限,也不会发起生成请求。生成需要账户具备模型权限和足够的 API 额度。 + +## 输入与输出 + +画布与 Agent 通过同一个连接支持以下输入: + +| 输入 | 选择方式 | +| --- | --- | +| 文本 | 填写提示词,不连接媒体参考。 | +| 首尾帧 | 选择首尾帧模式,指定首帧图片,可选填尾帧图片。 | +| 参考素材 | 选择参考模式,连接图片、视频、音频或混合素材。普通图片参考保持参考用途;音频可以单独使用。 | + +纯文本生成必须填写提示词,携带媒体时可以省略提示词。最终提示词包含所连接的文本内容,最多 15,000 个字符;超限会明确拒绝,不截断输入。 + +| 参考类型 | 格式 | 数量上限 | 单个文件大小 | 时长 | +| --- | --- | --- | --- | --- | +| 图片 | JPEG、PNG、WebP、GIF | 10 张 | 小于 30 MB | — | +| 视频 | MP4 | 5 段 | 不超过 200 MB | 每段 2–30 秒,视频总计不超过 30 秒 | +| 音频 | WAV | 5 段 | 不超过 15 MB | 每段 2–30 秒,音频总计不超过 30 秒 | + +MOV 请先转换为 MP4,MP3 请先转换为 WAV,再添加参考。OpenDirector 通过 Higgsfield 上传服务发送已接受文件的原始内容。账户凭据仅发送给官方 API。 + +输出为 1080p,时长支持 4–30 秒的整数。新节点默认 5 秒、16:9,并开启生成音频。比例支持 21:9、16:9、4:3、1:1、3:4 和 9:16,首尾帧模式也可以选择比例。可以关闭生成音频,已保存且受支持的参数会继续保留。 + +## 任务与结果 + +任务接受后保存固定的输入和参数。完成的视频会被下载、检查,并登记为工程素材和结果候选。采用结果时执行现有版本与锁定检查,保留之后修改的内容。生成文件沿用现有 50 MB 下载与恢复缓存上限。 + +中断后恢复原任务,可以继续提交、查询、下载或保存。私有恢复缓存记录首次提交的完整请求、素材地址和固定的 `Idempotency-Key`。该标识表示一次明确的生成操作,重复发送相同请求会继续使用同一个远端任务。缓存损坏时停止恢复,不重新提交生成。 + +提交结果不明时,恢复提交需要原 API Key ID。更换该标识后,请恢复原连接再恢复任务;不同账户分别记录重复请求标识。 + +远端任务排队时可以申请取消。系统分别记录取消请求和远端取消确认。开始执行后 Higgsfield 会拒绝取消;停止本地工作不能停止远端执行,也不能确认退款。 + +## 官方接口资料 + +- [文字生成视频](https://open.higgsfield.ai/models/sand/magi-2/text-to-video/api-reference) +- [图片生成视频](https://open.higgsfield.ai/models/sand/magi-2/image-to-video/api-reference) +- [参考素材生成视频](https://open.higgsfield.ai/models/sand/magi-2/reference-to-video/api-reference) +- [文件上传](https://docs.higgsfield.ai/docs/concepts/file-uploads) +- [请求生命周期](https://docs.higgsfield.ai/docs/concepts/requests) +- [重复请求处理](https://docs.higgsfield.ai/docs/concepts/idempotency) diff --git a/docs/guides/video-model-capabilities.md b/docs/guides/video-model-capabilities.md index fac4eff75..72f436852 100644 --- a/docs/guides/video-model-capabilities.md +++ b/docs/guides/video-model-capabilities.md @@ -67,6 +67,8 @@ Protocol references: [create task](https://platform.minimax.cn/docs/api-referenc ## Providers and per-model settings +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. + 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 fa2f62a34..cbaafe47f 100644 --- a/docs/guides/video-model-capabilities.zh-CN.md +++ b/docs/guides/video-model-capabilities.zh-CN.md @@ -67,6 +67,8 @@ ## 提供商与逐模型设置 +Higgsfield Open 通过同一个视频连接支持 `sand/magi-2`:文本、首尾帧和图片、视频、音频混合参考。输出为 1080p,时长支持 4–30 秒,可以关闭生成音频。接入、输入限制与恢复说明见 [MAGI-2 指南](higgsfield-magi-2.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 f05de01e8..5efb958a8 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -159,6 +159,10 @@ 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'] == 'higgsfield_open': + from opendirector.domain.higgsfield import parameters as magi2_parameters + return magi2_parameters(config, intent, node['videoMode'], + any(records[key]['kind'] == 'image' for key in node['referenceIds'])) if spec.kind == 'video' and config['protocol'] == 'bigmodel_video': from opendirector.domain.bigmodel_video import cogvideo_parameters return {**cogvideo_parameters(config, intent), 'watermark': not self.settings.get()['removeWatermark']} diff --git a/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index e104391d0..1b4c9102a 100644 --- a/packages/core/src/opendirector/application/generation_runtime.py +++ b/packages/core/src/opendirector/application/generation_runtime.py @@ -92,6 +92,10 @@ def recovery(self, task, directory): if (details.get('stage') == 'submit' and details.get('httpStatus') in {400, 401, 402, 403, 404, 413, 422, 429} and details.get('category') not in {'submission_unknown', 'local', 'protocol'}): return 'retry' # An explicit continuation may create a new attempt. + if task.get('protocol') == 'higgsfield_open': + submission = cache.submission() + if submission: + return 'remote' if submission.get('remote') else 'submit' return 'review' @@ -147,7 +151,10 @@ async def result_ready(suffix, url): stage = 'poll' if task.get('externalTaskId') else 'submit' task['phase'] = stage await save() # Mark submission before entering any provider call. - if hasattr(self.provider, 'resume_result'): + if task.get('protocol') == 'higgsfield_open': + suffix, data = await self.provider.generate(config, task, submitted, + result_ready=result_ready, recovery_cache=cache) + elif hasattr(self.provider, 'resume_result'): suffix, data = await self.provider.generate(config, task, submitted, result_ready=result_ready) else: suffix, data = await self.provider.generate(config, task, submitted) @@ -180,7 +187,10 @@ async def result_ready(suffix, url): cancel_config = config or self.configs.resolve(task['modelConfigId'], task['kind']) if cancel_config['url'] != task['baseURL'] or cancel_config['modelId'] != task['model'] or task.get('protocol') and cancel_config.get('protocol') != task['protocol']: raise ProjectError('原模型配置已变化,供应商取消未确认。', 409) - await self.provider.cancel(cancel_config, task["externalTaskId"]) + if task.get('protocol') == 'higgsfield_open': + await self.provider.cancel(cancel_config, task["externalTaskId"], recovery_cache=cache) + else: + await self.provider.cancel(cancel_config, task["externalTaskId"]) task["error"] = "已请求取消供应商任务,实际取消与费用以服务控制台为准。" except (ProjectError, OSError) as failure: task["error"] = "本地已停止,供应商取消未确认,请在控制台核对任务。" diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 602b2b3aa..1bb79fd14 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -414,6 +414,9 @@ def command_fingerprint(command: Command) -> str: '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', diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index bb2622e4d..74175b7ea 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -15,7 +15,7 @@ CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, FRAME_IMAGE_LIMIT, 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, + duration_matches, effective_video_mode, generate_audio_options, prompt_optional_with_media, ) from .assets import AssetRef, MediaMetadata from .base import CanvasItemVersion, Contract, Digest, GenerationKind, NonNegative, ObjectVersion, PositiveInt, ProjectEntity, Revision, digest, unique @@ -389,7 +389,11 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc raise ValueError('扒谱模型仅用于参照音乐生成,请选择音乐生成模型。') written = (any(isinstance(part, PromptReference) or part.text.strip() for part in spec.promptContent) if spec.promptContent is not None else bool(spec.prompt.strip())) - if not written and not implicit_text_prompt(spec, references): + optional_prompt = prompt_optional_with_media({ + 'profile': model.inputRules.profile, + 'hasMedia': any(ref.transmission != 'context_only' and ref.asset.kind in {'image', 'video', 'audio'} for ref in references), + }) + if not written and not implicit_text_prompt(spec, references) and not optional_prompt: raise ValueError('请填写生成提示词。') rules = model.inputRules if rules.referencesAllowed is False and references: @@ -415,7 +419,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if sum(ref.metadata.size for ref in transmitted) > rules.requestBytes: raise ValueError('参考素材总大小超过模型请求上限。') for ref in transmitted: - limit = rules.imageBytes if ref.asset.kind == 'image' else rules.videoBytes if ref.asset.kind == 'video' else rules.requestBytes + limit = (rules.imageBytes if ref.asset.kind == 'image' else rules.videoBytes if ref.asset.kind == 'video' + else rules.audioBytes if ref.asset.kind == 'audio' and rules.audioBytes is not None else rules.requestBytes) if ref.metadata.size > limit: raise ValueError('参考文件超过模型的单文件大小限制。') kinds = [ref.asset.kind for ref in references if ref.transmission != 'context_only'] @@ -516,8 +521,12 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc # The control video is the output's timeline, not a reference clip; its own limit applies above. seconds = [ref.metadata.durationSeconds for ref in transmitted if ref.asset.kind == kind and ref.role != 'control'] minimum = 2 if kind == 'audio' or rules.profile == 'minimax-h3-official' else 0 - if any(value is None or value < minimum or value <= 0 for value in seconds) or sum(seconds) > REFERENCE_MEDIA_SECONDS: + minimum = rules.referenceMediaMinSeconds if rules.referenceMediaMinSeconds is not None else minimum + maximum = rules.referenceMediaSeconds if rules.referenceMediaSeconds is not None else REFERENCE_MEDIA_SECONDS + if any(value is None or value < minimum or value <= 0 for value in seconds) or sum(seconds) > maximum: label = '视频' if kind == 'video' else '音频' + if rules.referenceMediaSeconds is not None: + raise ProjectError('参考视频和音频每段须为 2–30 秒,同类素材总时长不能超过 30 秒。', 422, code='higgsfield_duration') raise ValueError(f'{label}参考的时长必须已知,且总时长不能超过 {REFERENCE_MEDIA_SECONDS} 秒。') if rules.profile == 'fasth3-omni' and sum(kind in {'image', 'video', 'audio'} for kind in kinds) > FASTH3_MEDIA_REFERENCE_LIMIT: raise ValueError(f'FastH3 最多支持 {FASTH3_MEDIA_REFERENCE_LIMIT} 个媒体参考。') diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index ceb3fc6ae..6897ff9f5 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', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] +Protocol = Literal['openai', 'volcengine', 'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] VideoMode = Literal['first_frame', 'reference', 'continuation', 'control'] ImageQuality = Literal['auto', 'low', 'medium', 'high'] Count = Annotated[int, Field(strict=True, ge=0)] @@ -65,6 +65,12 @@ class InputRules(Contract): maxAudios: Count = Field(description='Maximum reference audio count.') 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, + description='Maximum bytes per reference audio; omitted preserves the existing request budget.') + referenceMediaMinSeconds: float | None = Field(default=None, ge=0, exclude_if=lambda value: value is None, + description='Minimum duration of each reference video or audio clip.') + referenceMediaSeconds: float | None = Field(default=None, gt=0, exclude_if=lambda value: value is None, + description='Maximum total reference duration, applied separately to video and audio.') requestBytes: Count = Field(description='Maximum aggregate reference bytes per request.') videoModes: tuple[VideoMode, ...] = Field(description='Supported video generation modes.') imageOutputs: tuple[ImageOutput, ...] = Field(default=(), description='Supported image aspect ratios and sizes.') @@ -136,7 +142,7 @@ def model_name(cls, value): @model_validator(mode='after') def connection(self): allowed = {'agent': {'openai'}, 'image': {'openai', 'volcengine', 'vllm_omni_segmentation'}, - 'video': {'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, + 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, 'audio': {'openai', 'volcengine', 'vllm_omni_music', 'vllm_omni_score'}, 'vision': {'vllm_omni'}} if self.protocol not in allowed[self.kind]: raise ValueError('Protocol is incompatible with model category') diff --git a/packages/core/src/opendirector/domain/higgsfield.py b/packages/core/src/opendirector/domain/higgsfield.py new file mode 100644 index 000000000..28f04c420 --- /dev/null +++ b/packages/core/src/opendirector/domain/higgsfield.py @@ -0,0 +1,63 @@ +"""MAGI-2 operations and limits published by Higgsfield Open.""" +from .projects import ProjectError + + +BASE = 'https://api.higgsfield.ai' +MODEL = 'sand/magi-2' +PROFILE = 'higgsfield-magi-2' +RATIOS = ('21:9', '16:9', '4:3', '1:1', '3:4', '9:16') +IMAGE_BYTES = 30 * 1024 * 1024 - 1 +VIDEO_BYTES = 200 * 1024 * 1024 +AUDIO_BYTES = 15 * 1024 * 1024 +IMAGE_TYPES = frozenset({'image/jpeg', 'image/png', 'image/webp', 'image/gif'}) + + +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('请选择 Higgsfield Open 的 MAGI-2 模型和官方 API 地址。', 422, code='higgsfield_model') + + +def magi2_capabilities(): + return {'outputs': [{'resolution': '1080P', 'durations': list(range(4, 31))}], + 'defaultResolution': '1080P', 'defaultDuration': 5, 'dimensionStep': 2} + + +def validate_outputs(capabilities): + if any(item['resolution'] != '1080P' + or any(second not in range(4, 31) for second in item['durations']) + or item.get('width') is not None or item.get('height') is not None + for item in capabilities['outputs']): + raise ProjectError('MAGI-2 支持 1080p 和 4–30 秒整数时长,请调整输出参数。', 422, code='higgsfield_output') + + +def operation(mode, has_images): + if mode == 'reference': + return 'reference-to-video' + if mode == 'first_frame': + return 'image-to-video' if has_images else 'text-to-video' + raise ProjectError('MAGI-2 支持首尾帧和参考素材模式。', 422, code='higgsfield_mode') + + +def parameters(config, intent, mode, has_images): + validate_model(config) + capabilities = config.get('videoCapabilities') or magi2_capabilities() + validate_outputs(capabilities) + resolution = intent.get('resolution', 'auto') + if resolution == 'auto': + resolution = capabilities['outputs'][0]['resolution'] + seconds = intent.get('durationSeconds') + if seconds is None: + seconds = capabilities['defaultDuration'] + if (isinstance(seconds, bool) or not isinstance(seconds, (int, float)) + or not any(item['resolution'] == resolution and seconds in item['durations'] + for item in capabilities['outputs'])): + raise ProjectError('MAGI-2 支持 1080p 和 4–30 秒整数时长,请调整输出参数。', 422, code='higgsfield_output') + ratio = intent.get('aspectRatio') or '16:9' + 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} diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index d0b3f55e0..729de0d94 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -7,6 +7,7 @@ from .moss_speech import is_moss_speech 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 .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 @@ -22,6 +23,16 @@ def _adapter_rules(config): 'maxAudios': 0, 'imageBytes': 8 * 1024 * 1024, 'requestBytes': 48 * 1024 * 1024, 'videoModes': ['first_frame'] if kind == 'video' else []} rules.update(maxVideos=0, videoBytes=DEFAULT_VIDEO_BYTES) + if config.get('protocol') == 'higgsfield_open': + validate_model(config) + rules.update(profile=PROFILE, allowedKinds=['text', 'image', 'video', 'audio'], + maxImages=10, maxVideos=5, maxAudios=5, imageBytes=IMAGE_BYTES, + videoBytes=VIDEO_BYTES, audioBytes=AUDIO_BYTES, + requestBytes=10 * IMAGE_BYTES + 5 * VIDEO_BYTES + 5 * AUDIO_BYTES + MAX_REFERENCES * 64 * 1024, + referenceMediaMinSeconds=2, referenceMediaSeconds=30, maxPromptCharacters=15000, + videoModes=['first_frame', 'reference'], frameRoles=['first_frame', 'last_frame'], + audioReferenceStandalone=True, aspectRatios=list(RATIOS)) + return rules if is_bigmodel_image(config): rules.update(profile='bigmodel-glm-image', allowedKinds=['text'], maxImages=0) return rules @@ -165,7 +176,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'} else [True] + rules['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 f035520e1..0e7ffd3f0 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': {'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, + 'video': {'higgsfield_open', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'volcengine', 'vllm_omni_segmentation', 'vllm_omni_depth'}, '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/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 6e0fecdab..4ee1fd661 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -96,7 +96,7 @@ def aspect_ratio_choices(spec): if kind == 'image': return ['auto', *_unique(ratio for ratio in spec.get('imageOutputRatios') or [] if ratio != 'auto')] if kind == 'video' and published is not None: - if video_mode in {'first-last', 'control'}: + if video_mode == 'control' or video_mode == 'first-last' and spec.get('protocol') != 'higgsfield_open': return ['auto'] return ['auto', *list(published)] framed = spec.get('protocol') == 'volcengine' or bool(spec.get('dimensioned')) @@ -168,18 +168,33 @@ def reference_byte_limit(spec): return AGENT_IMAGE_BYTES if spec.get('imageBytes') is None else spec['imageBytes'] if kind == 'video': return DEFAULT_VIDEO_BYTES if spec.get('videoBytes') is None else spec['videoBytes'] + if kind == 'audio' and spec.get('audioBytes') is not None: + return spec['audioBytes'] return DEFAULT_VIDEO_BYTES +def prompt_optional_with_media(spec): + """MAGI-2 image/reference endpoints allow an omitted prompt.""" + return spec.get('profile') == 'higgsfield-magi-2' and bool(spec.get('hasMedia')) + + DERIVATIONS = { 'aspectRatioChoices': aspect_ratio_choices, 'resolutionChoices': resolution_choices, 'effectiveVideoMode': effective_video_mode, 'generateAudioOptions': generate_audio_options, 'referenceByteLimit': reference_byte_limit, + 'promptOptionalWithMedia': prompt_optional_with_media, } _CASES = ( + ('magi2-image-ratios', 'aspectRatioChoices', { + 'kind': 'video', 'videoMode': 'first-last', 'publishedRatios': ['16:9', '9:16'], + 'protocol': 'higgsfield_open', 'dimensioned': False, 'imageOutputRatios': []}), + ('magi2-audio-bytes', 'referenceByteLimit', {'kind': 'audio', 'audioBytes': 15 * 1024 * 1024}), + ('magi2-media-prompt-optional', 'promptOptionalWithMedia', {'profile': 'higgsfield-magi-2', 'hasMedia': True}), + ('magi2-text-prompt-required', 'promptOptionalWithMedia', {'profile': 'higgsfield-magi-2', 'hasMedia': False}), + ('other-model-prompt-required', 'promptOptionalWithMedia', {'profile': 'minimax-h3-official', 'hasMedia': True}), ('image-ratios-drop-auto-and-duplicates', 'aspectRatioChoices', { 'kind': 'image', 'videoMode': None, 'publishedRatios': None, 'protocol': None, 'dimensioned': False, 'imageOutputRatios': ['16:9', 'auto', '16:9', '1:1']}), @@ -333,7 +348,7 @@ def derivation_vectors(): ]; } if (input.kind === "video" && input.publishedRatios != null) { - if (input.videoMode === "first-last" || input.videoMode === "control") return ["auto"]; + if (input.videoMode === "control" || input.videoMode === "first-last" && input.protocol !== "higgsfield_open") return ["auto"]; return ["auto", ...input.publishedRatios]; } const framed = input.protocol === "volcengine" || input.dimensioned; @@ -434,6 +449,7 @@ def derivation_vectors(): readonly kind: string; readonly imageBytes?: number | null; readonly videoBytes?: number | null; + readonly audioBytes?: number | null; }): number { if (input.kind === "text") return RULE_FACTS.textReferenceBytes; if (input.kind === "image") { @@ -442,9 +458,17 @@ def derivation_vectors(): if (input.kind === "video") { return input.videoBytes ?? RULE_FACTS.defaultVideoBytes; } + if (input.kind === "audio" && input.audioBytes != null) return input.audioBytes; return RULE_FACTS.defaultVideoBytes; } +export function promptOptionalWithMedia(input: { + readonly profile?: string; + readonly hasMedia: boolean; +}): boolean { + return input.profile === "higgsfield-magi-2" && input.hasMedia; +} + export const RULE_DERIVATION_VECTORS = __VECTORS__ as const; """ diff --git a/packages/core/src/opendirector/domain/video_capabilities.py b/packages/core/src/opendirector/domain/video_capabilities.py index 50ad25292..81d6b675d 100644 --- a/packages/core/src/opendirector/domain/video_capabilities.py +++ b/packages/core/src/opendirector/domain/video_capabilities.py @@ -9,6 +9,7 @@ from opendirector.domain.minimax_models import MINIMAX_MODELS, minimax_capabilities 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 VideoAdapter = Literal['auto', 'fasth3', 'fasth3_dual', 'minimax_h3', 'standard'] Second = Annotated[StrictInt, Field(ge=1, le=60)] @@ -64,6 +65,8 @@ def seedance_20_variant(model): def preset_capabilities(profile, model=''): + if profile == 'higgsfield-magi-2': + return magi2_capabilities() if profile == 'bigmodel-cogvideox-3': return cogvideo_capabilities(model) if profile == 'kling-official': @@ -98,6 +101,8 @@ 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': + validate_magi2_outputs(capabilities) if rules['profile'] in {'vllm-omni-h3', 'fasth3-omni'}: rules['fractionalDuration'] = True rules['videoCapabilities'] = capabilities @@ -132,6 +137,9 @@ def check_video_config(kind, protocol, adapter, capabilities): if protocol == 'bigmodel_video': validate_cogvideo_outputs(capabilities) return capabilities + if protocol == 'higgsfield_open': + validate_magi2_outputs(capabilities) + return capabilities if protocol == 'kling_video': validate_kling_outputs(capabilities) return capabilities diff --git a/packages/core/src/opendirector/infrastructure/generation_results.py b/packages/core/src/opendirector/infrastructure/generation_results.py index 811ea180f..a2516a494 100644 --- a/packages/core/src/opendirector/infrastructure/generation_results.py +++ b/packages/core/src/opendirector/infrastructure/generation_results.py @@ -1,4 +1,6 @@ """Private recovery cache. Locators never appear in public task receipts.""" +import hashlib +import json import os from pathlib import Path import tempfile @@ -9,6 +11,11 @@ from opendirector.infrastructure.local_projects import child, read_json, write_json +def _submission_digest(value): + encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode() + return hashlib.sha256(encoded).hexdigest() + + class GenerationResults: def __init__(self, directory, task_id): self.root = child(Path(directory), '.generation-results') @@ -44,6 +51,24 @@ def locator(self, suffix, url): raise ProjectError('生成结果地址无效,未重新提交生成。', 409) write_json(child(self.directory, 'result.json'), {'suffix': suffix, 'url': url}) + def submission(self): + """Exact idempotent request and provider locators; never public receipts.""" + path = child(self.directory, 'submission.json') + if not path.exists(): + return None + try: + record = read_json(path) + value = record['submission'] + if not isinstance(value, dict) or record['sha256'] != _submission_digest(value): + raise ValueError() + return value + except (KeyError, ValueError, TypeError): + raise ProjectError('生成恢复缓存无效,请保留原文件并核对任务。', 409) from None + + def save_submission(self, value): + self._prepare() + write_json(child(self.directory, 'submission.json'), {'submission': value, 'sha256': _submission_digest(value)}) + def data(self): metadata = self.metadata() path = child(self.directory, 'output') @@ -77,7 +102,7 @@ def save(self, suffix, data): def clear(self): # Remove only this task's cache after the durable success receipt. - for name in ('output', 'result.json'): + for name in ('output', 'result.json', 'submission.json'): child(self.directory, name).unlink(missing_ok=True) for directory in (self.directory, self.root): try: diff --git a/packages/core/src/opendirector/integrations/higgsfield_open.py b/packages/core/src/opendirector/integrations/higgsfield_open.py new file mode 100644 index 000000000..6804711c9 --- /dev/null +++ b/packages/core/src/opendirector/integrations/higgsfield_open.py @@ -0,0 +1,293 @@ +"""MAGI-2 uploads and asynchronous jobs through Higgsfield Open.""" +import asyncio +import hashlib +from io import BytesIO +import json +import re +from urllib.parse import urlsplit + +import httpx +from PIL import Image, UnidentifiedImageError + +from opendirector.domain.higgsfield import ( + BASE, MODEL, IMAGE_TYPES, operation, parameters, validate_model, +) +from opendirector.domain.input_rules import input_rules +from opendirector.domain.projects import ProjectError +from opendirector.domain.references import project_content +from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure +from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, public_target, trust_environment +from opendirector.integrations.reference_inputs import image_type, references, reference_text +from opendirector.integrations.volcengine import VolcengineGeneration +from opendirector.media.probe import require_ffprobe + + +def _credentials(config): + key = config.get('apiKey', '') + parts = key.split(':') + if len(parts) != 2 or any(not part or any(char.isspace() for char in part) for part in parts): + raise ProjectError('请填写 Higgsfield Open 的 KEY_ID:KEY_SECRET。', 422, code='higgsfield_key') + return key, *parts + + +def _https_url(url, stage): + if not isinstance(url, str) or len(url) > 16384: + raise protocol_failure(stage) + parsed = urlsplit(url) + if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or parsed.fragment: + raise protocol_failure(stage) + parsed.port + return url + + +def _task_urls(value, secrets, stage): + external_id = value.get('request_id') + if (not isinstance(external_id, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}', external_id) + or any(secret and secret in external_id for secret in secrets)): + raise protocol_failure(stage) + result = {'request_id': external_id} + for key in ('status_url', 'cancel_url'): + url = _https_url(value.get(key), stage) + if urlsplit(url).netloc != urlsplit(BASE).netloc: + raise protocol_failure(stage) + result[key] = url + return result + + +class HiggsfieldOpenGeneration(VolcengineGeneration): + def validate(self, kind, config): + validate_model({**config, 'kind': kind}) + _credentials(config) + require_ffprobe() + + def prepare_inputs(self, project_id, task, config, *, complete=True): + self.validate(task['kind'], config) + rules = input_rules(config) + mode = task.get('videoMode', 'first_frame') + bindings = task.get('referenceRoles') or [] + media, manifest, texts, frames = [], [], [], set() + totals = {'video': 0, 'audio': 0} + for blob, meta, kind in references(self.store, project_id, task['referenceIds']): + asset_id = str(meta['id']) + frozen = (task.get('inputSnapshot') or {}).get('references', {}).get(asset_id) + if frozen and frozen != meta['fingerprint']: + raise ProjectError('参考素材已变化,请重新核对后提交。', 409, code='higgsfield_reference_changed') + roles = [value['role'] for value in bindings if str(value['assetId']) == asset_id] or ['reference'] + if kind == 'text': + texts.append(reference_text(blob)) + elif kind == 'image': + mime = image_type(blob) + try: + with Image.open(BytesIO(blob)) as image: + image.verify() + except (UnidentifiedImageError, OSError, ValueError, SyntaxError, Image.DecompressionBombError): + raise ProjectError('图片需为有效的 JPEG、PNG、WebP 或 GIF,单张小于 30 MB。', 422, code='higgsfield_image') from None + if mime not in IMAGE_TYPES or len(blob) > rules['imageBytes']: + raise ProjectError('图片需为有效的 JPEG、PNG、WebP 或 GIF,单张小于 30 MB。', 422, code='higgsfield_image') + media.append(dict(assetId=asset_id, fingerprint=meta['fingerprint'], kind=kind, mimeType=mime, roles=roles)) + elif kind in totals: + mime = meta['type'] + if mime != ('video/mp4' if kind == 'video' else 'audio/wav'): + raise ProjectError('参考视频需为 MP4,音频需为 WAV。MOV 请先转换为 MP4,MP3 请先转换为 WAV。', 422, code='higgsfield_format') + if len(blob) > rules['videoBytes' if kind == 'video' else 'audioBytes']: + raise ProjectError('参考视频单个不能超过 200 MB,音频单个不能超过 15 MB。', 422, code='higgsfield_media_size') + duration = meta.get('durationMs') + if duration is None or not 2000 <= duration <= 30000: + raise ProjectError('参考视频和音频每段须为 2–30 秒,同类素材总时长不能超过 30 秒。', 422, code='higgsfield_duration') + totals[kind] += duration + media.append(dict(assetId=asset_id, fingerprint=meta['fingerprint'], kind=kind, mimeType=mime, roles=roles)) + else: + raise ProjectError('MAGI-2 支持文本、图片、MP4 视频和 WAV 音频参考。', 422, code='higgsfield_format') + manifest.append(dict(assetId=asset_id, fingerprint=meta['fingerprint'], kind=kind, transmission='content')) + if any(total > 30000 for total in totals.values()): + raise ProjectError('参考视频和音频每段须为 2–30 秒,同类素材总时长不能超过 30 秒。', 422, code='higgsfield_duration') + for kind, limit in (('image', 10), ('video', 5), ('audio', 5)): + if sum(item['kind'] == kind for item in media) > limit: + raise ProjectError('MAGI-2 最多支持 10 张图片、5 段视频和 5 段音频参考。', 422, code='higgsfield_reference_count') + route = operation(mode, any(item['kind'] == 'image' for item in media)) + if mode == 'first_frame': + for item in media: + roles = item['roles'] + if roles == ['reference'] and len(media) == 1: + roles = item['roles'] = ['first_frame'] + if (item['kind'] != 'image' or len(set(roles)) != len(roles) + or any(role not in {'first_frame', 'last_frame'} or role in frames for role in roles)): + raise ProjectError('每个首尾帧槽位只能使用一张图片,尾帧需要搭配首帧。', 422, code='higgsfield_frames') + frames.update(roles) + if frames and 'first_frame' not in frames: + raise ProjectError('每个首尾帧槽位只能使用一张图片,尾帧需要搭配首帧。', 422, code='higgsfield_frames') + elif not media or any(role != 'reference' for item in media for role in item['roles']): + raise ProjectError('参考模式需要至少一张图片、一段视频或一段音频,请检查素材角色。', 422, code='higgsfield_references') + prompt = project_content(task['promptContent'])[0] if task.get('promptContent') is not None else task['prompt'] + prompt = prompt + ''.join('\n' + text for text in texts) if prompt.strip() else '\n'.join(texts) + if complete and (len(prompt) > 15000 or not prompt.strip() and route == 'text-to-video'): + raise ProjectError('MAGI-2 提示词最多 15,000 字;纯文本生成需要填写提示词。', 422, code='higgsfield_prompt') + return dict(operation=route, prompt=prompt, media=media, references=manifest) + + def payload(self, config, task, prepared, urls): + frozen = task['parameters'] + intent = dict(durationSeconds=frozen.get('duration'), resolution=frozen.get('resolution', 'auto'), + aspectRatio=frozen.get('ratio'), generateAudio=frozen.get('generate_audio', True)) + normalized = parameters({**config, 'videoCapabilities': None}, intent, task.get('videoMode', 'first_frame'), + any(item['kind'] == 'image' for item in prepared['media'])) + if normalized['operation'] != prepared['operation'] or any(key in frozen and frozen[key] != value for key, value in normalized.items()): + raise protocol_failure('prepare') + body = dict(duration=normalized['duration'], resolution='1080p', aspect_ratio=normalized['ratio'], + generate_audio=normalized['generate_audio']) + if prepared['prompt'].strip(): + body['prompt'] = prepared['prompt'] + for item in prepared['media']: + url = urls[item['assetId']] + if normalized['operation'] == 'image-to-video': + for role in item['roles']: + body['image_url' if role == 'first_frame' else 'end_image_url'] = url + else: + body.setdefault(item['kind'] + '_urls', []).append(url) + return f"/{MODEL}/{normalized['operation']}", body + + async def _json(self, client, config, method, url, stage, *, idempotency_key=None, **kwargs): + secrets = _credentials(config) + headers = {'Authorization': f'Key {secrets[0]}'} + if idempotency_key: + headers['Idempotency-Key'] = idempotency_key + async with client.stream(method, url, headers=headers, extensions={'model_secrets': secrets}, **kwargs) as response: + await checked(response, stage=stage, secrets=secrets) + if stage == 'cancel': + if response.status_code != 202: + raise protocol_failure(stage) + return None + data = bytearray() + async for chunk in response.aiter_bytes(): + data.extend(chunk) + if len(data) > 1024 * 1024: + raise protocol_failure(stage) + value = json.loads(data) + if not isinstance(value, dict): + raise protocol_failure(stage) + return value + + async def _upload(self, client, config, item, data): + value = await self._json(client, config, 'POST', BASE + '/files/generate-upload-url', 'prepare', + json={'content_type': item['mimeType']}) + public_url = _https_url(value['public_url'], 'prepare') + upload_url = _https_url(value['upload_url'], 'prepare') + pinned, host_headers, extensions = await public_target(upload_url, schemes=('https',), + unsafe=lambda: protocol_failure('prepare'), unresolved=lambda: transport_failure('prepare')) + headers = httpx.Headers(value.get('upload_headers') or {}) + if any(key in headers for key in ('authorization', 'proxy-authorization', 'cookie', 'host', 'connection', 'transfer-encoding')): + raise protocol_failure('prepare') + headers.update(host_headers) + headers.setdefault('Content-Type', item['mimeType']) + extensions['model_secrets'] = _credentials(config) + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.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=_credentials(config)) + return public_url + + async def generate(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + self.validate(task['kind'], config) + if recovery_cache is None: + raise protocol_failure('prepare') + stage = 'prepare' + try: + record = await asyncio.to_thread(recovery_cache.submission) + expected_path = f"/{MODEL}/{task['parameters']['operation']}" + if record is None: + if task.get('externalTaskId'): + raise protocol_failure('poll') + record = dict(key=task['id'], path=expected_path, payload=None) + await asyncio.to_thread(recovery_cache.save_submission, record) + if (record.get('key') != task['id'] or record.get('path') != expected_path + or record.get('payload') is not None and not isinstance(record['payload'], dict)): + raise protocol_failure(stage) + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.transport, + trust_env=trust_environment(BASE, config=config), timeout=httpx.Timeout(240, connect=15), follow_redirects=False) as client: + remote = record.get('remote') + if remote is None: + if task.get('externalTaskId'): + raise protocol_failure('poll') + if record['payload'] is None: + prepared = await asyncio.to_thread(self.prepare_inputs, task['projectId'], task, config) + urls = {} + 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') + urls[item['assetId']] = await self._upload(client, config, item, data) + path, body = self.payload(config, task, prepared, urls) + if path != record['path']: + raise protocol_failure(stage) + record['payload'] = body + record['credential'] = hashlib.sha256(_credentials(config)[1].encode()).hexdigest() + # Freeze exact URLs, order and omitted fields before the billable POST. + await asyncio.to_thread(recovery_cache.save_submission, record) + if record.get('credential') != hashlib.sha256(_credentials(config)[1].encode()).hexdigest(): + # Idempotency is account-scoped. A different key ID could + # belong to another account and charge for a second job. + raise protocol_failure('prepare', message='原请求的 Higgsfield API Key ID 已变化,请恢复原连接后再恢复任务。') + stage = 'submit' + value = await self._json(client, config, 'POST', BASE + record['path'], stage, + json=record['payload'], idempotency_key=record['key']) + remote = _task_urls(value, _credentials(config), stage) + record['remote'] = remote + await asyncio.to_thread(recovery_cache.save_submission, record) + remote = _task_urls(remote, _credentials(config), 'poll') + if task.get('externalTaskId') and task['externalTaskId'] != remote['request_id']: + raise protocol_failure('poll') + await submitted(remote['request_id']) + stage = 'poll' + while True: + value = await self._retry_read(lambda: self._json(client, config, 'GET', remote['status_url'], stage)) + if value.get('request_id') != remote['request_id']: + raise protocol_failure(stage) + status = value.get('status') + if status == 'completed': + url = _https_url(value['video']['url'], 'download') + if result_ready: + await result_ready('mp4', url) + stage = 'download' + return await self.resume_result(config, 'mp4', url) + if status in {'failed', 'nsfw', 'canceled', 'cancelled'}: + failure = {**value, 'status': 'cancelled' if status in {'canceled', 'cancelled'} else 'failed'} + if status == 'nsfw': + failure['error'] = {'code': 'moderation_blocked'} + raise provider_failure(failure, stage=stage, http_status=200, secrets=_credentials(config)) + if status not in {'queued', 'in_progress'}: + 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): + try: + _https_url(url, 'download') + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.transport, + trust_env=trust_environment(url, config=config), timeout=httpx.Timeout(240, connect=15)) as client: + return suffix, await self._download(client, url, secrets=_credentials(config), public_only=True) + except httpx.TimeoutException: + raise transport_failure('download', timeout=True) from None + except httpx.HTTPError: + raise transport_failure('download') from None + except (ValueError, TypeError): + raise protocol_failure('download') from None + + async def cancel(self, config, external_id, *, recovery_cache=None): + try: + record = await asyncio.to_thread(recovery_cache.submission) if recovery_cache else None + remote = _task_urls((record or {}).get('remote') or {}, _credentials(config), 'cancel') + if remote['request_id'] != external_id: + raise protocol_failure('cancel') + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.transport, + trust_env=trust_environment(BASE, config=config), timeout=15, follow_redirects=False) as client: + await self._json(client, config, 'POST', remote['cancel_url'], 'cancel') + except httpx.TimeoutException: + raise transport_failure('cancel', timeout=True) from None + except httpx.HTTPError: + raise transport_failure('cancel') from None + except (ValueError, TypeError, KeyError, AttributeError): + raise protocol_failure('cancel') from None diff --git a/packages/core/src/opendirector/integrations/model_capabilities.py b/packages/core/src/opendirector/integrations/model_capabilities.py index 2305b9048..c4a3ceeb2 100644 --- a/packages/core/src/opendirector/integrations/model_capabilities.py +++ b/packages/core/src/opendirector/integrations/model_capabilities.py @@ -8,6 +8,7 @@ from opendirector.domain.minimax_models import MINIMAX_MODELS 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.video_capabilities import VideoCapabilities from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment from opendirector.integrations.volcengine import endpoint @@ -17,6 +18,8 @@ async def read_service_models(config, transport=None): + if config.get('protocol') == 'higgsfield_open': + return [{'id': MAGI2_MODEL, 'videoCapabilities': magi2_capabilities()}] if config.get('protocol') == 'bigmodel_video': return [{'id': COGVIDEO_MODEL, 'videoCapabilities': cogvideo_capabilities()}] if config.get('protocol') == 'kling_video': diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 2073864e1..da687d58f 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -18,6 +18,7 @@ from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.minimax_video import MinimaxVideoGeneration 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.fasth3 import generation_fields as fasth3_generation_fields @@ -36,6 +37,7 @@ def __init__(self, store, transport=None, poll_interval=3, retry_delays=(0.5, 1. self.minimax_video = MinimaxVideoGeneration(store, transport, poll_interval) 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.vllm_omni = VllmOmniGeneration(store, transport, poll_interval) self.vllm_omni_image = VllmOmniImageGeneration(store, transport, poll_interval) self.minimax_image = MinimaxH3Images(transport, poll_interval) @@ -46,6 +48,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') == 'higgsfield_open': + return self.higgsfield_open if config and config.get('protocol') == 'bigmodel_video': return self.bigmodel_video if config and config.get('protocol') == 'kling_video': @@ -126,7 +130,9 @@ async def resume_result(self, config, suffix, url): except (httpx.InvalidURL, ValueError, TypeError, KeyError, AttributeError): raise protocol_failure('download') from None - async def generate(self, config, task, submitted, *, result_ready=None): + async def generate(self, config, task, submitted, *, result_ready=None, recovery_cache=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 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')) @@ -282,7 +288,9 @@ async def _score(self, task, params): return await VllmOmniScore(self.transport).score(config, ScoreRequest( data, meta['name'], melody_only=params['score_mode'] == 'melody')) - async def cancel(self, config, external_id): + async def cancel(self, config, external_id, *, recovery_cache=None): + if config.get('protocol') == 'higgsfield_open': + return await self.higgsfield_open.cancel(config, external_id, recovery_cache=recovery_cache) adapter = self._profile_adapter(config) if adapter: return await adapter.cancel(config, external_id) diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 0a804e366..4410a6a47 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -10,6 +10,7 @@ import { effectiveVideoMode, generateAudioOptions, referenceByteLimit, + promptOptionalWithMedia, resolutionChoices, } from "../contracts/ruleFacts.generated.ts"; import { subjectReferenceNodes } from "../canvas/subjectReferences.ts"; @@ -43,6 +44,9 @@ export interface InputRules { maxImages: number; imageBytes?: number; videoBytes?: number; + audioBytes?: number | null; + referenceMediaMinSeconds?: number | null; + referenceMediaSeconds?: number | null; requestBytes?: number; maxPromptCharacters?: number | null; voiceRequired?: boolean | null; @@ -75,6 +79,7 @@ export interface ModelConfig { protocol: | "openai" | "volcengine" + | "higgsfield_open" | "minimax_video_v2" | "kling_video" | "bigmodel_video" @@ -586,7 +591,11 @@ export function backendBlocker( if (capabilityIssue) return capabilityIssue; if ( !settings.prompt.trim() && - !hasImplicitTextPrompt(settings, [...incoming, ...pinned], config) + !hasImplicitTextPrompt(settings, [...incoming, ...pinned], config) && + !promptOptionalWithMedia({ + profile: config.inputRules.profile, + hasMedia: references.some((ref) => ["image", "video", "audio"].includes(ref.node.data.kind)), + }) ) return settings.mode !== "audio" ? tNow("errors.rules.promptRequired") @@ -774,12 +783,24 @@ export function referenceBudgetIssue( kind: source.type, imageBytes: config.inputRules.imageBytes, videoBytes: config.inputRules.videoBytes, + audioBytes: config.inputRules.audioBytes, }); if (size > limit) return tNow("errors.rules.referenceFileSize"); total += size; } if (total > (config.inputRules.requestBytes ?? Infinity)) return tNow("errors.rules.referenceBudget"); + const maximumSeconds = config.inputRules.referenceMediaSeconds; + if (maximumSeconds != null) { + const minimumSeconds = config.inputRules.referenceMediaMinSeconds ?? 0; + for (const kind of ["video", "audio"] as const) { + const seconds = usable.filter((source) => source.type === kind) + .map((source) => source.data.media?.durationSeconds); + if (seconds.some((value) => value == null || value < minimumSeconds) || + seconds.reduce((sum, value) => sum + (value ?? 0), 0) > maximumSeconds) + return tNow("errors.rules.referenceDuration", { minimum: minimumSeconds, maximum: maximumSeconds }); + } + } for (const [kind, maximum] of [ ["image", config.inputRules.maxImages], ["video", config.inputRules.maxVideos], diff --git a/src/canvas/ModelCapabilityCard.tsx b/src/canvas/ModelCapabilityCard.tsx index 65ae6d567..b7f1f0176 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"].includes( + const official = ["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open"].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 === "higgsfield_open" + ? "models.service.higgsfieldSummary" : connection.protocol === "kling_video" ? modelId === "kling-4.0-flash" ? "models.service.klingFlashSummary" @@ -196,6 +198,8 @@ export function ModelCapabilityCard({ {t( connection.protocol === "bigmodel_video" ? "models.service.bigmodelVideoReferences" + : connection.protocol === "higgsfield_open" + ? "models.service.higgsfieldReferences" : connection.protocol === "kling_video" ? "models.service.klingReferences" : "models.service.officialReferences", diff --git a/src/canvas/ModelServiceForm.tsx b/src/canvas/ModelServiceForm.tsx index 3d23f206a..7311da83d 100644 --- a/src/canvas/ModelServiceForm.tsx +++ b/src/canvas/ModelServiceForm.tsx @@ -42,6 +42,7 @@ const PROTOCOLS: Record< ["vllm_omni", "models.protocolOption.videos"], ["minimax_video_v2", "models.protocolOption.minimaxVideo"], ["kling_video", "models.protocolOption.klingVideo"], + ["higgsfield_open", "models.protocolOption.higgsfieldOpen"], ["bigmodel_video", "models.protocolOption.bigmodelVideo"], ["volcengine", "models.protocolOption.volcengine"], ["vllm_omni_segmentation", "models.protocolOption.segmentation"], @@ -164,7 +165,7 @@ export function ModelServiceForm({ setValue((current) => ({ ...current, ...patch, - ...(["minimax_video_v2", "kling_video", "bigmodel_video"].includes(patch.protocol ?? "") + ...(["minimax_video_v2", "kling_video", "bigmodel_video", "higgsfield_open"].includes(patch.protocol ?? "") ? ({ connectionType: "api", authMode: "bearer", @@ -508,6 +509,8 @@ export function ModelServiceForm({ ? t("models.service.noAuthPlaceholder") : hasSavedKey ? t("models.service.savedKeyPlaceholder") + : value.protocol === "higgsfield_open" + ? "KEY_ID:KEY_SECRET" : t("models.service.apiKeyPlaceholder") } onChange={(event) => update({ apiKey: event.target.value })} @@ -527,6 +530,9 @@ export function ModelServiceForm({ {["minimax_video_v2", "kling_video", "bigmodel_video"].includes(value.protocol) && (

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

)} + {value.protocol === "higgsfield_open" && ( +

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

+ )} {mode === "video" && - (!backend || config?.protocol === "volcengine") && ( + (!backend || config?.protocol === "volcengine" || config?.protocol === "higgsfield_open") && (